use of org.forgerock.json.resource.BadRequestException 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();
}
}
use of org.forgerock.json.resource.BadRequestException 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");
}
}
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class RealmResource method updateInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
final JsonValue realmDetails = request.getContent();
ResourceResponse resource;
String realm;
OrganizationConfigManager ocm;
OrganizationConfigManager realmCreatedOcm;
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
try {
hasPermission(context);
realm = checkForTopLevelRealm(resourceId);
if (realm != null && !realm.startsWith("/")) {
realm = "/" + realm;
}
if (!realmPath.equalsIgnoreCase("/")) {
realm = realmPath + realm;
}
// Update a realm - if it's not found, error out.
ocm = new OrganizationConfigManager(getSSOToken(), realm);
List newServiceNames;
// update ID_REPO attributes
updateConfiguredServices(ocm, createServicesMap(realmDetails));
newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
if (newServiceNames == null || newServiceNames.isEmpty()) {
debug.error("RealmResource.updateInstance() : No Services defined.");
} else {
//assign services to realm
assignServices(ocm, newServiceNames);
}
// READ THE REALM
realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realm);
debug.message("RealmResource.updateInstance :: UPDATE of realm " + realm + " performed by " + principalName);
// create a resource for handler to return
resource = newResourceResponse(realm, String.valueOf(System.currentTimeMillis()), createJsonMessage("realmUpdated", realmCreatedOcm.getOrganizationName()));
return newResultPromise(resource);
} catch (SMSException e) {
try {
configureErrorMessage(e);
return new NotFoundException(e.getMessage(), e).asPromise();
} catch (ForbiddenException fe) {
// User does not have authorization
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
return fe.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (ConflictException ce) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ce);
return ce.asPromise();
} catch (BadRequestException be) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, be);
return be.asPromise();
} catch (Exception ex) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
return new NotFoundException("Cannot update realm.", ex).asPromise();
}
} catch (SSOException sso) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, sso);
return new PermanentException(401, "Access Denied", null).asPromise();
} catch (ForbiddenException fe) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
return fe.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.Instance() : Cannot UPDATE " + resourceId, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (Exception ex) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
return new NotFoundException("Cannot update realm.", ex).asPromise();
}
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class RealmResource method readInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
ResourceResponse resource;
JsonValue jval;
String holdResourceId = checkForTopLevelRealm(resourceId);
try {
hasPermission(context);
if (holdResourceId != null && !holdResourceId.startsWith("/")) {
holdResourceId = "/" + holdResourceId;
}
if (!realmPath.equalsIgnoreCase("/")) {
holdResourceId = realmPath + holdResourceId;
}
OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), holdResourceId);
// get associated services for this realm , include mandatory service names.
Set serviceNames = ocm.getAssignedServices();
jval = createJsonMessage(SERVICE_NAMES, serviceNames);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
resource = newResourceResponse(resourceId, String.valueOf(System.currentTimeMillis()), jval);
if (debug.messageEnabled()) {
debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + resourceId + " performed by " + principalName);
}
return newResultPromise(resource);
} catch (SSOException sso) {
debug.error("RealmResource.updateInstance() : Cannot READ " + resourceId, sso);
return new PermanentException(401, "Access Denied", null).asPromise();
} catch (ForbiddenException fe) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId + ":" + fe);
return fe.asPromise();
} catch (SMSException smse) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, smse);
try {
configureErrorMessage(smse);
return new BadRequestException(smse.getMessage(), smse).asPromise();
} catch (NotFoundException nf) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, nf);
return nf.asPromise();
} catch (ForbiddenException fe) {
// User does not have authorization
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, fe);
return fe.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (ConflictException ce) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, ce);
return ce.asPromise();
} catch (BadRequestException be) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, be);
return be.asPromise();
} catch (Exception e) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, e);
return new BadRequestException(e.getMessage(), e).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class IdentityResourceV1 method updateInstance.
/**
* Updates an instance given a JSON object with User Attributes
* @param admin Token that has administrative privileges
* @param details Json Value containing details of user identity
* @return A successful promise if the update was successful
*/
private Promise<ActionResponse, ResourceException> updateInstance(SSOToken admin, final JsonValue details, final String realm) {
JsonValue jVal = details;
IdentityDetails newDtls;
String resourceId = jVal.get(USERNAME).asString();
try {
newDtls = jsonValueToIdentityDetails(objectType, jVal, realm);
if (newDtls.getAttributes() == null || newDtls.getAttributes().length < 1) {
throw new BadRequestException("Illegal arguments: One or more required arguments is null or empty");
}
newDtls.setName(resourceId);
// update resource with new details
identityServices.update(newDtls, admin);
debug.message("IdentityResource.updateInstance :: Anonymous UPDATE in realm={} for resourceId={}", realm, resourceId);
// read updated identity back to client
IdentityDetails checkIdent = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
// handle updated resource
return newResultPromise(newActionResponse(identityDetailsToJsonValue(checkIdent)));
} catch (ResourceException re) {
debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, re);
return re.asPromise();
} catch (final Exception e) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, e);
return new NotFoundException(e.getMessage(), e).asPromise();
}
}
Aggregations