Search in sources :

Example 1 with QueryFilter

use of org.forgerock.util.query.QueryFilter in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpointTest method shouldListResourceSetDescriptions.

@Test
@SuppressWarnings("unchecked")
public void shouldListResourceSetDescriptions() throws Exception {
    //Given
    Set<ResourceSetDescription> resourceSetDescriptions = new HashSet<ResourceSetDescription>();
    ResourceSetDescription resourceSetDescription = new ResourceSetDescription("RESOURCE_SET_ID", "CLIENT_ID", "RESOURCE_OWNER_ID", RESOURCE_SET_DESCRIPTION_CONTENT.asMap());
    ResourceSetDescription resourceSetDescription2 = new ResourceSetDescription("RESOURCE_SET_ID_2", "CLIENT_ID", "RESOURCE_OWNER_ID", RESOURCE_SET_DESCRIPTION_UPDATED_CONTENT.asMap());
    resourceSetDescriptions.add(resourceSetDescription);
    resourceSetDescriptions.add(resourceSetDescription2);
    noUriResourceSetId();
    noConditions();
    given(store.query(any(QueryFilter.class))).willReturn(resourceSetDescriptions);
    //When
    Representation responseRep = endpoint.readOrListResourceSet();
    //Then
    ArgumentCaptor<QueryFilter> queryParametersCaptor = ArgumentCaptor.forClass(QueryFilter.class);
    verify(store).query(queryParametersCaptor.capture());
    QueryFilter<String> query = queryParametersCaptor.getValue();
    Map<String, String> params = query.accept(QUERY_PARAMS_EXTRACTOR, new HashMap<String, String>());
    assertThat(params).contains(entry(ResourceSetTokenField.CLIENT_ID, "CLIENT_ID"), entry(ResourceSetTokenField.RESOURCE_OWNER_ID, "RESOURCE_OWNER_ID"));
    List<String> responseBody = (List<String>) new ObjectMapper().readValue(responseRep.getText(), List.class);
    assertThat(responseBody).contains("RESOURCE_SET_ID", "RESOURCE_SET_ID_2");
}
Also used : JacksonRepresentation(org.restlet.ext.jackson.JacksonRepresentation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) Representation(org.restlet.representation.Representation) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) QueryFilter(org.forgerock.util.query.QueryFilter) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 2 with QueryFilter

use of org.forgerock.util.query.QueryFilter in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpointTest method shouldNotCreateExistingResourceSetDescription.

