Search in sources :

Example 26 with ActionResponse

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

the class IdentityResourceV1 method anonymousUpdate.

/**
     * Perform an anonymous update of a user's password using the provided token.
     *
     * The token must match a token placed in the CTS in order for the request
     * to proceed.
     *
     * @param context Non null
     * @param request Non null
     * @param realm Non null
     */
private Promise<ActionResponse, ResourceException> anonymousUpdate(final Context context, final ActionRequest request, final String realm) {
    final String tokenID;
    String confirmationId;
    String username;
    String nwpassword;
    final JsonValue jVal = request.getContent();
    try {
        tokenID = jVal.get(TOKEN_ID).asString();
        jVal.remove(TOKEN_ID);
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        jVal.remove(CONFIRMATION_ID);
        username = jVal.get(USERNAME).asString();
        nwpassword = jVal.get("userpassword").asString();
        if (username == null || username.isEmpty()) {
            throw new BadRequestException("username not provided");
        }
        if (nwpassword == null || username.isEmpty()) {
            throw new BadRequestException("new password not provided");
        }
        validateToken(tokenID, realm, username, confirmationId);
        // update Identity
        SSOToken admin = RestUtils.getToken();
        // Update instance with new password value
        return updateInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {

            @Override
            public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
                // Only remove the token if the update was successful, errors will be set in the handler.
                try {
                    // Even though the generated token will eventually timeout, delete it after a successful read
                    // so that the reset password request cannot be made again using the same token.
                    CTSHolder.getCTS().deleteAsync(tokenID);
                } catch (DeleteFailedException e) {
                    // reading and deleting, the token has expired.
                    if (debug.messageEnabled()) {
                        debug.message("Deleting token " + tokenID + " after a successful " + "read failed due to " + e.getMessage(), e);
                    }
                } catch (CoreTokenException cte) {
                    // For any unexpected CTS error
                    debug.error("Error performing anonymousUpdate", cte);
                    return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
                }
                return newResultPromise(response);
            }
        });
    } catch (BadRequestException bre) {
        // For any malformed request.
        debug.warning("Bad request received for anonymousUpdate " + bre.getMessage());
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("Error performing anonymousUpdate", re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        // For any unexpected CTS error
        debug.error("Error performing anonymousUpdate", cte);
        return new InternalServerErrorException(cte).asPromise();
    }
}
Also used : Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) ActionResponse(org.forgerock.json.resource.ActionResponse)

Example 27 with ActionResponse

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

the class PolicyResourceEvaluationTest method shouldMakeTreeEvaluation.

@Test
public void shouldMakeTreeEvaluation() throws EntitlementException {
    // Given...
    given(request.getAction()).willReturn("evaluateTree");
    Context context = buildContextStructure("/abc");
    given(requestFactory.buildRequest(PolicyAction.TREE_EVALUATE, context, request)).willReturn(policyRequest);
    given(policyRequest.getRestSubject()).willReturn(restSubject);
    given(policyRequest.getApplication()).willReturn("some-application");
    given(factory.getEvaluator(restSubject, "some-application")).willReturn(evaluator);
    given(policyRequest.getApplication()).willReturn("some-application");
    given(policyRequest.getRealm()).willReturn("/abc");
    List<Entitlement> decisions = Arrays.asList(new Entitlement());
    given(evaluator.routePolicyRequest(policyRequest)).willReturn(decisions);
    JsonValue jsonDecision = JsonValue.json(array());
    given(parser.printEntitlements(decisions)).willReturn(jsonDecision);
    // When...
    Promise<ActionResponse, ResourceException> promise = policyResource.actionCollection(context, request);
    // Then...
    verify(request).getAction();
    verify(requestFactory).buildRequest(PolicyAction.TREE_EVALUATE, context, request);
    verify(policyRequest).getRestSubject();
    verify(policyRequest, times(2)).getApplication();
    verify(policyRequest).getRealm();
    verify(factory).getEvaluator(restSubject, "some-application");
    verify(evaluator).routePolicyRequest(policyRequest);
    verify(parser).printEntitlements(decisions);
    assertThat(promise).succeeded().withContent().isEqualTo(jsonDecision);
    verifyNoMoreInteractions(request, subjectContext, requestFactory, policyRequest, factory, evaluator, parser);
}
Also used : ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) Context(org.forgerock.services.context.Context) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) JsonValue(org.forgerock.json.JsonValue) ResourceException(org.forgerock.json.resource.ResourceException) Entitlement(com.sun.identity.entitlement.Entitlement) ActionResponse(org.forgerock.json.resource.ActionResponse) Test(org.testng.annotations.Test)

Example 28 with ActionResponse

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

the class PolicyV1FilterTest method forwardOnAction.

/**
     * Verify that action requests are forwarded on.
     */
@Test
public void forwardOnAction() throws Exception {
    // Given
    ActionRequest actionRequest = mock(ActionRequest.class);
    // When
    Promise<ActionResponse, ResourceException> promise = filter.filterAction(context, actionRequest, requestHandler);
    // Then
    assertThat(promise).succeeded();
    assertThat(promise.get().getJsonContent().contains("ttl")).isFalse();
}
Also used : ActionRequest(org.forgerock.json.resource.ActionRequest) ResourceException(org.forgerock.json.resource.ResourceException) ActionResponse(org.forgerock.json.resource.ActionResponse) Test(org.testng.annotations.Test)

Example 29 with ActionResponse

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

the class PolicyResourceWithCopyMoveSupport method copyOrMovePoliciesByApplication.

