Search in sources :

Example 6 with JsonPointer

use of org.forgerock.json.JsonPointer in project OpenAM by OpenRock.

the class UmaPolicyServiceImplTest method shouldQueryUmaPoliciesBySubjectAndUnknownResourceServer.

@Test
@SuppressWarnings("unchecked")
public void shouldQueryUmaPoliciesBySubjectAndUnknownResourceServer() throws Exception {
    //Given
    Context context = createContext();
    QueryRequest request = Requests.newQueryRequest("").setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("permissions/subject"), "SUBJECT_ONE"), QueryFilter.equalTo(new JsonPointer("resourceServer"), "OTHER_CLIENT_ID")));
    mockBackendQuery(context);
    //When
    Pair<QueryResponse, Collection<UmaPolicy>> queryResult = policyService.queryPolicies(context, request).getOrThrowUninterruptibly();
    //Then
    assertThat(queryResult.getSecond()).hasSize(0);
}
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) QueryRequest(org.forgerock.json.resource.QueryRequest) QueryResponse(org.forgerock.json.resource.QueryResponse) Collection(java.util.Collection) JsonPointer(org.forgerock.json.JsonPointer) Test(org.testng.annotations.Test)

Example 7 with JsonPointer

use of org.forgerock.json.JsonPointer in project OpenAM by OpenRock.

the class UmaPolicyServiceImplDelegationTest method policyToUpdate.

private JsonValue policyToUpdate(String resourceSetId) {
    mockPolicyResourceDelegateForUpdatedPolicy();
    JsonValue umaPolicy = createUmaPolicyForResourceSet(resourceSetId);
    umaPolicy.remove(new JsonPointer("/permissions/0/scopes/1"));
    return umaPolicy;
}
Also used : JsonValue(org.forgerock.json.JsonValue) JsonPointer(org.forgerock.json.JsonPointer)

Example 8 with JsonPointer

use of org.forgerock.json.JsonPointer in project OpenAM by OpenRock.

the class PolicyGraph method moveScope.

/**
     * Moves the scopes that are incorrectly active/inactive to a policy that has the opposite state.
     * @param moveFrom A map of policy owners to policies the scope is incorrectly currently in.
     * @param moveTo A map of policy owner to existing policies the scope might be moved to.
     * @param context The context for passing to the policy resource delegate.
     * @param policyResourceDelegate To be used for deleting any policies that are emptied of scopes (actions).
     * @param allMovingRights All the scopes that need switching state.
     * @param createdPolicies Policies that are being created by this update.
     * @param updatedPolicies Policies that are being updated by this update.
     * @param scope The current scope being operated on.
     * @param newPolicyActive Whether the scope is being moved to active state.
     * @param promises Promises for all policy updates.
     * @param user The user for whom we are switching scope state.
     * @throws BadRequestException If the UmaPolicy cannot be created for new policy.
     */
private void moveScope(Map<String, JsonValue> moveFrom, Map<String, JsonValue> moveTo, Context context, PolicyResourceDelegate policyResourceDelegate, Set<String> allMovingRights, Set<JsonValue> createdPolicies, Set<JsonValue> updatedPolicies, String scope, boolean newPolicyActive, List<Promise<List<ResourceResponse>, ResourceException>> promises, String user) throws BadRequestException {
    JsonPointer scopePointer = new JsonPointer(BACKEND_POLICY_ACTION_VALUES_KEY).child(scope);
    for (Map.Entry<String, JsonValue> ownedPolicy : moveFrom.entrySet()) {
        String owner = ownedPolicy.getKey();
        JsonValue policy = ownedPolicy.getValue();
        JsonValue ownedMoveTo = moveTo.get(owner);
        boolean policyToMoveToAlreadyExists = ownedMoveTo != null;
        if (policyToMoveToAlreadyExists) {
            ownedMoveTo.put(scopePointer, true);
            // If this policy is being created already, no need to update.
            if (!createdPolicies.contains(ownedMoveTo)) {
                updatedPolicies.add(ownedMoveTo);
            }
            policy.remove(scopePointer);
        } else if (allScopesAreSwitchingState(allMovingRights, policy)) {
            policy.put(ACTIVE_KEY, true);
        } else {
            // Create a new policy to move to
            JsonValue newPolicy = UmaPolicy.valueOf(resourceSet, json(object(field(POLICY_ID_KEY, resourceSet.getId()), field(PERMISSIONS_KEY, array(object(field(SUBJECT_KEY, user), field(SCOPES_KEY, array(scope)))))))).asUnderlyingPolicies(owner).iterator().next();
            newPolicy.put(ACTIVE_KEY, newPolicyActive);
            createdPolicies.add(newPolicy);
            moveTo.put(owner, newPolicy);
            policy.remove(scopePointer);
        }
        if (policy.get(BACKEND_POLICY_ACTION_VALUES_KEY).size() == 0) {
            // No scopes left in the policy, so it can be removed.
            updatedPolicies.remove(policy);
            promises.add(policyResourceDelegate.deletePolicies(context, singleton(policy.get("_id").asString())));
        } else {
            updatedPolicies.add(policy);
        }
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) JsonPointer(org.forgerock.json.JsonPointer) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with JsonPointer

use of org.forgerock.json.JsonPointer 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)

