Search in sources :

Example 16 with UmaPolicy

use of org.forgerock.openam.uma.UmaPolicy in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method internalReadPolicy.

/**
     * {@inheritDoc}
     */
private Promise<UmaPolicy, ResourceException> internalReadPolicy(final Context context, final String resourceSetId) {
    String resourceOwnerUid = getResourceOwnerUid(context);
    QueryRequest request = Requests.newQueryRequest("").setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("resourceTypeUuid"), resourceSetId), QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid)));
    return policyResourceDelegate.queryPolicies(context, request).thenAsync(new AsyncFunction<Pair<QueryResponse, List<ResourceResponse>>, UmaPolicy, ResourceException>() {

        @Override
        public Promise<UmaPolicy, ResourceException> apply(Pair<QueryResponse, List<ResourceResponse>> value) {
            try {
                if (value.getSecond().isEmpty()) {
                    return new NotFoundException("UMA Policy not found, " + resourceSetId).asPromise();
                } else {
                    ResourceSetDescription resourceSet = getResourceSet(getRealm(context), resourceSetId);
                    UmaPolicy umaPolicy = UmaPolicy.fromUnderlyingPolicies(resourceSet, value.getSecond());
                    return newResultPromise(umaPolicy);
                }
            } catch (ResourceException e) {
                return e.asPromise();
            }
        }
    });
}
Also used : QueryRequest(org.forgerock.json.resource.QueryRequest) NotFoundException(org.forgerock.json.resource.NotFoundException) JsonPointer(org.forgerock.json.JsonPointer) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Promise(org.forgerock.util.promise.Promise) ResourceResponse(org.forgerock.json.resource.ResourceResponse) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) ResourceException(org.forgerock.json.resource.ResourceException) List(java.util.List) ArrayList(java.util.ArrayList) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair)

Example 17 with UmaPolicy

use of org.forgerock.openam.uma.UmaPolicy 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 UmaPolicy

use of org.forgerock.openam.uma.UmaPolicy 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 UmaPolicy

use of org.forgerock.openam.uma.UmaPolicy in project OpenAM by OpenRock.

the class ResourceSetService method combine.

private Collection<ResourceSetDescription> combine(Context context, ResourceSetWithPolicyQuery resourceSetWithPolicyQuery, Collection<ResourceSetDescription> resourceSets, Collection<UmaPolicy> policies, boolean augmentWithPolicies, String resourceOwnerId) throws org.forgerock.oauth2.core.exceptions.NotFoundException, ServerException {
    Map<String, ResourceSetDescription> resourceSetsById = new HashMap<String, ResourceSetDescription>();
    Map<String, UmaPolicy> policiesById = new HashMap<String, UmaPolicy>();
    for (ResourceSetDescription resourceSet : resourceSets) {
        resourceSetsById.put(resourceSet.getId(), resourceSet);
    }
    for (UmaPolicy policy : policies) {
        policiesById.put(policy.getId(), policy);
    }
    if (AggregateQuery.Operator.AND.equals(resourceSetWithPolicyQuery.getOperator())) {
        resourceSetsById.keySet().retainAll(policiesById.keySet());
        if (augmentWithPolicies) {
            for (ResourceSetDescription resourceSet : resourceSetsById.values()) {
                resourceSet.setPolicy(policiesById.get(resourceSet.getId()).asJson());
            }
        }
    } else if (AggregateQuery.Operator.OR.equals(resourceSetWithPolicyQuery.getOperator())) {
        if (augmentWithPolicies) {
            for (ResourceSetDescription resourceSet : resourceSetsById.values()) {
                augmentWithPolicy(context, resourceSet.getId(), resourceSet);
            }
        }
        for (Map.Entry<String, UmaPolicy> entry : policiesById.entrySet()) {
            ResourceSetDescription resourceSet;
            if (resourceSetsById.containsKey(entry.getKey())) {
                resourceSet = resourceSetsById.get(entry.getKey());
            } else {
                RealmContext realmContext = context.asContext(RealmContext.class);
                resourceSet = resourceSetStoreFactory.create(realmContext.getResolvedRealm()).read(entry.getKey(), resourceOwnerId);
            }
            if (augmentWithPolicies) {
                resourceSet.setPolicy(entry.getValue().asJson());
            }
            resourceSetsById.put(entry.getKey(), resourceSet);
        }
    }
    return resourceSetsById.values();
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) HashMap(java.util.HashMap) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription)