private ActionResponse copyOrMovePoliciesByApplication(Context context, ActionRequest request, PolicyAction copyOrMoveAction) throws ResourceException {
    JsonValue payload = request.getContent();
    JsonValue from = payload.get("from");
    JsonValue to = payload.get("to");
    if (from.isNull()) {
        throw new BadRequestException("from definition is missing");
    }
    if (!from.isDefined("application")) {
        throw new BadRequestException("from application definition is missing");
    }
    String sourceApplication = from.get("application").asString();
    if (to.isNull()) {
        throw new BadRequestException("to definition is missing");
    }
    String sourceRealm = RealmContext.getRealm(context);
    String destinationRealm = to.get("realm").defaultTo(sourceRealm).asString();
    String destinationApplication = to.get("application").defaultTo(sourceApplication).asString();
    JsonValue resourceTypeMapping = payload.get("resourceTypeMapping").defaultTo(Collections.emptyMap());
    String namePostfix = to.get("namePostfix").defaultTo("").asString();
    QueryRequest queryRequest = Requests.newQueryRequest("policies");
    queryRequest.setQueryFilter(QueryFilter.equalTo(new JsonPointer("applicationName"), sourceApplication));
    final List<JsonValue> policies = new ArrayList<>();
    router.handleQuery(context, queryRequest, new QueryResourceHandler() {

        @Override
        public boolean handleResource(ResourceResponse resourceResponse) {
            policies.add(resourceResponse.getContent());
            return true;
        }
    }).getOrThrowUninterruptibly();
    JsonValue actionResponseContent = json(array());
    for (JsonValue policy : policies) {
        ActionResponse response = copyOrMoveGivenPolicy(context, policy, destinationRealm, destinationApplication, namePostfix, resourceTypeMapping, copyOrMoveAction);
        actionResponseContent.add(response.getJsonContent().asMap());
    }
    return Responses.newActionResponse(actionResponseContent);
}
Also used : QueryRequest(org.forgerock.json.resource.QueryRequest) ResourceResponse(org.forgerock.json.resource.ResourceResponse) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) BadRequestException(org.forgerock.json.resource.BadRequestException) JsonPointer(org.forgerock.json.JsonPointer) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) ActionResponse(org.forgerock.json.resource.ActionResponse)

Example 30 with ActionResponse

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

the class PrivilegeAuthzModuleTest method crestActionEvaluateIsAllowed.

@Test
public void crestActionEvaluateIsAllowed() throws SSOException, DelegationException {
    // Given...
    final Set<String> actions = new HashSet<>(Arrays.asList("READ"));
    final DelegationPermission permission = new DelegationPermission("/abc", "rest", "1.0", "policies", "evaluate", actions, EXTENSIONS, DUMB_FUNC);
    given(factory.newInstance("/abc", "rest", "1.0", "policies", "evaluate", actions, EXTENSIONS)).willReturn(permission);
    given(subjectContext.getCallerSSOToken()).willReturn(token);
    given(evaluator.isAllowed(eq(token), eq(permission), eq(ENVIRONMENT))).willReturn(true);
    JsonValue jsonValue = json(object(field("someKey", "someValue")));
    Promise<ActionResponse, ResourceException> promise = Promises.newResultPromise(Responses.newActionResponse(jsonValue));
    given(provider.actionCollection(isA(Context.class), isA(ActionRequest.class))).willReturn(promise);
    // When...
    final FilterChain chain = AuthorizationFilters.createAuthorizationFilter(provider, module);
    final Router router = new Router();
    router.addRoute(RoutingMode.STARTS_WITH, Router.uriTemplate("/policies"), chain);
    final RealmContext context = new RealmContext(subjectContext);
    context.setSubRealm("abc", "abc");
    final ActionRequest request = Requests.newActionRequest("/policies", "evaluate");
    Promise<ActionResponse, ResourceException> result = router.handleAction(context, request);
    // Then...
    assertThat(result).succeeded().withContent().stringAt("someKey").isEqualTo("someValue");
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) Context(org.forgerock.services.context.Context) RealmContext(org.forgerock.openam.rest.RealmContext) FilterChain(org.forgerock.json.resource.FilterChain) JsonValue(org.forgerock.json.JsonValue) Router(org.forgerock.json.resource.Router) Matchers.anyString(org.mockito.Matchers.anyString) DelegationPermission(com.sun.identity.delegation.DelegationPermission) ActionResponse(org.forgerock.json.resource.ActionResponse) ActionRequest(org.forgerock.json.resource.ActionRequest) ResourceException(org.forgerock.json.resource.ResourceException) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Aggregations

ActionResponse (org.forgerock.json.resource.ActionResponse)43 ResourceException (org.forgerock.json.resource.ResourceException)37 Test (org.testng.annotations.Test)34 ActionRequest (org.forgerock.json.resource.ActionRequest)29 Context (org.forgerock.services.context.Context)22 JsonValue (org.forgerock.json.JsonValue)20 RealmContext (org.forgerock.openam.rest.RealmContext)13 Promise (org.forgerock.util.promise.Promise)7 Promises.newResultPromise (org.forgerock.util.promise.Promises.newResultPromise)7 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)6 BadRequestException (org.forgerock.json.resource.BadRequestException)5 SSOToken (com.iplanet.sso.SSOToken)4 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)4 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)4 Responses.newActionResponse (org.forgerock.json.resource.Responses.newActionResponse)4 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)4 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)4 FilterChain (org.forgerock.json.resource.FilterChain)3 NotFoundException (org.forgerock.json.resource.NotFoundException)3 Router (org.forgerock.json.resource.Router)3