Search in sources :

Example 16 with ForbiddenException

use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.

the class TokenGenerationService method validateAssertionSubjectSession.

private SSOToken validateAssertionSubjectSession(TokenGenerationServiceInvocationState invocationState) throws ForbiddenException {
    SSOToken subjectToken;
    SSOTokenManager tokenManager;
    try {
        tokenManager = SSOTokenManager.getInstance();
        subjectToken = tokenManager.createSSOToken(invocationState.getSsoTokenString());
    } catch (SSOException e) {
        logger.debug("Exception caught creating the SSO token from the token string, almost certainly " + "because token string does not correspond to a valid session: " + e);
        throw new ForbiddenException(e.toString(), e);
    }
    if (!tokenManager.isValidToken(subjectToken)) {
        throw new ForbiddenException("SSO token string does not correspond to a valid SSOToken");
    }
    try {
        AMIdentity subjectIdentity = IdUtils.getIdentity(subjectToken);
        String invocationRealm = invocationState.getRealm();
        String subjectSessionRealm = DNMapper.orgNameToRealmName(subjectIdentity.getRealm());
        logger.debug("TokenGenerationService:validateAssertionSubjectSession subjectRealm " + subjectSessionRealm + " invocation realm: " + invocationRealm);
        if (!invocationRealm.equalsIgnoreCase(subjectSessionRealm)) {
            logger.error("TokenGenerationService:validateAssertionSubjectSession realms do not match: Subject realm : " + subjectSessionRealm + " invocation realm: " + invocationRealm);
            throw new ForbiddenException("SSO token subject realm does not match invocation realm");
        }
    } catch (SSOException | IdRepoException e) {
        logger.error("TokenGenerationService:validateAssertionSubjectSession error while validating identity : " + e);
        throw new ForbiddenException(e.toString(), e);
    }
    return subjectToken;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Example 17 with ForbiddenException

use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method updatePolicy.

/**
     * {@inheritDoc}
     */
@Override
public //TODO need to check if need to delete backend policies
Promise<UmaPolicy, ResourceException> updatePolicy(//TODO need to check if need to delete backend policies
final Context context, //TODO need to check if need to delete backend policies
final String resourceSetId, JsonValue policy) {
    final UmaPolicy updatedUmaPolicy;
    final ResourceSetDescription resourceSet;
    try {
        resourceSet = getResourceSet(getRealm(context), resourceSetId);
        updatedUmaPolicy = UmaPolicy.valueOf(resourceSet, resolveUsernameToUID(context, policy));
        boolean canShare = canUserShareResourceSet(resourceSet.getResourceOwnerId(), contextHelper.getUserId(context), resourceSet.getClientId(), getRealm(context), resourceSet.getId(), updatedUmaPolicy.getScopes());
        if (!canShare) {
            return new ForbiddenException().asPromise();
        }
        validateScopes(resourceSet, updatedUmaPolicy.getScopes());
    } catch (ResourceException e) {
        return e.asPromise();
    }
    return internalReadPolicy(context, resourceSetId).thenAsync(beforeResourceSharedModified(updatedUmaPolicy)).thenOnResult(new ResultHandler<UmaPolicy>() {

        @Override
        public void handleResult(UmaPolicy currentUmaPolicy) {
            Set<String> modifiedScopes = new HashSet<>(updatedUmaPolicy.getScopes());
            modifiedScopes.retainAll(currentUmaPolicy.getScopes());
            Set<String> removedScopes = new HashSet<>(currentUmaPolicy.getScopes());
            removedScopes.removeAll(modifiedScopes);
            for (JsonValue policy : currentUmaPolicy.asUnderlyingPolicies(contextHelper.getUserId(context))) {
                for (String scope : removedScopes) {
                    if (policy.get("actionValues").isDefined(scope)) {
                        policyResourceDelegate.queryPolicies(context, Requests.newQueryRequest("").setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("createdBy"), contextHelper.getUserUid(context)), QueryFilter.equalTo(new JsonPointer("name"), policy.get("name").asString())))).thenAsync(new DeleteOldPolicyFunction(context));
                    }
                }
            }
        }
    }).thenOnResult(new ResultHandler<UmaPolicy>() {

        @Override
        public void handleResult(UmaPolicy currentUmaPolicy) {
            Set<String> modifiedScopes = new HashSet<>(currentUmaPolicy.getScopes());
            modifiedScopes.retainAll(updatedUmaPolicy.getScopes());
            Set<String> deletedScopes = new HashSet<>(updatedUmaPolicy.getScopes());
            deletedScopes.removeAll(modifiedScopes);
            for (JsonValue policy : updatedUmaPolicy.asUnderlyingPolicies(contextHelper.getUserId(context))) {
                for (String scope : deletedScopes) {
                    if (policy.get("actionValues").isDefined(scope)) {
                        policyResourceDelegate.createPolicies(context, singleton(policy));
                    }
                }
            }
        }
    }).thenOnResult(new ResultHandler<UmaPolicy>() {

        @Override
        public void handleResult(UmaPolicy currentUmaPolicy) {
            String uid = contextHelper.getUserId(context);
            Set<String> underlyingPolicyIds = new HashSet<>(currentUmaPolicy.getUnderlyingPolicyIds());
            Set<JsonValue> newUnderlyingPolicies = updatedUmaPolicy.asUnderlyingPolicies(uid);
            for (JsonValue value : newUnderlyingPolicies) {
                underlyingPolicyIds.remove(value.get("name").asString());
            }
            policyResourceDelegate.deletePolicies(context, underlyingPolicyIds);
        }
    }).thenAsync(new UpdatePolicyGraphStatesFunction<UmaPolicy>(resourceSet, context)).thenAsync(new UpdateUmaPolicyFunction(context, updatedUmaPolicy, resourceSetId, resourceSet));
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) Set(java.util.Set) HashSet(java.util.HashSet) JsonValue(org.forgerock.json.JsonValue) JsonPointer(org.forgerock.json.JsonPointer) ResultHandler(org.forgerock.util.promise.ResultHandler) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) ResourceException(org.forgerock.json.resource.ResourceException) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) HashSet(java.util.HashSet)

