Search in sources :

Example 11 with UmaPolicy

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

the class UmaPolicyServiceImplTest method shouldUpdateUmaPolicy.

@Test
public void shouldUpdateUmaPolicy() throws Exception {
    //Given
    Context context = createContext();
    JsonValue policy = createUmaPolicyJson("RESOURCE_SET_ID", "SCOPE_A", "SCOPE_C");
    policy.remove(new JsonPointer("/permissions/0/scopes/1"));
    List<ResourceResponse> updatedPolicies = new ArrayList<>();
    ResourceResponse updatedPolicy1 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectOneUpdatedPolicyJson());
    ResourceResponse updatedPolicy2 = newResourceResponse("ID_2", "REVISION_1", createBackendSubjectTwoPolicyJson());
    updatedPolicies.add(updatedPolicy1);
    updatedPolicies.add(updatedPolicy2);
    Promise<List<ResourceResponse>, ResourceException> updatePolicyPromise = newResultPromise(updatedPolicies);
    List<ResourceResponse> currentPolicies = new ArrayList<>();
    ResourceResponse currentPolicy1 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectOnePolicyJson());
    ResourceResponse currentPolicy2 = newResourceResponse("ID_2", "REVISION_1", createBackendSubjectTwoPolicyJson());
    currentPolicies.add(currentPolicy1);
    currentPolicies.add(currentPolicy2);
    Promise<Pair<QueryResponse, List<ResourceResponse>>, ResourceException> currentPolicyPromise = newResultPromise(Pair.of((QueryResponse) null, currentPolicies));
    setupQueries(currentPolicyPromise, updatedPolicy1, updatedPolicy2);
    given(policyResourceDelegate.updatePolicies(eq(context), Matchers.<Set<JsonValue>>anyObject())).willReturn(updatePolicyPromise);
    //When
    UmaPolicy umaPolicy = policyService.updatePolicy(context, "RESOURCE_SET_ID", policy).getOrThrowUninterruptibly();
    //Then
    InOrder inOrder = inOrder(resourceDelegationFilter, policyResourceDelegate);
    inOrder.verify(resourceDelegationFilter).beforeResourceSharedModification(any(UmaPolicy.class), any(UmaPolicy.class));
    inOrder.verify(policyResourceDelegate, times(2)).updatePolicies(any(Context.class), anySetOf(JsonValue.class));
    assertThat(umaPolicy.getId()).isEqualTo("RESOURCE_SET_ID");
    assertThat(umaPolicy.getRevision()).isNotNull();
    JsonValue expectedPolicyJson = createUmaPolicyJson("RESOURCE_SET_ID", "SCOPE_A", "SCOPE_C");
    expectedPolicyJson.remove(new JsonPointer("/permissions/0/scopes/1"));
    assertThat(umaPolicy.asJson().asMap()).isEqualTo(expectedPolicyJson.asMap());
}
Also used : ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) SSOTokenContext(org.forgerock.openam.rest.resource.SSOTokenContext) Context(org.forgerock.services.context.Context) InOrder(org.mockito.InOrder) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) JsonPointer(org.forgerock.json.JsonPointer) ResourceResponse(org.forgerock.json.resource.ResourceResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) List(java.util.List) ArrayList(java.util.ArrayList) ResourceException(org.forgerock.json.resource.ResourceException) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) Test(org.testng.annotations.Test)

Example 12 with UmaPolicy

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

the class UmaPolicyServiceImplTest method shouldCreateUmaPolicy.

