Search in sources :

Example 1 with Attribute

use of com.sun.identity.idsvcs.Attribute in project OpenAM by OpenRock.

the class IdentityResourceV3 method patchInstance.

/**
     * Patch the user's password and only the password.  No other value may be patched.  The old value of the
     * password does not have to be known.  Admin only.  The only patch operation supported is "replace", i.e. not
     * "add" or "move", etc.
     *
     * @param context The context
     * @param resourceId The username we're patching
     * @param request The patch request
     */
@Override
public Promise<ResourceResponse, ResourceException> patchInstance(final Context context, final String resourceId, final PatchRequest request) {
    if (!objectType.equals(IdentityRestUtils.USER_TYPE)) {
        return new BadRequestException("Cannot patch object type " + objectType).asPromise();
    }
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        if (!isAdmin(context)) {
            return new ForbiddenException("Only admin can patch user values").asPromise();
        }
        SSOToken ssoToken = getSSOToken(RestUtils.getToken().getTokenID().toString());
        IdentityServicesImpl identityServices = getIdentityServices();
        IdentityDetails identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
        Attribute[] existingAttributes = identityDetails.getAttributes();
        Map<String, Set<String>> existingAttributeMap = attributesToMap(existingAttributes);
        Map<String, Set<String>> newAttributeMap = new HashMap<>();
        if (existingAttributeMap.containsKey(IdentityRestUtils.UNIVERSAL_ID)) {
            Set<String> values = existingAttributeMap.get(IdentityRestUtils.UNIVERSAL_ID);
            if (isNotEmpty(values) && !isUserActive(values.iterator().next())) {
                return new ForbiddenException("User " + resourceId + " is not active: Request is forbidden").asPromise();
            }
        }
        boolean updateNeeded = false;
        for (PatchOperation patchOperation : request.getPatchOperations()) {
            switch(patchOperation.getOperation()) {
                case PatchOperation.OPERATION_REPLACE:
                    {
                        String name = getFieldName(patchOperation.getField());
                        if (!patchableAttributes.contains(name)) {
                            return new BadRequestException("For the object type " + IdentityRestUtils.USER_TYPE + ", field \"" + name + "\" cannot be altered by PATCH").asPromise();
                        }
                        JsonValue value = patchOperation.getValue();
                        newAttributeMap.put(name, identityAttributeJsonToSet(value));
                        updateNeeded = true;
                        break;
                    }
                default:
                    return new BadRequestException("PATCH of " + IdentityRestUtils.USER_TYPE + " does not support operation " + patchOperation.getOperation()).asPromise();
            }
        }
        if (updateNeeded) {
            identityDetails.setAttributes(mapToAttributes(newAttributeMap));
            identityServices.update(identityDetails, ssoToken);
            // re-read the altered identity details from the repo.
            identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
        }
        return newResultPromise(newResourceResponse("result", "1", identityDetailsToJsonValue(identityDetails)));
    } catch (final ObjectNotFound notFound) {
        logger.error("IdentityResourceV3.patchInstance cannot find resource " + resourceId, notFound);
        return new NotFoundException("Resource cannot be found.", notFound).asPromise();
    } catch (final TokenExpired tokenExpired) {
        logger.error("IdentityResourceV3.patchInstance, token expired", tokenExpired);
        return new PermanentException(401, "Unauthorized", null).asPromise();
    } catch (final AccessDenied accessDenied) {
        logger.error("IdentityResourceV3.patchInstance, access denied", accessDenied);
        return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
    } catch (final GeneralFailure generalFailure) {
        logger.error("IdentityResourceV3.patchInstance, general failure " + generalFailure.getMessage());
        return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
    } catch (ForbiddenException fex) {
        logger.warning("IdentityResourceV3.patchInstance, insufficient privileges.", fex);
        return fex.asPromise();
    } catch (NotFoundException notFound) {
        logger.warning("IdentityResourceV3.patchInstance " + resourceId + " not found", notFound);
        return new NotFoundException("Resource " + resourceId + " cannot be found.", notFound).asPromise();
    } catch (ResourceException resourceException) {
        logger.warning("IdentityResourceV3.patchInstance caught ResourceException", resourceException);
        return resourceException.asPromise();
    } catch (Exception exception) {
        logger.error("IdentityResourceV3.patchInstance caught exception", exception);
        return new InternalServerErrorException(exception.getMessage(), exception).asPromise();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) Attribute(com.sun.identity.idsvcs.Attribute) HashMap(java.util.HashMap) NotFoundException(org.forgerock.json.resource.NotFoundException) IdentityServicesImpl(com.sun.identity.idsvcs.opensso.IdentityServicesImpl) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) PatchOperation(org.forgerock.json.resource.PatchOperation) TokenExpired(com.sun.identity.idsvcs.TokenExpired) ResourceException(org.forgerock.json.resource.ResourceException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) AccessDenied(com.sun.identity.idsvcs.AccessDenied) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) BadRequestException(org.forgerock.json.resource.BadRequestException) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 2 with Attribute