Example 18 with ForbiddenException

use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method createPolicy.

/**
     * {@inheritDoc}
     */
@Override
public Promise<UmaPolicy, ResourceException> createPolicy(final Context context, JsonValue policy) {
    final UmaPolicy umaPolicy;
    final ResourceSetDescription resourceSet;
    final String userId = contextHelper.getUserId(context);
    String realm = getRealm(context);
    try {
        String policyId = UmaPolicy.idOf(policy);
        resourceSet = getResourceSet(realm, policyId);
        umaPolicy = UmaPolicy.valueOf(resourceSet, resolveUsernameToUID(context, policy));
        boolean canShare = canUserShareResourceSet(resourceSet.getResourceOwnerId(), userId, resourceSet.getClientId(), realm, resourceSet.getId(), umaPolicy.getScopes());
        if (!canShare) {
            return new ForbiddenException().asPromise();
        }
        validateScopes(resourceSet, umaPolicy.getScopes());
        verifyPolicyDoesNotAlreadyExist(context, resourceSet);
    } catch (ResourceException e) {
        return e.asPromise();
    }
    return beforeResourceShared(umaPolicy).thenAsync(new AsyncFunction<UmaPolicy, List<ResourceResponse>, ResourceException>() {

        @Override
        public Promise<List<ResourceResponse>, ResourceException> apply(UmaPolicy umaPolicy) {
            return policyResourceDelegate.createPolicies(context, umaPolicy.asUnderlyingPolicies(userId));
        }
    }).thenAlways(afterResourceShared(umaPolicy)).thenAsync(new UpdatePolicyGraphStatesFunction<List<ResourceResponse>>(resourceSet, context)).thenAsync(new AuditAndProduceUmaPolicyFunction(resourceSet, context));
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) ResourceException(org.forgerock.json.resource.ResourceException) List(java.util.List) ArrayList(java.util.ArrayList) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) AsyncFunction(org.forgerock.util.AsyncFunction)

Example 19 with ForbiddenException

use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.

the class IdentityServicesImpl method create.

/**
     * Creates a new {@code AMIdentity} in the identity repository with the
     * details specified in {@code identity}.
     *
     * @param identity The identity details.
     * @param admin The admin token.
     * @throws ResourceException If a problem occurs.
     */