@Test
@SuppressWarnings("unchecked")
public void shouldCreateUmaPolicy() throws Exception {
    //Given
    Context context = createContext();
    JsonValue policy = createUmaPolicyJson("RESOURCE_SET_ID");
    List<ResourceResponse> createdPolicies = new ArrayList<>();
    ResourceResponse createdPolicy1 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectOnePolicyJson());
    ResourceResponse createdPolicy2 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectTwoPolicyJson());
    createdPolicies.add(createdPolicy1);
    createdPolicies.add(createdPolicy2);
    Promise<Pair<QueryResponse, List<ResourceResponse>>, ResourceException> queryPromise = Promises.newExceptionPromise((ResourceException) new NotFoundException());
    setupQueries(queryPromise, createdPolicy1, createdPolicy2);
    Promise<List<ResourceResponse>, ResourceException> createPolicyPromise = newResultPromise(createdPolicies);
    given(policyResourceDelegate.createPolicies(eq(context), Matchers.<Set<JsonValue>>anyObject())).willReturn(createPolicyPromise);
    //When
    UmaPolicy umaPolicy = policyService.createPolicy(context, policy).getOrThrowUninterruptibly();
    //Then
    InOrder inOrder = inOrder(resourceDelegationFilter, policyResourceDelegate, resourceDelegationFilter);
    inOrder.verify(resourceDelegationFilter).beforeResourceShared(any(UmaPolicy.class));
    inOrder.verify(policyResourceDelegate).createPolicies(eq(context), anySetOf(JsonValue.class));
    inOrder.verify(resourceDelegationFilter).afterResourceShared(any(UmaPolicy.class));
    assertThat(umaPolicy.getId()).isEqualTo("RESOURCE_SET_ID");
    assertThat(umaPolicy.getRevision()).isNotNull();
    assertThat(umaPolicy.asJson().asMap()).hasSize(3).contains(entry("policyId", "RESOURCE_SET_ID"), entry("name", "NAME"));
    JsonValue permissions = umaPolicy.asJson().get("permissions");
    assertThat(permissions.asList()).hasSize(2);
    assertThat(permissions.get(0).asMap()).contains(entry("subject", "SUBJECT_ONE"));
    assertThat(permissions.get(0).get("scopes").asList()).containsOnly("SCOPE_A", "SCOPE_B");
    assertThat(permissions.get(1).asMap()).contains(entry("subject", "SUBJECT_TWO"));
    assertThat(permissions.get(1).get("scopes").asList()).containsOnly("SCOPE_A");
}
Also used : ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) SSOTokenContext(org.forgerock.openam.rest.resource.SSOTokenContext) Context(org.forgerock.services.context.Context) InOrder(org.mockito.InOrder) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) NotFoundException(org.forgerock.json.resource.NotFoundException) 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) Pair(org.forgerock.util.Pair) Test(org.testng.annotations.Test)

Example 13 with UmaPolicy

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

the class UmaPolicyServiceImplDelegationTest method aliceShouldBeAbleToUpdatePolicyForResource.

@Test
public void aliceShouldBeAbleToUpdatePolicyForResource() throws Exception {
    //Given
    userIsLoggedIn("alice", "REALM");
    accessingUriForUser("alice");
    String resourceSetId = registerResourceSet("alice");
    createPolicyFor("bob", resourceSetId, "SCOPE_A", "SCOPE_B");
    JsonValue policy = policyToUpdate(resourceSetId);
    Context context = getContext();
    //When
    Promise<UmaPolicy, ResourceException> promise = policyService.updatePolicy(context, resourceSetId, policy);
    //Then
    assertThat(promise).succeeded();
}
Also used : ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) SSOTokenContext(org.forgerock.openam.rest.resource.SSOTokenContext) Context(org.forgerock.services.context.Context) JsonValue(org.forgerock.json.JsonValue) ResourceException(org.forgerock.json.resource.ResourceException) Matchers.anyString(org.mockito.Matchers.anyString) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Test(org.testng.annotations.Test) UmaPolicyServiceImplTest(org.forgerock.openam.uma.rest.UmaPolicyServiceImplTest)

Example 14 with UmaPolicy

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

the class ResourceSetService method getResourceSets.

/**
     * Queries resource sets across the resource set store and UMA policy store.
     *
     * @param context             The context.
     * @param realm               The realm.
     * @param query               The aggregated query.
     * @param resourceOwnerId     The resource owner id.
     * @param augmentWithPolicies {@code true} to pull in UMA policies into the resource set.
     * @return A Promise containing the Resource Sets or a ResourceException.
     */