@Test
@SuppressWarnings("unchecked")
public void shouldNotCreateExistingResourceSetDescription() throws Exception {
    //Given
    JsonRepresentation entity = createCreateRequestRepresentation();
    when(store.query(any(QueryFilter.class))).thenReturn(asSet(new ResourceSetDescription("id", "CLIENT_ID", "RESOURCE_OWNER_ID", RESOURCE_SET_DESCRIPTION_CONTENT.asMap())));
    noConditions();
    //When
    Representation result = endpoint.createResourceSet(entity);
    //Then
    ArgumentCaptor<QueryFilter> queryCaptor = ArgumentCaptor.forClass(QueryFilter.class);
    verify(store).query(queryCaptor.capture());
    verifyZeroInteractions(resourceRegistrationFilter);
    String queryString = queryCaptor.getValue().toString();
    assertThat(queryString).contains("name eq \"NAME\"").contains("clientId eq \"CLIENT_ID\"").contains("resourceOwnerId eq \"RESOURCE_OWNER_ID\"").doesNotContain(" or ");
    verify(response).setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    assertThat(result).isInstanceOf(JsonRepresentation.class);
    assertThat(((JsonRepresentation) result).getJsonObject().get("error")).isEqualTo("Bad Request");
    assertThat(((JsonRepresentation) result).getJsonObject().getString("error_description")).contains("'NAME' already exists");
}
Also used : QueryFilter(org.forgerock.util.query.QueryFilter) JacksonRepresentation(org.restlet.ext.jackson.JacksonRepresentation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) Representation(org.restlet.representation.Representation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Test(org.testng.annotations.Test)

Example 3 with QueryFilter

use of org.forgerock.util.query.QueryFilter in project OpenAM by OpenRock.

the class UpgradeResourceTypeStep method createResourceType.

/**
     * Create the resource type for the given application if a suitable resource type does not already exist.
     * @param state The state object that contains the various parameters for creating the resource type.
     * @param realm The realm in which the application and resource type resides.
     * @return The resource type if it could be created or {@code null} if it could not.
     * @throws UpgradeException If the application types could not be read.
     */
private ResourceType createResourceType(ResourceTypeState state, String realm) throws UpgradeException {
    final Set<QueryFilter<SmsAttribute>> actionFilters = transformSet(state.actions, new Function<String, QueryFilter<SmsAttribute>, NeverThrowsException>() {

        @Override
        public QueryFilter<SmsAttribute> apply(String value) {
            return QueryFilter.equalTo(ResourceTypeSmsAttributes.ACTIONS, value);
        }
    });
    final Set<QueryFilter<SmsAttribute>> patternFilters = transformSet(state.patterns, new Function<String, QueryFilter<SmsAttribute>, NeverThrowsException>() {

        @Override
        public QueryFilter<SmsAttribute> apply(String value) {
            return QueryFilter.equalTo(ResourceTypeSmsAttributes.PATTERNS, value);
        }
    });
    final Set<ResourceType> resourceTypes;
    try {
        resourceTypes = resourceTypeService.getResourceTypes(QueryFilter.and(QueryFilter.and(actionFilters), QueryFilter.and(patternFilters)), getAdminSubject(), realm);
    } catch (EntitlementException e) {
        throw new UpgradeException("Failed to retrieve resource type for " + state.appName, e);
    }
    if (!resourceTypes.isEmpty()) {
        // Some matching resource types have been found, return the first one.
        return resourceTypes.iterator().next();
    }
    ResourceType resourceType = ResourceType.builder().setName(state.appName + RESOURCES_TYPE_NAME_SUFFIX).addActions(getActions(state.actions)).addPatterns(state.patterns).setDescription(RESOURCE_TYPE_DESCRIPTION + state.appName).generateUUID().build();
    saveResourceType(resourceType, realm);
    state.resourceTypeName = resourceType.getName();
    return resourceType;
}
Also used : NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) UpgradeException(org.forgerock.openam.upgrade.UpgradeException) EntitlementException(com.sun.identity.entitlement.EntitlementException) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceType(org.forgerock.openam.entitlement.ResourceType)

Example 4 with QueryFilter

use of org.forgerock.util.query.QueryFilter in project OpenAM by OpenRock.

the class ResourceTypeConfigurationImpl method getResourceTypes.

@Override
public Set<ResourceType> getResourceTypes(final QueryFilter<SmsAttribute> queryFilter, final Subject subject, final String realm) throws EntitlementException {
    final SSOToken token = SubjectUtils.getSSOToken(subject);
    final String dn = getResourceTypeBaseDN(realm);
    final Filter filter = queryFilter.accept(new SmsQueryFilterVisitor(), null);
    final Set<ResourceType> resourceTypes = new HashSet<ResourceType>();
    try {
        if (SMSEntry.checkIfEntryExists(dn, token)) {
            // Interaction with legacy service.
            @SuppressWarnings("unchecked") final Iterator<SMSDataEntry> iterator = (Iterator<SMSDataEntry>) SMSEntry.search(token, dn, filter.toString(), 0, 0, false, false, Collections.emptySet());
            while (iterator.hasNext()) {
                final SMSDataEntry entry = iterator.next();
                final String name = entry.getAttributeValue(CONFIG_NAME);
                // Extract the resource types UUID from the LDAP DN representation.
                final String uuid = LDAPUtils.getName(DN.valueOf(entry.getDN()));
                // Interaction with legacy service.
                @SuppressWarnings("unchecked") final Set<String> actionSet = entry.getAttributeValues(CONFIG_ACTIONS);
                final Map<String, Boolean> actions = getActions(actionSet);
                // Interaction with legacy service.
                @SuppressWarnings("unchecked") final Set<String> resources = entry.getAttributeValues(CONFIG_PATTERNS);
                final String description = entry.getAttributeValue(CONFIG_DESCRIPTION);
                final String createdBy = entry.getAttributeValue(CONFIG_CREATED_BY);
                final String creationDate = entry.getAttributeValue(CONFIG_CREATION_DATE);
                final String modifiedBy = entry.getAttributeValue(CONFIG_LAST_MODIFIED_BY);
                final String modifiedDate = entry.getAttributeValue(CONFIG_LAST_MODIFIED_DATE);
                final ResourceType resourceType = ResourceType.builder().setUUID(uuid).setName(name).setActions(actions).setPatterns(resources).setDescription(description).setCreatedBy(createdBy).setCreationDate(Long.parseLong(creationDate)).setLastModifiedBy(modifiedBy).setLastModifiedDate(Long.parseLong(modifiedDate)).build();
                resourceTypes.add(resourceType);
            }
        }
    } catch (SMSException smsE) {
        throw new EntitlementException(RESOURCE_TYPE_RETRIEVAL_ERROR, realm, smsE);
    }
    return resourceTypes;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) SMSDataEntry(com.sun.identity.sm.SMSDataEntry) SMSException(com.sun.identity.sm.SMSException) ResourceType(org.forgerock.openam.entitlement.ResourceType) EntitlementException(com.sun.identity.entitlement.EntitlementException) Filter(org.forgerock.opendj.ldap.Filter) QueryFilter(org.forgerock.util.query.QueryFilter) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Example 5 with QueryFilter

