Search in sources :

Example 6 with Entitlement

use of com.sun.identity.entitlement.Entitlement in project OpenAM by OpenRock.

the class MultipleResourceRestTest method setup.

@BeforeClass
public void setup() throws Exception {
    PrivilegeManager pm = PrivilegeManager.getInstance(REALM, adminSubject);
    {
        Privilege privilege = Privilege.getNewInstance();
        privilege.setName(PRIVILEGE_NAME + "1");
        Map<String, Boolean> actions = new HashMap<String, Boolean>();
        actions.put("GET", true);
        Entitlement entitlement = new Entitlement(RESOURCE_NAME + "/*", actions);
        privilege.setEntitlement(entitlement);
        EntitlementSubject sbj = new AuthenticatedUsers();
        privilege.setSubject(sbj);
        pm.add(privilege);
    }
    {
        Privilege privilege = Privilege.getNewInstance();
        privilege.setName(PRIVILEGE_NAME + "2");
        Map<String, Boolean> actions = new HashMap<String, Boolean>();
        actions.put("GET", false);
        Entitlement entitlement = new Entitlement(RESOURCE_NAME + "/index.html", actions);
        privilege.setEntitlement(entitlement);
        EntitlementSubject sbj = new AuthenticatedUsers();
        privilege.setSubject(sbj);
        pm.add(privilege);
    }
    String tokenId = adminToken.getTokenID().toString();
    hashedTokenId = Hash.hash(tokenId);
    tokenIdHeader = RestServiceManager.SSOTOKEN_SUBJECT_PREFIX + RestServiceManager.SUBJECT_DELIMITER + tokenId;
    String cookieValue = tokenId;
    if (Boolean.parseBoolean(SystemProperties.get(Constants.AM_COOKIE_ENCODE, "false"))) {
        cookieValue = URLEncoder.encode(tokenId, "UTF-8");
    }
    cookie = new Cookie(SystemProperties.get(Constants.AM_COOKIE_NAME), cookieValue);
    user = IdRepoUtils.createUser(REALM, "MultipleResourceRestTestUser");
    decisionsClient = Client.create().resource(SystemProperties.getServerInstanceName() + "/ws/1/entitlement/decisions");
    entitlementsClient = Client.create().resource(SystemProperties.getServerInstanceName() + "/ws/1/entitlement/entitlements");
}
Also used : EntitlementSubject(com.sun.identity.entitlement.EntitlementSubject) Cookie(javax.ws.rs.core.Cookie) AuthenticatedUsers(org.forgerock.openam.entitlement.conditions.subject.AuthenticatedUsers) PrivilegeManager(com.sun.identity.entitlement.PrivilegeManager) Privilege(com.sun.identity.entitlement.Privilege) JSONEntitlement(com.sun.identity.entitlement.JSONEntitlement) Entitlement(com.sun.identity.entitlement.Entitlement) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) BeforeClass(org.testng.annotations.BeforeClass)

Example 7 with Entitlement

use of com.sun.identity.entitlement.Entitlement in project OpenAM by OpenRock.

the class PolicyResource method actionCollection.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest actionRequest) {
    final String actionString = actionRequest.getAction();
    final PolicyAction action = PolicyAction.getAction(actionString);
    if (!PolicyAction.isEvaluateAction(action)) {
        final String errorMsg = "Action '" + actionString + "' not implemented for this resource";
        final NotSupportedException nsE = new NotSupportedException(errorMsg);
        DEBUG.error(errorMsg, nsE);
        return nsE.asPromise();
    }
    try {
        if (DEBUG.messageEnabled()) {
            DEBUG.message("Rendering policy request for action " + actionString);
        }
        final PolicyRequest request = requestFactory.buildRequest(action, context, actionRequest);
        final PolicyEvaluator evaluator = factory.getEvaluator(request.getRestSubject(), request.getApplication());
        if (DEBUG.messageEnabled()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Evaluating policy request for action ");
            builder.append(actionString);
            builder.append(" under realm ");
            builder.append(request.getRealm());
            builder.append(" within the application context ");
            builder.append(request.getApplication());
            DEBUG.message(builder.toString());
        }
        final List<Entitlement> entitlements = evaluator.routePolicyRequest(request);
        return newResultPromise(newActionResponse(policyParser.printEntitlements(entitlements)));
    } catch (final EntitlementException eE) {
        DEBUG.error("Error evaluating policy request", eE);
        return resourceErrorHandler.handleError(context, actionRequest, eE).asPromise();
    }
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) Entitlement(com.sun.identity.entitlement.Entitlement) PolicyRequest(org.forgerock.openam.entitlement.rest.model.json.PolicyRequest)

Example 8 with Entitlement

use of com.sun.identity.entitlement.Entitlement in project OpenAM by OpenRock.

the class DataStore method add.