public void create(IdentityDetails identity, SSOToken admin) throws ResourceException {
    Reject.ifNull(identity, admin);
    // Obtain identity details & verify
    String idName = identity.getName();
    String idType = identity.getType();
    String realm = identity.getRealm();
    if (StringUtils.isEmpty(idName)) {
        // TODO: add a message to the exception
        throw new BadRequestException("Identity name not provided");
    }
    if (StringUtils.isEmpty(idType)) {
        idType = "user";
    }
    if (realm == null) {
        realm = "/";
    }
    try {
        // Obtain IdRepo to create validate IdType & operations
        IdType objectIdType = getIdType(idType);
        AMIdentityRepository repo = getRepo(admin, realm);
        if (!isOperationSupported(repo, objectIdType, IdOperation.CREATE)) {
            // TODO: add message to exception
            throw new UnsupportedOperationException("Unsupported: Type: " + idType + " Operation: CREATE");
        }
        // Obtain creation attributes
        Map<String, Set<String>> idAttrs = asMap(identity.getAttributes());
        // Create the identity, special case of Agents to merge
        // and validate the attributes
        AMIdentity amIdentity;
        if (isTypeAgent(objectIdType)) {
            createAgent(idAttrs, objectIdType, idType, idName, realm, admin);
        } else {
            // Create other identites like User, Group, Role, etc.
            amIdentity = repo.createIdentity(objectIdType, idName, idAttrs);
            // Process roles, groups & memberships
            if (IdType.USER.equals(objectIdType)) {
                Set<String> roles = asSet(identity.getRoleList());
                if (roles != null && !roles.isEmpty()) {
                    if (!isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
                        // TODO: localize message
                        throw new UnsupportedOperationException("Unsupported: Type: " + IdType.ROLE + " Operation: EDIT");
                    }
                    for (String roleName : roles) {
                        AMIdentity role = fetchAMIdentity(repo, IdType.ROLE, roleName, false);
                        if (role != null) {
                            role.addMember(amIdentity);
                            role.store();
                        }
                    }
                }
                Set<String> groups = asSet(identity.getGroupList());
                if (groups != null && !groups.isEmpty()) {
                    if (!isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
                        // TODO: localize message
                        throw new UnsupportedOperationException("Unsupported: Type: " + IdType.GROUP + " Operation: EDIT");
                    }
                    for (String groupName : groups) {
                        AMIdentity group = fetchAMIdentity(repo, IdType.GROUP, groupName, false);
                        if (group != null) {
                            group.addMember(amIdentity);
                            group.store();
                        }
                    }
                }
            }
            if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
                Set<String> members = asSet(identity.getMemberList());
                if (members != null) {
                    if (IdType.GROUP.equals(objectIdType) && !isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
                        throw new ForbiddenException("Token is not authorized");
                    }
                    if (IdType.ROLE.equals(objectIdType) && !isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
                        throw new ForbiddenException("Token is not authorized");
                    }
                    for (String memberName : members) {
                        AMIdentity user = fetchAMIdentity(repo, IdType.USER, memberName, false);
                        if (user != null) {
                            amIdentity.addMember(user);
                        }
                    }
                    amIdentity.store();
                }
            }
        }
    } catch (IdRepoDuplicateObjectException ex) {
        throw new ConflictException("Resource already exists", ex);
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:create", e);
        if (IdRepoErrorCode.ACCESS_DENIED.equals(e.getErrorCode())) {
            throw new ForbiddenException(e.getMessage());
        } else if (e.getLdapErrorIntCode() == LDAPConstants.LDAP_CONSTRAINT_VIOLATION) {
            debug.error(e.getMessage(), e);
            throw new BadRequestException();
        } else {
            throw new NotFoundException(e.getMessage());
        }
    } catch (SSOException | SMSException | ConfigurationException | MalformedURLException | UnsupportedOperationException e) {
        debug.error("IdentityServicesImpl:create", e);
        throw new NotFoundException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:create", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) MalformedURLException(java.net.MalformedURLException) Set(java.util.Set) HashSet(java.util.HashSet) ConflictException(org.forgerock.json.resource.ConflictException) SMSException(com.sun.identity.sm.SMSException) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ConfigurationException(com.sun.identity.common.configuration.ConfigurationException) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) IdRepoDuplicateObjectException(com.sun.identity.idm.IdRepoDuplicateObjectException) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) BadRequestException(org.forgerock.json.resource.BadRequestException)

Example 20 with ForbiddenException

use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.

the class IdentityServicesImpl method update.

/**
     * Updates an {@code AMIdentity} in the identity repository with the
     * details specified in {@code identity}.
     *
     * @param identity The updated identity details.
     * @param admin The admin token.
     * @throws ResourceException If a problem occurs.
     */
public void update(IdentityDetails identity, SSOToken admin) throws ResourceException {
    String idName = identity.getName();
    String idType = identity.getType();
    String realm = identity.getRealm();
    if (StringUtils.isEmpty(idName)) {
        // TODO: add a message to the exception
        throw new BadRequestException("");
    }
    if (StringUtils.isEmpty(idType)) {
        idType = "user";
    }
    if (realm == null) {
        realm = "";
    }
    try {
        IdType objectIdType = getIdType(idType);
        AMIdentityRepository repo = getRepo(admin, realm);
        if (!isOperationSupported(repo, objectIdType, IdOperation.EDIT)) {
            // TODO: add message to exception
            throw new ForbiddenException("");
        }
        AMIdentity amIdentity = getAMIdentity(admin, repo, idType, idName);
        if (amIdentity == null) {
            String msg = "Object \'" + idName + "\' of type \'" + idType + "\' not found.'";
            throw new NotFoundException(msg);
        }
        if (isSpecialUser(amIdentity)) {
            throw new ForbiddenException("Cannot update attributes for this user.");
        }
        Map<String, Set<String>> attrs = asMap(identity.getAttributes());
        if (attrs != null && !attrs.isEmpty()) {
            Map<String, Set<String>> idAttrs = new HashMap<>();
            Set<String> removeAttrs = new HashSet<>();
            for (Map.Entry<String, Set<String>> entry : attrs.entrySet()) {
                String attrName = entry.getKey();
                Set<String> attrValues = entry.getValue();
                if (attrValues != null && !attrValues.isEmpty()) {
                    // attribute to add or modify
                    idAttrs.put(attrName, attrValues);
                } else {
                    // attribute to remove
                    removeAttrs.add(attrName);
                }
            }
            boolean storeNeeded = false;
            if (!idAttrs.isEmpty()) {
                amIdentity.setAttributes(idAttrs);
                storeNeeded = true;
            }
            if (!removeAttrs.isEmpty()) {
                amIdentity.removeAttributes(removeAttrs);
                storeNeeded = true;
            }
            if (storeNeeded) {
                amIdentity.store();
            }
        }
        if (IdType.USER.equals(objectIdType)) {
            Set<String> roles = asSet(identity.getRoleList());
            if (!roles.isEmpty()) {
                setMemberships(repo, amIdentity, roles, IdType.ROLE);
            }
            Set<String> groups = asSet(identity.getGroupList());
            if (!groups.isEmpty()) {
                setMemberships(repo, amIdentity, groups, IdType.GROUP);
            }
        }
        if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
            Set<String> members = asSet(identity.getMemberList());
            if (!members.isEmpty()) {
                setMembers(repo, amIdentity, members, IdType.USER);
            }
        }
    } catch (IdRepoException ex) {
        debug.error("IdentityServicesImpl:update", ex);
        if (IdRepoErrorCode.LDAP_EXCEPTION.equals(ex.getErrorCode())) {
            throw new InternalServerErrorException(ex.getConstraintViolationDetails());
        } else if (LDAPConstants.LDAP_INVALID_SYNTAX.equals(ex.getLDAPErrorCode())) {
            throw new BadRequestException("Unrecognized or invalid syntax for an attribute.");
        } else if (IdRepoErrorCode.ILLEGAL_ARGUMENTS.equals(ex.getErrorCode())) {
            throw new BadRequestException(ex);
        }
        throw RESOURCE_MAPPING_HANDLER.handleError(ex);
    } catch (SSOException ex) {
        debug.error("IdentityServicesImpl:update", ex);
        throw new BadRequestException(ex.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:update", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

ForbiddenException (org.forgerock.json.resource.ForbiddenException)31 SSOException (com.iplanet.sso.SSOException)26 BadRequestException (org.forgerock.json.resource.BadRequestException)22 NotFoundException (org.forgerock.json.resource.NotFoundException)21 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)20 ResourceException (org.forgerock.json.resource.ResourceException)19 IdRepoException (com.sun.identity.idm.IdRepoException)18 SMSException (com.sun.identity.sm.SMSException)18 JsonValue (org.forgerock.json.JsonValue)17 PermanentException (org.forgerock.json.resource.PermanentException)16 SSOToken (com.iplanet.sso.SSOToken)15 ConflictException (org.forgerock.json.resource.ConflictException)15 RealmContext (org.forgerock.openam.rest.RealmContext)14 NotSupportedException (org.forgerock.json.resource.NotSupportedException)11 ResourceResponse (org.forgerock.json.resource.ResourceResponse)11 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)10 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)10 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)9 OrganizationConfigManager (com.sun.identity.sm.OrganizationConfigManager)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)8