Search in sources :

Example 1 with ApplicationScopeSettings

use of io.gravitee.am.model.application.ApplicationScopeSettings in project gravitee-access-management by gravitee-io.

the class DynamicClientRegistrationRequestTest method setUp.

@Before
public void setUp() {
    // Build Object to patch
    toPatch = new Client();
    toPatch.setClientName("oldName");
    toPatch.setClientSecret("expectedSecret");
    toPatch.setClientUri("shouldDisappear");
    toPatch.setScopeSettings(Arrays.asList(new ApplicationScopeSettings("scopeA"), new ApplicationScopeSettings("scopeB")));
    toPatch.setAccessTokenValiditySeconds(7200);
    toPatch.setRefreshTokenValiditySeconds(3600);
    toPatch.setResponseTypes(Arrays.asList("old", "old2"));
    toPatch.setDefaultMaxAge(1);
    // Build patcher
    patcher = new DynamicClientRegistrationRequest();
    patcher.setClientName(Optional.of("expectedClientName"));
    patcher.setClientUri(Optional.empty());
    patcher.setGrantTypes(Optional.of(Arrays.asList("grant1", "grant2")));
    patcher.setResponseTypes(Optional.empty());
    patcher.setScope(Optional.of("scope1 scope2"));
}
Also used : ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) Client(io.gravitee.am.model.oidc.Client) Before(org.junit.Before)

Example 2 with ApplicationScopeSettings

use of io.gravitee.am.model.application.ApplicationScopeSettings in project gravitee-access-management by gravitee-io.

the class DynamicClientRegistrationServiceTest method create_defaultScopes_notUsed.

@Test
public void create_defaultScopes_notUsed() {
    DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest();
    request.setRedirectUris(Optional.empty());
    request.setScope(Optional.of("openid not allowed"));
    OIDCSettings oidc = OIDCSettings.defaultSettings();
    oidc.getClientRegistrationSettings().setDefaultScopes(Arrays.asList("phone", "email"));
    when(domain.getOidc()).thenReturn(oidc);
    TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test();
    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValue(client -> this.defaultAssertion(client) && client.getScopeSettings().size() == 3 && client.getScopeSettings().stream().map(ApplicationScopeSettings::getScope).collect(Collectors.toList()).containsAll(Arrays.asList("openid", "not", "allowed")));
}
Also used : ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) WebClient(io.vertx.reactivex.ext.web.client.WebClient) Client(io.gravitee.am.model.oidc.Client) OIDCSettings(io.gravitee.am.model.oidc.OIDCSettings) Test(org.junit.Test)

Example 3 with ApplicationScopeSettings

use of io.gravitee.am.model.application.ApplicationScopeSettings in project gravitee-access-management by gravitee-io.

the class ScopeServiceImpl method delete.