/**
     * Adds a privilege.
     *
     * @param adminSubject Admin Subject who has the rights to write to
     *        datastore.
     * @param realm Realm name.
     * @param p Privilege object.
     * @return the DN of added privilege.
     * @throws com.sun.identity.entitlement.EntitlementException if privilege
     * cannot be added.
     */
public String add(Subject adminSubject, String realm, Privilege p) throws EntitlementException {
    ResourceSaveIndexes indexes = p.getEntitlement().getResourceSaveIndexes(adminSubject, realm);
    Set<String> subjectIndexes = SubjectAttributesManager.getSubjectSearchIndexes(p);
    String dn = null;
    try {
        createDefaultSubConfig(adminToken, realm, null);
        dn = getPrivilegeDistinguishedName(p.getName(), realm, null);
        SMSEntry s = new SMSEntry(adminToken, dn);
        Map<String, Set<String>> map = new HashMap<String, Set<String>>();
        Set<String> searchable = new HashSet<String>();
        map.put(SMSEntry.ATTR_XML_KEYVAL, searchable);
        searchable.add(Privilege.RESOURCE_TYPE_UUID_ATTRIBUTE + "=" + p.getResourceTypeUuid());
        if (indexes != null) {
            for (String i : indexes.getHostIndexes()) {
                searchable.add(HOST_INDEX_KEY + "=" + i);
            }
            for (String i : indexes.getPathIndexes()) {
                searchable.add(PATH_INDEX_KEY + "=" + i);
            }
            for (String i : indexes.getParentPathIndexes()) {
                searchable.add(PATH_PARENT_INDEX_KEY + "=" + i);
            }
            for (String i : subjectIndexes) {
                searchable.add(SUBJECT_INDEX_KEY + "=" + i);
            }
        }
        Set<String> setServiceID = new HashSet<String>(2);
        map.put(SMSEntry.ATTR_SERVICE_ID, setServiceID);
        setServiceID.add("indexes");
        Set<String> set = new HashSet<String>(2);
        map.put(SMSEntry.ATTR_KEYVAL, set);
        set.add(SERIALIZABLE_INDEX_KEY + "=" + p.toJSONObject().toString());
        Set<String> setObjectClass = new HashSet<String>(4);
        map.put(SMSEntry.ATTR_OBJECTCLASS, setObjectClass);
        setObjectClass.add(SMSEntry.OC_TOP);
        setObjectClass.add(SMSEntry.OC_SERVICE_COMP);
        Set<String> info = new HashSet<String>(8);
        String privilegeName = p.getName();
        if (privilegeName != null) {
            info.add(Privilege.NAME_ATTRIBUTE + "=" + privilegeName);
        }
        String privilegeDesc = p.getDescription();
        if (privilegeDesc != null) {
            info.add(Privilege.DESCRIPTION_ATTRIBUTE + "=" + privilegeDesc);
        }
        String createdBy = p.getCreatedBy();
        if (createdBy != null) {
            info.add(Privilege.CREATED_BY_ATTRIBUTE + "=" + createdBy);
        }
        String lastModifiedBy = p.getLastModifiedBy();
        if (lastModifiedBy != null) {
            info.add(Privilege.LAST_MODIFIED_BY_ATTRIBUTE + "=" + lastModifiedBy);
        }
        long creationDate = p.getCreationDate();
        if (creationDate > 0) {
            String data = Long.toString(creationDate) + "=" + Privilege.CREATION_DATE_ATTRIBUTE;
            info.add(data);
            info.add("|" + data);
        }
        long lastModifiedDate = p.getLastModifiedDate();
        if (lastModifiedDate > 0) {
            String data = Long.toString(lastModifiedDate) + "=" + Privilege.LAST_MODIFIED_DATE_ATTRIBUTE;
            info.add(data);
            info.add("|" + data);
        }
        Entitlement ent = p.getEntitlement();
        info.add(Privilege.APPLICATION_ATTRIBUTE + "=" + ent.getApplicationName());
        for (String a : p.getApplicationIndexes()) {
            info.add(Privilege.APPLICATION_ATTRIBUTE + "=" + a);
        }
        map.put("ou", info);
        s.setAttributes(map);
        s.save();
        Map<String, String> params = new HashMap<String, String>();
        params.put(NotificationServlet.ATTR_NAME, privilegeName);
        params.put(NotificationServlet.ATTR_REALM_NAME, realm);
        Notifier.submit(NotificationServlet.PRIVILEGE_ADDED, params);
        updateIndexCount(realm, 1, false);
    } catch (JSONException e) {
        throw new EntitlementException(210, e);
    } catch (SSOException e) {
        throw new EntitlementException(210, e);
    } catch (SMSException e) {
        throw new EntitlementException(210, e);
    }
    return dn;
}
Also used : HashSet(java.util.HashSet) Collections.emptySet(java.util.Collections.emptySet) Set(java.util.Set) HashMap(java.util.HashMap) SMSException(com.sun.identity.sm.SMSException) JSONException(org.json.JSONException) SSOException(com.iplanet.sso.SSOException) ResourceSaveIndexes(com.sun.identity.entitlement.ResourceSaveIndexes) EntitlementException(com.sun.identity.entitlement.EntitlementException) SMSEntry(com.sun.identity.sm.SMSEntry) Entitlement(com.sun.identity.entitlement.Entitlement) HashSet(java.util.HashSet)