use of org.forgerock.util.query.QueryFilter in project OpenAM by OpenRock.

the class ResourceSetServiceTest method shouldGetResourceSetsWhenResourceSetsExistQueryingByOrWithPolicies.

@Test
public void shouldGetResourceSetsWhenResourceSetsExistQueryingByOrWithPolicies() throws Exception {
    //Given
    Context context = createContext();
    String realm = "REALM";
    ResourceSetWithPolicyQuery query = new ResourceSetWithPolicyQuery();
    String resourceOwnerId = "RESOURCE_OWNER_ID";
    boolean augmentWithPolicies = true;
    QueryFilter<String> resourceSetQuery = QueryFilter.contains("name", "RS_THREE");
    QueryFilter policyQuery = QueryFilter.alwaysFalse();
    Set<ResourceSetDescription> queriedResourceSets = new HashSet<>();
    ResourceSetDescription resourceSetOne = new ResourceSetDescription("RS_ID_ONE", "CLIENT_ID_ONE", "RESOURCE_OWNER_ID", singletonMap("name", (Object) "RS_ONE"));
    ResourceSetDescription resourceSetTwo = new ResourceSetDescription("RS_ID_TWO", "CLIENT_ID_TWO", "RESOURCE_OWNER_ID", singletonMap("name", (Object) "RS_TWO"));
    ResourceSetDescription resourceSetThree = new ResourceSetDescription("RS_ID_THREE", "CLIENT_ID_TWO", "RESOURCE_OWNER_ID", singletonMap("name", (Object) "RS_THREE"));
    Collection<UmaPolicy> queriedPolicies = new HashSet<>();
    UmaPolicy policyOne = mock(UmaPolicy.class);
    UmaPolicy policyTwo = mock(UmaPolicy.class);
    UmaPolicy policyThree = mock(UmaPolicy.class);
    JsonValue policyOneJson = mock(JsonValue.class);
    JsonValue policyTwoJson = mock(JsonValue.class);
    JsonValue policyThreeJson = mock(JsonValue.class);
    Pair<QueryResponse, Collection<UmaPolicy>> queriedPoliciesPair = Pair.of(newQueryResponse(), queriedPolicies);
    Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> queriedPoliciesPromise = Promises.newResultPromise(queriedPoliciesPair);
    Promise<UmaPolicy, ResourceException> policyOnePromise = Promises.newResultPromise(policyOne);
    Promise<UmaPolicy, ResourceException> policyTwoPromise = Promises.newResultPromise(policyTwo);
    mockResourceOwnerIdentity(resourceOwnerId, realm);
    query.setResourceSetQuery(resourceSetQuery);
    query.setPolicyQuery(policyQuery);
    queriedResourceSets.add(resourceSetOne);
    queriedResourceSets.add(resourceSetTwo);
    queriedPolicies.add(policyOne);
    queriedPolicies.add(policyThree);
    given(policyOne.getId()).willReturn("RS_ID_ONE");
    given(policyOne.getResourceSet()).willReturn(resourceSetOne);
    given(policyTwo.getId()).willReturn("RS_ID_TWO");
    given(policyTwo.getResourceSet()).willReturn(resourceSetTwo);
    given(policyThree.getId()).willReturn("RS_ID_THREE");
    given(policyThree.getResourceSet()).willReturn(resourceSetThree);
    given(policyOne.asJson()).willReturn(policyOneJson);
    given(policyTwo.asJson()).willReturn(policyTwoJson);
    given(policyThree.asJson()).willReturn(policyThreeJson);
    given(resourceSetStore.query(QueryFilter.and(resourceSetQuery, equalTo(ResourceSetTokenField.RESOURCE_OWNER_ID, "RESOURCE_OWNER_ID")))).willReturn(queriedResourceSets);
    given(policyService.queryPolicies(eq(context), Matchers.<QueryRequest>anyObject())).willReturn(queriedPoliciesPromise);
    given(resourceSetStore.read("RS_ID_ONE", resourceOwnerId)).willReturn(resourceSetOne);
    given(resourceSetStore.read("RS_ID_THREE", resourceOwnerId)).willReturn(resourceSetThree);
    given(policyService.readPolicy(context, "RS_ID_ONE")).willReturn(policyOnePromise);
    given(policyService.readPolicy(context, "RS_ID_TWO")).willReturn(policyTwoPromise);
    Entitlement entitlement = new Entitlement();
    Map<String, Boolean> actionValues = new HashMap();
    actionValues.put("actionValueKey", true);
    entitlement.setActionValues(actionValues);
    Evaluator evaluator = mock(Evaluator.class);
    given(umaProviderSettings.getPolicyEvaluator(any(Subject.class), anyString())).willReturn(evaluator);
    given(evaluator.evaluate(eq(realm), any(Subject.class), eq("RS_ONE"), isNull(Map.class), eq(false))).willReturn(singletonList(entitlement));
    given(evaluator.evaluate(eq(realm), any(Subject.class), eq("RS_TWO"), isNull(Map.class), eq(false))).willReturn(singletonList(entitlement));
    given(evaluator.evaluate(eq(realm), any(Subject.class), eq("RS_THREE"), isNull(Map.class), eq(false))).willReturn(Collections.<Entitlement>emptyList());
    //When
    Collection<ResourceSetDescription> resourceSets = service.getResourceSets(context, realm, query, resourceOwnerId, augmentWithPolicies).getOrThrowUninterruptibly();
    //Then
    assertThat(resourceSets).hasSize(2).contains(resourceSetOne, resourceSetThree);
    assertThat(resourceSetOne.getPolicy()).isEqualTo(policyOneJson);
    assertThat(resourceSetThree.getPolicy()).isEqualTo(policyThreeJson);
}
Also used : HashMap(java.util.HashMap) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) ResourceException(org.forgerock.json.resource.ResourceException) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) HashSet(java.util.HashSet) Pair(org.forgerock.util.Pair) RootContext(org.forgerock.services.context.RootContext) RealmContext(org.forgerock.openam.rest.RealmContext) Context(org.forgerock.services.context.Context) JsonValue(org.forgerock.json.JsonValue) Evaluator(com.sun.identity.entitlement.Evaluator) Subject(javax.security.auth.Subject) QueryFilter(org.forgerock.util.query.QueryFilter) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) Collection(java.util.Collection) Entitlement(com.sun.identity.entitlement.Entitlement) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.testng.annotations.Test)

Aggregations

QueryFilter (org.forgerock.util.query.QueryFilter)16 Test (org.testng.annotations.Test)10 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)9 HashSet (java.util.HashSet)8 ResourceException (org.forgerock.json.resource.ResourceException)7 Collection (java.util.Collection)6 QueryResponse (org.forgerock.json.resource.QueryResponse)6 Responses.newQueryResponse (org.forgerock.json.resource.Responses.newQueryResponse)6 UmaPolicy (org.forgerock.openam.uma.UmaPolicy)6 Pair (org.forgerock.util.Pair)6 RealmContext (org.forgerock.openam.rest.RealmContext)5 Context (org.forgerock.services.context.Context)5 RootContext (org.forgerock.services.context.RootContext)5 CoreTokenField (org.forgerock.openam.tokens.CoreTokenField)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 JsonValue (org.forgerock.json.JsonValue)3 TokenFilterBuilder (org.forgerock.openam.cts.api.filter.TokenFilterBuilder)3 ResourceType (org.forgerock.openam.entitlement.ResourceType)3 Filter (org.forgerock.opendj.ldap.Filter)3