Example 20 with UmaPolicy

use of org.forgerock.openam.uma.UmaPolicy in project OpenAM by OpenRock.

the class ResourceSetServiceTest method getResourceSetsShouldReturnSetWhenResourceSetsExistWithNoPolicyQuery.

@Test
public void getResourceSetsShouldReturnSetWhenResourceSetsExistWithNoPolicyQuery() throws Exception {
    //Given
    Context context = createContext();
    String realm = "REALM";
    ResourceSetWithPolicyQuery query = new ResourceSetWithPolicyQuery();
    String resourceOwnerId = "RESOURCE_OWNER_ID";
    boolean augmentWithPolicies = false;
    QueryFilter<String> resourceSetQuery = mock(QueryFilter.class);
    Set<ResourceSetDescription> queriedResourceSets = new HashSet<>();
    ResourceSetDescription resourceSetOne = new ResourceSetDescription("RS_ID_ONE", "CLIENT_ID_ONE", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());
    ResourceSetDescription resourceSetTwo = new ResourceSetDescription("RS_ID_TWO", "CLIENT_ID_TWO", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());
    mockResourceOwnerIdentity(resourceOwnerId, realm);
    mockFilteredResourceSetsQueryVisitor(resourceSetQuery, queriedResourceSets);
    query.setResourceSetQuery(resourceSetQuery);
    queriedResourceSets.add(resourceSetOne);
    queriedResourceSets.add(resourceSetTwo);
    given(resourceSetStore.query(resourceSetQuery)).willReturn(queriedResourceSets);
    Collection<UmaPolicy> queriedPolicies = new HashSet<UmaPolicy>();
    Pair<QueryResponse, Collection<UmaPolicy>> queriedPoliciesPair = Pair.of(newQueryResponse(), queriedPolicies);
    Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> queriedPoliciesPromise = Promises.newResultPromise(queriedPoliciesPair);
    given(policyService.queryPolicies(eq(context), Matchers.<QueryRequest>anyObject())).willReturn(queriedPoliciesPromise);
    //When
    Collection<ResourceSetDescription> resourceSets = service.getResourceSets(context, realm, query, resourceOwnerId, augmentWithPolicies).getOrThrowUninterruptibly();
    //Then
    assertThat(resourceSets).hasSize(2).contains(resourceSetOne, resourceSetTwo);
    assertThat(resourceSetOne.getPolicy()).isNull();
    assertThat(resourceSetTwo.getPolicy()).isNull();
}
Also used : RootContext(org.forgerock.services.context.RootContext) RealmContext(org.forgerock.openam.rest.RealmContext) Context(org.forgerock.services.context.Context) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) Collection(java.util.Collection) ResourceException(org.forgerock.json.resource.ResourceException) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) HashSet(java.util.HashSet) Pair(org.forgerock.util.Pair) Test(org.testng.annotations.Test)

Aggregations

UmaPolicy (org.forgerock.openam.uma.UmaPolicy)34 ResourceException (org.forgerock.json.resource.ResourceException)33 Context (org.forgerock.services.context.Context)28 Test (org.testng.annotations.Test)28 RealmContext (org.forgerock.openam.rest.RealmContext)21 JsonValue (org.forgerock.json.JsonValue)17 QueryResponse (org.forgerock.json.resource.QueryResponse)15 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)15 Pair (org.forgerock.util.Pair)15 ResourceResponse (org.forgerock.json.resource.ResourceResponse)13 HashSet (java.util.HashSet)12 Responses.newQueryResponse (org.forgerock.json.resource.Responses.newQueryResponse)12 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)11 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)11 ClientContext (org.forgerock.services.context.ClientContext)11 Collection (java.util.Collection)10 RootContext (org.forgerock.services.context.RootContext)9 UmaPolicyServiceImplTest (org.forgerock.openam.uma.rest.UmaPolicyServiceImplTest)8 Matchers.anyString (org.mockito.Matchers.anyString)8 ArrayList (java.util.ArrayList)7