use of com.sun.identity.idsvcs.Attribute in project OpenAM by OpenRock.

the class IdentityResourceV3 method mapToAttributes.

/**
     * Convert a map back into an array of attributes.
     * @param map The map to convert.
     * @return The, possibly empty, array of attributes.
     */
private Attribute[] mapToAttributes(Map<String, Set<String>> map) {
    Attribute[] result = new Attribute[map.size()];
    int index = 0;
    for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
        result[index] = new Attribute();
        result[index].setName(entry.getKey());
        result[index].setValues(entry.getValue().toArray(new String[0]));
        index++;
    }
    return result;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Attribute(com.sun.identity.idsvcs.Attribute) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Attribute

use of com.sun.identity.idsvcs.Attribute in project OpenAM by OpenRock.

the class IdentityRestUtils method enforceWhiteList.

/**
     * When an instance of a user is created via self service, we impose additional rules for security purposes.
     * Namely, we strictly apply a whitelist of valid attribute names to each attribute in the incoming JSON
     * representation of the user object.  This ensures a hacker can't manipulate the request and thereby pretend
     * to be a manager, demigod or individual they are not.
     *
     * There is no return value.  If you survive calling this function without an exception being thrown, there
     * are no illegal values in the incoming JSON
     *
     * @param context The context
     * @param jsonValue The request
     * @param objectType The type of object we're creating, user, group, etc.
     * @param validUserAttributes The set of valid user attributes
     * @throws BadRequestException If any attribute is found in the JSON representation of the user object containing
     * an attribute that is not in our whitelist
     */
public static void enforceWhiteList(final Context context, final JsonValue jsonValue, final String objectType, final Set<String> validUserAttributes) throws BadRequestException {
    if (!context.containsContext(SelfServiceContext.class) || !objectType.equals(USER_TYPE)) {
        return;
    }
    final String realm = RealmContext.getRealm(context);
    if (validUserAttributes == null || validUserAttributes.isEmpty()) {
        throw new BadRequestException("Null/empty whitelist of valid attributes for self service user creation");
    }
    IdentityDetails identityDetails = jsonValueToIdentityDetails(objectType, jsonValue, realm);
    Attribute[] attributes = identityDetails.getAttributes();
    for (Attribute attribute : attributes) {
        if (!validUserAttributes.contains(attribute.getName())) {
            throw new BadRequestException("User attribute " + attribute.getName() + " is not valid for self service creation");
        }
    }
}
Also used : Attribute(com.sun.identity.idsvcs.Attribute) BadRequestException(org.forgerock.json.resource.BadRequestException) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails)

Example 4 with Attribute

use of com.sun.identity.idsvcs.Attribute in project OpenAM by OpenRock.

the class IdentityServicesImpl method read.