Promise<Collection<ResourceSetDescription>, ResourceException> getResourceSets(final Context context, String realm, final ResourceSetWithPolicyQuery query, final String resourceOwnerId, final boolean augmentWithPolicies) {
    final Set<ResourceSetDescription> resourceSets;
    try {
        resourceSets = new ResourceSetSharedFilter(this, resourceOwnerId, realm).filter(resourceSetStoreFactory.create(realm).query(query.getResourceSetQuery()));
    } catch (ServerException e) {
        return new InternalServerErrorException(e).asPromise();
    }
    QueryRequest policyQuery = newQueryRequest("").setQueryId("searchAll");
    policyQuery.setQueryFilter(QueryFilter.<JsonPointer>alwaysTrue());
    return getSharedResourceSets(context, policyQuery, resourceOwnerId).thenAsync(new AsyncFunction<Set<ResourceSetDescription>, Collection<ResourceSetDescription>, ResourceException>() {

        @Override
        public Promise<Collection<ResourceSetDescription>, ResourceException> apply(final Set<ResourceSetDescription> sharedResourceSets) {
            //combine the owned ResourceSets with the shared ones, then filter based on the query
            sharedResourceSets.addAll(resourceSets);
            final Collection<ResourceSetDescription> filteredResourceSets = filterPolicies(resourceSets, query);
            Promise<Collection<ResourceSetDescription>, ResourceException> resourceSetsPromise;
            if (query.getPolicyQuery() != null) {
                QueryRequest policyQuery = newQueryRequest("").setQueryFilter(query.getPolicyQuery());
                resourceSetsPromise = policyService.queryPolicies(context, policyQuery).thenAsync(new AsyncFunction<Pair<QueryResponse, Collection<UmaPolicy>>, Collection<ResourceSetDescription>, ResourceException>() {

                    @Override
                    public Promise<Collection<ResourceSetDescription>, ResourceException> apply(Pair<QueryResponse, Collection<UmaPolicy>> result) throws ResourceException {
                        try {
                            return newResultPromise(combine(context, query, filteredResourceSets, result.getSecond(), augmentWithPolicies, resourceOwnerId));
                        } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
                            return new InternalServerErrorException(e).asPromise();
                        } catch (ServerException e) {
                            return new InternalServerErrorException(e).asPromise();
                        }
                    }
                });
            } else {
                if (augmentWithPolicies) {
                    List<Promise<ResourceSetDescription, ResourceException>> promises = new ArrayList<>();
                    PromiseImpl<ResourceSetDescription, ResourceException> kicker = PromiseImpl.create();
                    promises.add(kicker);
                    for (ResourceSetDescription resourceSet : filteredResourceSets) {
                        promises.add(augmentWithPolicy(context, resourceSet.getId(), resourceSet));
                    }
                    resourceSetsPromise = Promises.when(promises).thenAsync(new AsyncFunction<List<ResourceSetDescription>, Collection<ResourceSetDescription>, ResourceException>() {

                        @Override
                        public Promise<Collection<ResourceSetDescription>, ResourceException> apply(List<ResourceSetDescription> resourceSets) {
                            Collection<ResourceSetDescription> resourceSetDescriptions = new HashSet<>();
                            for (ResourceSetDescription rs : filteredResourceSets) {
                                if (rs != null) {
                                    resourceSetDescriptions.add(rs);
                                }
                            }
                            return newResultPromise(resourceSetDescriptions);
                        }
                    });
                    kicker.handleResult(null);
                } else {
                    resourceSetsPromise = newResultPromise(filteredResourceSets);
                }
            }
            return resourceSetsPromise;
        }
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) 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) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) Requests.newQueryRequest(org.forgerock.json.resource.Requests.newQueryRequest) QueryRequest(org.forgerock.json.resource.QueryRequest) PromiseImpl(org.forgerock.util.promise.PromiseImpl) ResourceSetSharedFilter(org.forgerock.openam.uma.ResourceSetSharedFilter) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) QueryResponse(org.forgerock.json.resource.QueryResponse) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Collection(java.util.Collection)

Example 15 with UmaPolicy

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

the class UmaPolicyServiceImpl method queryPolicies.

/**
     * {@inheritDoc}
     */