Example 9 with Entitlement

use of com.sun.identity.entitlement.Entitlement 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)

Example 10 with Entitlement

use of com.sun.identity.entitlement.Entitlement in project OpenAM by OpenRock.

the class OpenSSOPrivilege method internalEvaluate.

private List<Entitlement> internalEvaluate(Subject adminSubject, String realm, Subject subject, String applicationName, String resourceName, Set<String> actionNames, Map<String, Set<String>> environment, boolean recursive) throws EntitlementException {
    Entitlement originalEntitlement = getEntitlement();
    if (!isActive()) {
        Entitlement entitlement = new Entitlement(originalEntitlement.getApplicationName(), originalEntitlement.getResourceName(), Collections.<String>emptySet());
        return Arrays.asList(entitlement);
    }
    // First evaluate subject conditions.
    SubjectDecision subjectDecision = doesSubjectMatch(adminSubject, realm, subject, resourceName, environment);
    if (!subjectDecision.isSatisfied()) {
        Entitlement entitlement = new Entitlement(originalEntitlement.getApplicationName(), originalEntitlement.getResourceName(), Collections.<String>emptySet());
        entitlement.setAdvices(subjectDecision.getAdvices());
        return Arrays.asList(entitlement);
    }
    // Second evaluate environment conditions.
    ConditionDecision conditionDecision = doesConditionMatch(realm, subject, resourceName, environment);
    if (!conditionDecision.isSatisfied()) {
        Entitlement entitlement = new Entitlement(originalEntitlement.getApplicationName(), originalEntitlement.getResourceName(), Collections.<String>emptySet());
        entitlement.setAdvices(conditionDecision.getAdvice());
        entitlement.setTTL(conditionDecision.getTimeToLive());
        return Arrays.asList(entitlement);
    }
    // Finally verify the resource.
    Set<String> matchedResources = originalEntitlement.evaluate(adminSubject, realm, subject, applicationName, resourceName, actionNames, environment, recursive);
    if (PolicyConstants.DEBUG.messageEnabled()) {
        PolicyConstants.DEBUG.message("[PolicyEval] OpenSSOPrivilege.evaluate: resources=" + matchedResources);
    }
    // Retrieve the collection of response attributes base on the resource.
    Map<String, Set<String>> attributes = getAttributes(adminSubject, realm, subject, resourceName, environment);
    squashMaps(attributes, conditionDecision.getResponseAttributes());
    List<Entitlement> results = new ArrayList<>();
    for (String matchedResource : matchedResources) {
        Entitlement entitlement = new Entitlement(originalEntitlement.getApplicationName(), matchedResource, originalEntitlement.getActionValues());
        entitlement.setAdvices(conditionDecision.getAdvice());
        entitlement.setAttributes(attributes);
        entitlement.setTTL(conditionDecision.getTimeToLive());
        results.add(entitlement);
    }
    return results;
}
Also used : Set(java.util.Set) SubjectDecision(com.sun.identity.entitlement.SubjectDecision) ArrayList(java.util.ArrayList) Entitlement(com.sun.identity.entitlement.Entitlement) ConditionDecision(com.sun.identity.entitlement.ConditionDecision)

Aggregations

Entitlement (com.sun.identity.entitlement.Entitlement)43 Privilege (com.sun.identity.entitlement.Privilege)19 HashMap (java.util.HashMap)19 HashSet (java.util.HashSet)19 EntitlementSubject (com.sun.identity.entitlement.EntitlementSubject)14 Test (org.testng.annotations.Test)14 Subject (javax.security.auth.Subject)13 EntitlementException (com.sun.identity.entitlement.EntitlementException)12 Evaluator (com.sun.identity.entitlement.Evaluator)9 Set (java.util.Set)9 JsonValue (org.forgerock.json.JsonValue)9 EntitlementCondition (com.sun.identity.entitlement.EntitlementCondition)8 SSOToken (com.iplanet.sso.SSOToken)7 OrSubject (com.sun.identity.entitlement.OrSubject)6 PrivilegeManager (com.sun.identity.entitlement.PrivilegeManager)6 ResourceAttribute (com.sun.identity.entitlement.ResourceAttribute)6 SSOException (com.iplanet.sso.SSOException)5 OpenSSOPrivilege (com.sun.identity.entitlement.opensso.OpenSSOPrivilege)5 OpenSSOUserSubject (com.sun.identity.entitlement.opensso.OpenSSOUserSubject)5 AuthenticatedUsers (org.forgerock.openam.entitlement.conditions.subject.AuthenticatedUsers)5