public IdentityDetails read(String name, Map<String, Set<String>> attributes, SSOToken admin) throws IdServicesException {
    IdentityDetails rv = null;
    String realm = null;
    String repoRealm;
    String identityType = null;
    List<String> attrsToGet = null;
    if (attributes != null) {
        for (Attribute attr : asAttributeArray(attributes)) {
            String attrName = attr.getName();
            if ("realm".equalsIgnoreCase(attrName)) {
                String[] values = attr.getValues();
                if (values != null && values.length > 0) {
                    realm = values[0];
                }
            } else if ("objecttype".equalsIgnoreCase(attrName)) {
                String[] values = attr.getValues();
                if (values != null && values.length > 0) {
                    identityType = values[0];
                }
            } else {
                if (attrsToGet == null) {
                    attrsToGet = new ArrayList<>();
                }
                attrsToGet.add(attrName);
            }
        }
    }
    if (StringUtils.isEmpty(realm)) {
        repoRealm = "/";
    } else {
        repoRealm = realm;
    }
    if (StringUtils.isEmpty(identityType)) {
        identityType = "User";
    }
    try {
        AMIdentity amIdentity = getAMIdentity(admin, identityType, name, repoRealm);
        if (amIdentity == null) {
            debug.error("IdentityServicesImpl:read identity not found");
            throw new ObjectNotFound(name);
        }
        if (isSpecialUser(amIdentity)) {
            throw new AccessDenied("Cannot retrieve attributes for this user.");
        }
        rv = convertToIdentityDetails(amIdentity, attrsToGet);
        if (!StringUtils.isEmpty(realm)) {
            // use the realm specified by the request
            rv.setRealm(realm);
        }
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:read", e);
        mapIdRepoException(e);
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl:read", e);
        throw new GeneralFailure(e.getMessage());
    }
    return rv;
}
Also used : Attribute(com.sun.identity.idsvcs.Attribute) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) ArrayList(java.util.ArrayList) IdRepoException(com.sun.identity.idm.IdRepoException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) SSOException(com.iplanet.sso.SSOException) AccessDenied(com.sun.identity.idsvcs.AccessDenied)

Example 5 with Attribute

use of com.sun.identity.idsvcs.Attribute in project OpenAM by OpenRock.

the class IdentityServicesImpl method attributes.