@Override
public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> queryPolicies(final Context context, final QueryRequest umaQueryRequest) {
    if (umaQueryRequest.getQueryExpression() != null) {
        return new BadRequestException("Query expressions not supported").asPromise();
    }
    QueryRequest request = Requests.newQueryRequest("");
    final AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>> filter = umaQueryRequest.getQueryFilter().accept(new AggregateUmaPolicyQueryFilter(), new AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>>());
    String queryId = umaQueryRequest.getQueryId();
    if (queryId != null && queryId.equals("searchAll")) {
        request.setQueryFilter(QueryFilter.<JsonPointer>alwaysTrue());
    } else {
        String resourceOwnerUid = getResourceOwnerUid(context);
        if (filter.getFirstQuery() == null) {
            request.setQueryFilter(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid));
        } else {
            request.setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid), filter.getFirstQuery()));
        }
    }
    return policyResourceDelegate.queryPolicies(context, request).thenAsync(new AsyncFunction<Pair<QueryResponse, List<ResourceResponse>>, Collection<UmaPolicy>, ResourceException>() {

        @Override
        public Promise<Collection<UmaPolicy>, ResourceException> apply(Pair<QueryResponse, List<ResourceResponse>> value) {
            Map<String, Set<ResourceResponse>> policyMapping = new HashMap<>();
            for (ResourceResponse policy : value.getSecond()) {
                String resource = policy.getContent().get("resources").asList(String.class).get(0);
                if (!resource.startsWith(UMA_POLICY_SCHEME)) {
                    continue;
                }
                resource = resource.replaceFirst(UMA_POLICY_SCHEME, "");
                if (resource.indexOf(":") > 0) {
                    resource = resource.substring(0, resource.indexOf(":"));
                }
                Set<ResourceResponse> mapping = policyMapping.get(resource);
                if (mapping == null) {
                    mapping = new HashSet<>();
                    policyMapping.put(resource, mapping);
                }
                mapping.add(policy);
            }
            try {
                Collection<UmaPolicy> umaPolicies = new HashSet<>();
                for (Map.Entry<String, Set<ResourceResponse>> entry : policyMapping.entrySet()) {
                    ResourceSetDescription resourceSet = getResourceSetDescription(entry.getKey(), context);
                    UmaPolicy umaPolicy = UmaPolicy.fromUnderlyingPolicies(resourceSet, entry.getValue());
                    resolveUIDToUsername(umaPolicy.asJson());
                    umaPolicies.add(umaPolicy);
                }
                return newResultPromise(umaPolicies);
            } catch (ResourceException e) {
                return e.asPromise();
            }
        }
    }).thenAsync(new AsyncFunction<Collection<UmaPolicy>, Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException>() {

        @Override
        public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> apply(Collection<UmaPolicy> policies) {
            Collection<UmaPolicy> results = policies;
            if (filter.getSecondQuery() != null) {
                PolicySearch search = filter.getSecondQuery().accept(new UmaPolicyQueryFilterVisitor(), new PolicySearch(policies));
                if (AggregateQuery.Operator.AND.equals(filter.getOperator())) {
                    results.retainAll(search.getPolicies());
                }
            }
            int pageSize = umaQueryRequest.getPageSize();
            String pagedResultsCookie = umaQueryRequest.getPagedResultsCookie();
            int pagedResultsOffset = umaQueryRequest.getPagedResultsOffset();
            Collection<UmaPolicy> pagedPolicies = new HashSet<UmaPolicy>();
            int count = 0;
            for (UmaPolicy policy : results) {
                if (count >= pagedResultsOffset * pageSize) {
                    pagedPolicies.add(policy);
                }
                count++;
            }
            int remainingPagedResults = results.size() - pagedPolicies.size();
            if (pageSize > 0) {
                remainingPagedResults /= pageSize;
            }
            return newResultPromise(Pair.of(newQueryResponse(pagedResultsCookie, CountPolicy.EXACT, remainingPagedResults), pagedPolicies));
        }
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) JsonPointer(org.forgerock.json.JsonPointer) AsyncFunction(org.forgerock.util.AsyncFunction) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) List(java.util.List) ArrayList(java.util.ArrayList) ResourceException(org.forgerock.json.resource.ResourceException) PolicySearch(org.forgerock.openam.uma.PolicySearch) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) HashSet(java.util.HashSet) UmaPolicyQueryFilterVisitor(org.forgerock.openam.uma.UmaPolicyQueryFilterVisitor) QueryRequest(org.forgerock.json.resource.QueryRequest) Promise(org.forgerock.util.promise.Promise) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceResponse(org.forgerock.json.resource.ResourceResponse) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap)

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