Example 10 with JsonPointer

use of org.forgerock.json.JsonPointer in project OpenAM by OpenRock.

the class ResourceTypesResource method queryCollection.

/**
     * Reads the details of all {@link org.forgerock.openam.entitlement.ResourceType}s in the system.
     *
     * The user's {@link org.forgerock.json.resource.SecurityContext} must indicate they are a user with
     * administrator-level access.
     *
     * @param context {@inheritDoc}
     * @param request {@inheritDoc}
     * @param handler {@inheritDoc}
     */
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
    String principalName = "unknown";
    String realm = getRealm(context);
    QueryFilter<JsonPointer> queryFilter = request.getQueryFilter();
    try {
        Subject subject = getSubject(context);
        principalName = PrincipalRestUtils.getPrincipalNameFromSubject(subject);
        Map<String, Map<String, Set<String>>> configData = resourceTypeService.getResourceTypesData(subject, realm);
        Set<String> filterResults;
        if (queryFilter == null) {
            filterResults = configData.keySet();
        } else {
            filterResults = queryFilter.accept(new DataQueryFilterVisitor(), configData);
        }
        List<ResourceResponse> results = new ArrayList<>();
        for (String uuid : filterResults) {
            ResourceType resourceType = resourceTypeService.getResourceType(subject, realm, uuid);
            results.add(newResourceResponse(resourceType.getUUID(), null, new JsonResourceType(resourceType).toJsonValue()));
        }
        QueryResponsePresentation.enableDeprecatedRemainingQueryResponse(request);
        return QueryResponsePresentation.perform(handler, request, results);
    } catch (EntitlementException ee) {
        if (logger.errorEnabled()) {
            logger.error("ResourceTypesResource :: QUERY by " + principalName + ": Caused EntitlementException: ", ee);
        }
        return exceptionMappingHandler.handleError(context, request, ee).asPromise();
    } catch (QueryException e) {
        return new BadRequestException(e.getL10NMessage(ServerContextUtils.getLocaleFromContext(context))).asPromise();
    }
}
Also used : JsonResourceType(org.forgerock.openam.entitlement.rest.wrappers.JsonResourceType) JsonResourceType(org.forgerock.openam.entitlement.rest.wrappers.JsonResourceType) ResourceType(org.forgerock.openam.entitlement.ResourceType) JsonPointer(org.forgerock.json.JsonPointer) Subject(javax.security.auth.Subject) EntitlementException(com.sun.identity.entitlement.EntitlementException) QueryException(org.forgerock.openam.rest.query.QueryException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) DataQueryFilterVisitor(org.forgerock.openam.rest.query.DataQueryFilterVisitor)

Aggregations

JsonPointer (org.forgerock.json.JsonPointer)64 Test (org.testng.annotations.Test)40 QueryRequest (org.forgerock.json.resource.QueryRequest)34 JsonValue (org.forgerock.json.JsonValue)21 QueryResponse (org.forgerock.json.resource.QueryResponse)19 Context (org.forgerock.services.context.Context)18 RealmContext (org.forgerock.openam.rest.RealmContext)17 Collection (java.util.Collection)15 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)13 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)13 ClientContext (org.forgerock.services.context.ClientContext)13 Subject (javax.security.auth.Subject)10 ResourceException (org.forgerock.json.resource.ResourceException)10 ResourceResponse (org.forgerock.json.resource.ResourceResponse)10 ArrayList (java.util.ArrayList)9 BadRequestException (org.forgerock.json.resource.BadRequestException)9 SearchFilter (com.sun.identity.entitlement.util.SearchFilter)8 HashMap (java.util.HashMap)7 HashSet (java.util.HashSet)7 List (java.util.List)7