@Override
public Completable delete(String scopeId, boolean force, User principal) {
    LOGGER.debug("Delete scope {}", scopeId);
    return scopeRepository.findById(scopeId).switchIfEmpty(Maybe.error(new ScopeNotFoundException(scopeId))).flatMapSingle(scope -> {
        if (scope.isSystem() && !force) {
            throw new SystemScopeDeleteException(scopeId);
        }
        return Single.just(scope);
    }).flatMapCompletable(scope -> Completable.fromSingle(// 1_ Remove permissions from role
    roleService.findByDomain(scope.getDomain()).flatMapObservable(roles -> Observable.fromIterable(roles.stream().filter(role -> role.getOauthScopes() != null && role.getOauthScopes().contains(scope.getKey())).collect(Collectors.toList()))).flatMapSingle(role -> {
        role.getOauthScopes().remove(scope.getKey());
        UpdateRole updatedRole = new UpdateRole();
        updatedRole.setName(role.getName());
        updatedRole.setDescription(role.getDescription());
        updatedRole.setPermissions(role.getOauthScopes());
        // Save role
        return roleService.update(scope.getDomain(), role.getId(), updatedRole);
    }).toList()).andThen(// 2_ Remove scopes from application
    applicationService.findByDomain(scope.getDomain()).flatMapObservable(applications -> Observable.fromIterable(applications.stream().filter(application -> {
        if (application.getSettings() == null) {
            return false;
        }
        if (application.getSettings().getOauth() == null) {
            return false;
        }
        ApplicationOAuthSettings oAuthSettings = application.getSettings().getOauth();
        return oAuthSettings.getScopeSettings() != null && !oAuthSettings.getScopeSettings().stream().filter(s -> s.getScope().equals(scope.getKey())).findFirst().isEmpty();
    }).collect(Collectors.toList()))).flatMapSingle(application -> {
        // Remove scope from application
        final List<ApplicationScopeSettings> cleanScopes = application.getSettings().getOauth().getScopeSettings().stream().filter(s -> !s.getScope().equals(scope.getKey())).collect(Collectors.toList());
        application.getSettings().getOauth().setScopeSettings(cleanScopes);
        // Then update
        return applicationService.update(application);
    }).toList()).toCompletable().andThen(scopeApprovalRepository.deleteByDomainAndScopeKey(scope.getDomain(), scope.getKey())).andThen(scopeRepository.delete(scopeId)).andThen(Completable.fromSingle(eventService.create(new Event(Type.SCOPE, new Payload(scope.getId(), ReferenceType.DOMAIN, scope.getDomain(), Action.DELETE))))).doOnComplete(() -> auditService.report(AuditBuilder.builder(ScopeAuditBuilder.class).principal(principal).type(EventType.SCOPE_DELETED).scope(scope))).doOnError(throwable -> auditService.report(AuditBuilder.builder(ScopeAuditBuilder.class).principal(principal).type(EventType.SCOPE_DELETED).throwable(throwable)))).onErrorResumeNext(ex -> {
        if (ex instanceof AbstractManagementException) {
            return Completable.error(ex);
        }
        LOGGER.error("An error occurs while trying to delete scope: {}", scopeId, ex);
        return Completable.error(new TechnicalManagementException(String.format("An error occurs while trying to delete scope: %s", scopeId), ex));
    });
}
Also used : java.util(java.util) Completable(io.reactivex.Completable) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Single(io.reactivex.Single) Event(io.gravitee.am.model.common.event.Event) Type(io.gravitee.am.common.event.Type) io.gravitee.am.service.exception(io.gravitee.am.service.exception) User(io.gravitee.am.identityprovider.api.User) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) ReferenceType(io.gravitee.am.model.ReferenceType) Observable(io.reactivex.Observable) URI(java.net.URI) Scope(io.gravitee.am.model.oauth2.Scope) io.gravitee.am.service(io.gravitee.am.service) Action(io.gravitee.am.common.event.Action) Page(io.gravitee.am.model.common.Page) Logger(org.slf4j.Logger) ApplicationOAuthSettings(io.gravitee.am.model.application.ApplicationOAuthSettings) MalformedURLException(java.net.MalformedURLException) ScopeRepository(io.gravitee.am.repository.management.api.ScopeRepository) EventType(io.gravitee.am.common.audit.EventType) Collectors(java.util.stream.Collectors) RandomString(io.gravitee.am.common.utils.RandomString) io.gravitee.am.service.model(io.gravitee.am.service.model) Component(org.springframework.stereotype.Component) Payload(io.gravitee.am.model.common.event.Payload) ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) ScopeAuditBuilder(io.gravitee.am.service.reporter.builder.management.ScopeAuditBuilder) Lazy(org.springframework.context.annotation.Lazy) ScopeApprovalRepository(io.gravitee.am.repository.oauth2.api.ScopeApprovalRepository) ApplicationOAuthSettings(io.gravitee.am.model.application.ApplicationOAuthSettings) ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) Event(io.gravitee.am.model.common.event.Event) Payload(io.gravitee.am.model.common.event.Payload) ScopeAuditBuilder(io.gravitee.am.service.reporter.builder.management.ScopeAuditBuilder)

Example 4 with ApplicationScopeSettings

use of io.gravitee.am.model.application.ApplicationScopeSettings in project gravitee-access-management by gravitee-io.

the class PatchApplicationScopeSettings method patch.

public ApplicationScopeSettings patch(ApplicationScopeSettings _toPatch) {
    ApplicationScopeSettings toPatch = _toPatch == null ? new ApplicationScopeSettings() : new ApplicationScopeSettings(_toPatch);
    SetterUtils.safeSet(toPatch::setScope, this.getScope());
    SetterUtils.safeSet(toPatch::setDefaultScope, this.getDefaultScope());
    SetterUtils.safeSet(toPatch::setScopeApproval, this.getScopeApproval());
    return toPatch;
}
Also used : ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings)

Example 5 with ApplicationScopeSettings

use of io.gravitee.am.model.application.ApplicationScopeSettings in project gravitee-access-management by gravitee-io.

the class AbstractRequestResolver method resolveAuthorizedScopes.

/**
 * If the client omits the scope parameter when requesting authorization, the authorization server MUST either process the
 * request using a pre-defined default value or fail the request indicating an invalid scope.
 * See <a href="https://tools.ietf.org/html/rfc6749#section-3.3">3.3. Access Token Scope</a>
 *
 * @param request the request to resolve
 * @param client the client which trigger the request
 * @return the oauth 2.0 request
 */