private UserDetails attributes(List<String> attributeNames, Token subject, Boolean refresh) throws TokenExpired, GeneralFailure, AccessDenied {
    UserDetails details = new UserDetails();
    try {
        SSOToken ssoToken = getSSOToken(subject);
        if (refresh != null && refresh) {
            SSOTokenManager.getInstance().refreshSession(ssoToken);
        }
        Map<String, Set<String>> sessionAttributes = new HashMap<>();
        Set<String> s;
        if (attributeNames != null) {
            String propertyNext;
            for (String attrNext : attributeNames) {
                s = new HashSet<>();
                if (attrNext.equalsIgnoreCase("idletime")) {
                    s.add(Long.toString(ssoToken.getIdleTime()));
                } else if (attrNext.equalsIgnoreCase("timeleft")) {
                    s.add(Long.toString(ssoToken.getTimeLeft()));
                } else if (attrNext.equalsIgnoreCase("maxsessiontime")) {
                    s.add(Long.toString(ssoToken.getMaxSessionTime()));
                } else if (attrNext.equalsIgnoreCase("maxidletime")) {
                    s.add(Long.toString(ssoToken.getMaxIdleTime()));
                } else {
                    propertyNext = ssoToken.getProperty(attrNext);
                    if (propertyNext != null && !propertyNext.isEmpty()) {
                        s.add(propertyNext);
                    }
                }
                if (!s.isEmpty()) {
                    sessionAttributes.put(attrNext, s);
                }
            }
        }
        // Obtain user memberships (roles and groups)
        AMIdentity userIdentity = IdUtils.getIdentity(ssoToken);
        if (isSpecialUser(userIdentity)) {
            throw new AccessDenied("Cannot retrieve attributes for this user.");
        }
        // Determine the types that can have members
        SSOToken adminToken = AccessController.doPrivileged(AdminTokenAction.getInstance());
        AMIdentityRepository idrepo = new AMIdentityRepository(userIdentity.getRealm(), adminToken);
        Set<IdType> supportedTypes = idrepo.getSupportedIdTypes();
        Set<IdType> membersTypes = new HashSet<>();
        for (IdType type : supportedTypes) {
            if (type.canHaveMembers().contains(userIdentity.getType())) {
                membersTypes.add(type);
            }
        }
        // Determine the roles and groups
        List<String> roles = new ArrayList<>();
        for (IdType type : membersTypes) {
            try {
                Set<AMIdentity> memberships = userIdentity.getMemberships(type);
                for (AMIdentity membership : memberships) {
                    roles.add(membership.getUniversalId());
                }
            } catch (IdRepoException ire) {
                debug.message("IdentityServicesImpl:attributes", ire);
            // Ignore and continue
            }
        }
        String[] r = new String[roles.size()];
        details.setRoles(roles.toArray(r));
        Map<String, Set<String>> userAttributes;
        if (attributeNames != null) {
            Set<String> attrNames = new HashSet<>(attributeNames);
            userAttributes = userIdentity.getAttributes(attrNames);
        } else {
            userAttributes = userIdentity.getAttributes();
        }
        if (userAttributes != null) {
            for (Map.Entry<String, Set<String>> entry : sessionAttributes.entrySet()) {
                if (userAttributes.keySet().contains(entry.getKey())) {
                    userAttributes.get(entry.getKey()).addAll(entry.getValue());
                } else {
                    userAttributes.put(entry.getKey(), entry.getValue());
                }
            }
        } else {
            userAttributes = sessionAttributes;
        }
        List<Attribute> attributes = new ArrayList<>(userAttributes.size());
        for (String name : userAttributes.keySet()) {
            Attribute attribute = new Attribute();
            attribute.setName(name);
            Set<String> value = userAttributes.get(name);
            if (value != null && !value.isEmpty()) {
                List<String> valueList = new ArrayList<>(value.size());
                // Convert the set to a List of String
                for (String next : value) {
                    if (next != null) {
                        valueList.add(next);
                    }
                }
                String[] v = new String[valueList.size()];
                attribute.setValues(valueList.toArray(v));
                attributes.add(attribute);
            }
        }
        Attribute[] a = new Attribute[attributes.size()];
        details.setAttributes(attributes.toArray(a));
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:attributes", e);
        throw new GeneralFailure(e.getMessage());
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl:attributes", e);
        throw new GeneralFailure(e.getMessage());
    } catch (TokenExpired e) {
        debug.warning("IdentityServicesImpl:attributes original error", e);
        throw new TokenExpired("Cannot retrieve Token.");
    }
    //TODO handle token translation
    details.setToken(subject);
    return details;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(com.sun.identity.idsvcs.Attribute) ArrayList(java.util.ArrayList) SSOException(com.iplanet.sso.SSOException) UserDetails(com.sun.identity.idsvcs.UserDetails) TokenExpired(com.sun.identity.idsvcs.TokenExpired) HashSet(java.util.HashSet) IdRepoException(com.sun.identity.idm.IdRepoException) AccessDenied(com.sun.identity.idsvcs.AccessDenied) IdType(com.sun.identity.idm.IdType) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Attribute (com.sun.identity.idsvcs.Attribute)5 AccessDenied (com.sun.identity.idsvcs.AccessDenied)3 GeneralFailure (com.sun.identity.idsvcs.GeneralFailure)3 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 SSOException (com.iplanet.sso.SSOException)2 SSOToken (com.iplanet.sso.SSOToken)2 AMIdentity (com.sun.identity.idm.AMIdentity)2 IdRepoException (com.sun.identity.idm.IdRepoException)2 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)2 TokenExpired (com.sun.identity.idsvcs.TokenExpired)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 BadRequestException (org.forgerock.json.resource.BadRequestException)2 AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)1 IdType (com.sun.identity.idm.IdType)1 UserDetails (com.sun.identity.idsvcs.UserDetails)1 IdentityServicesImpl (com.sun.identity.idsvcs.opensso.IdentityServicesImpl)1