protected Single<R> resolveAuthorizedScopes(R request, Client client, User endUser) {
    final Set<String> requestScopes = request.getScopes();
    Set<String> clientResolvedScopes = new HashSet<>();
    Set<String> resolvedScopes = new HashSet<>();
    Set<String> invalidScopes = new HashSet<>();
    // client scopes
    if (client.getScopeSettings() != null && !client.getScopeSettings().isEmpty()) {
        final List<String> clientScopes = client.getScopeSettings().stream().map(ApplicationScopeSettings::getScope).collect(Collectors.toList());
        final List<String> defaultScopes = client.getScopeSettings().stream().filter(ApplicationScopeSettings::isDefaultScope).map(ApplicationScopeSettings::getScope).collect(Collectors.toList());
        final List<String> parameterizedScopes = this.scopeManager == null ? new ArrayList<>() : client.getScopeSettings().stream().map(ApplicationScopeSettings::getScope).filter(scopeManager::isParameterizedScope).collect(Collectors.toList());
        // no requested scope, set default client scopes to the request
        if (requestScopes == null || requestScopes.isEmpty()) {
            resolvedScopes.addAll(new HashSet<>(defaultScopes));
        } else {
            // filter the actual scopes granted by the client
            for (String scope : requestScopes) {
                if (clientScopes.contains(scope) || ParameterizedScopeUtils.isParameterizedScope(parameterizedScopes, scope)) {
                    resolvedScopes.add(scope);
                    clientResolvedScopes.add(scope);
                } else {
                    invalidScopes.add(scope);
                }
            }
        }
    }
    // user scopes
    if (endUser != null && client.isEnhanceScopesWithUserPermissions()) {
        Set<Role> roles = endUser.getRolesPermissions();
        if (roles != null && !roles.isEmpty()) {
            Set<String> permissions = roles.stream().map(role -> role.getOauthScopes() != null ? role.getOauthScopes() : Collections.<String>emptyList()).flatMap(List::stream).collect(Collectors.toSet());
            if (requestScopes != null) {
                // filter the actual scopes granted by the resource owner
                requestScopes.forEach(scope -> {
                    if (!permissions.contains(scope) && !clientResolvedScopes.contains(scope)) {
                        invalidScopes.add(scope);
                    }
                });
            }
            // The request must be enhanced with all of user's permissions
            invalidScopes.removeAll(permissions);
            resolvedScopes.addAll(permissions);
        }
    }
    if (!invalidScopes.isEmpty()) {
        return Single.error(new InvalidScopeException("Invalid scope(s): " + invalidScopes.stream().collect(Collectors.joining(SCOPE_DELIMITER))));
    }
    if (resolvedScopes.isEmpty() && (requestScopes != null && !requestScopes.isEmpty())) {
        return Single.error(new InvalidScopeException("Invalid scope(s): " + requestScopes.stream().collect(Collectors.joining(SCOPE_DELIMITER))));
    }
    // only put default values if there is no requested scopes
    if (requestScopes == null || requestScopes.isEmpty()) {
        request.setScopes(resolvedScopes);
    }
    return Single.just(request);
}
Also used : Role(io.gravitee.am.model.Role) ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) InvalidScopeException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidScopeException)

Aggregations

ApplicationScopeSettings (io.gravitee.am.model.application.ApplicationScopeSettings)47 Client (io.gravitee.am.model.oidc.Client)39 Test (org.junit.Test)36 AuthorizationRequest (io.gravitee.am.gateway.handler.oauth2.service.request.AuthorizationRequest)13 Role (io.gravitee.am.model.Role)10 User (io.vertx.reactivex.ext.auth.User)10 User (io.gravitee.am.model.User)9 ApplicationOAuthSettings (io.gravitee.am.model.application.ApplicationOAuthSettings)5 JWTAuthorizationCodeResponse (io.gravitee.am.gateway.handler.oauth2.service.response.jwt.JWTAuthorizationCodeResponse)4 OIDCSettings (io.gravitee.am.model.oidc.OIDCSettings)4 Single (io.reactivex.Single)4 TokenRequest (io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest)3 ApplicationSettings (io.gravitee.am.model.application.ApplicationSettings)3 Event (io.gravitee.am.model.common.event.Event)3 EventType (io.gravitee.am.common.audit.EventType)2 Action (io.gravitee.am.common.event.Action)2 Type (io.gravitee.am.common.event.Type)2 GrantType (io.gravitee.am.common.oauth2.GrantType)2 RandomString (io.gravitee.am.common.utils.RandomString)2 AccessToken (io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken)2