Search in sources :

Example 11 with DelegationPermission

use of com.sun.identity.delegation.DelegationPermission in project OpenAM by OpenRock.

the class PrivilegeAuthzModuleTest method crestPatchIsAllowed.

@Test
public void crestPatchIsAllowed() throws SSOException, DelegationException {
    // Given...
    final Set<String> actions = new HashSet<>(Arrays.asList("MODIFY"));
    final DelegationPermission permission = new DelegationPermission("/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS, DUMB_FUNC);
    given(factory.newInstance("/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS)).willReturn(permission);
    given(subjectContext.getCallerSSOToken()).willReturn(token);
    given(evaluator.isAllowed(eq(token), eq(permission), eq(ENVIRONMENT))).willReturn(true);
    JsonValue jsonValue = json(object(field("someKey", "someValue")));
    Promise<ResourceResponse, ResourceException> promise = Promises.newResultPromise(Responses.newResourceResponse("1", "1.0", jsonValue));
    given(provider.patchInstance(isA(Context.class), eq("123"), isA(PatchRequest.class))).willReturn(promise);
    // When...
    final FilterChain chain = AuthorizationFilters.createAuthorizationFilter(provider, module);
    final Router router = new Router();
    router.addRoute(RoutingMode.STARTS_WITH, Router.uriTemplate("/policies"), chain);
    final RealmContext context = new RealmContext(subjectContext);
    context.setSubRealm("abc", "abc");
    final PatchRequest request = Requests.newPatchRequest("/policies/123", PatchOperation.add("abc", "123"));
    Promise<ResourceResponse, ResourceException> result = router.handlePatch(context, request);
    // Then...
    assertThat(result).succeeded().withContent().stringAt("someKey").isEqualTo("someValue");
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) Context(org.forgerock.services.context.Context) RealmContext(org.forgerock.openam.rest.RealmContext) FilterChain(org.forgerock.json.resource.FilterChain) JsonValue(org.forgerock.json.JsonValue) Router(org.forgerock.json.resource.Router) Matchers.anyString(org.mockito.Matchers.anyString) PatchRequest(org.forgerock.json.resource.PatchRequest) DelegationPermission(com.sun.identity.delegation.DelegationPermission) ResourceResponse(org.forgerock.json.resource.ResourceResponse) ResourceException(org.forgerock.json.resource.ResourceException) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 12 with DelegationPermission

use of com.sun.identity.delegation.DelegationPermission in project OpenAM by OpenRock.

the class PrivilegeAuthzModuleTest method crestRequestNotAllowed.

@Test
public void crestRequestNotAllowed() throws SSOException, DelegationException {
    // Given...
    final Set<String> actions = new HashSet<>(Arrays.asList("MODIFY"));
    final DelegationPermission permission = new DelegationPermission("/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS, DUMB_FUNC);
    given(factory.newInstance("/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS)).willReturn(permission);
    given(subjectContext.getCallerSSOToken()).willReturn(token);
    given(evaluator.isAllowed(eq(token), eq(permission), eq(ENVIRONMENT))).willReturn(false);
    // When...
    final FilterChain chain = AuthorizationFilters.createAuthorizationFilter(provider, module);
    final Router router = new Router();
    router.addRoute(RoutingMode.STARTS_WITH, Router.uriTemplate("/policies"), chain);
    final RealmContext context = new RealmContext(subjectContext);
    context.setSubRealm("abc", "abc");
    final CreateRequest request = Requests.newCreateRequest("/policies", JsonValue.json(new Object()));
    Promise<ResourceResponse, ResourceException> promise = router.handleCreate(context, request);
    // Then...
    assertThat(promise).failedWithException().isInstanceOf(ForbiddenException.class);
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) ResourceResponse(org.forgerock.json.resource.ResourceResponse) CreateRequest(org.forgerock.json.resource.CreateRequest) FilterChain(org.forgerock.json.resource.FilterChain) Router(org.forgerock.json.resource.Router) ResourceException(org.forgerock.json.resource.ResourceException) Matchers.anyString(org.mockito.Matchers.anyString) DelegationPermission(com.sun.identity.delegation.DelegationPermission) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 13 with DelegationPermission

use of com.sun.identity.delegation.DelegationPermission in project OpenAM by OpenRock.

the class DelegationPolicyImpl method policyToPrivilege.

/**
     *  Converts a policy to a delegation privilege.
     * @param policy policy to be converted
     * @return priv <code>DelegationPrivilege</code> represting policy.
     */
private DelegationPrivilege policyToPrivilege(Policy policy) throws DelegationException {
    String pname = null;
    Set permissions = new HashSet();
    Set svalues = new HashSet();
    if (policy == null) {
        return null;
    }
    try {
        // get policy name, which is the privilege name as well
        pname = policy.getName();
        // get privilege subjects
        Set snames = policy.getSubjectNames();
        if ((snames != null) && (!snames.isEmpty())) {
            if (snames.contains(DELEGATION_AUTHN_USERS)) {
                svalues.add(AUTHN_USERS_ID);
            }
            if (snames.contains(DELEGATION_SUBJECT)) {
                Subject subject = policy.getSubject(DELEGATION_SUBJECT);
                Set values = subject.getValues();
                if (values != null) {
                    svalues.addAll(values);
                }
            }
        }
        if (DelegationManager.debug.messageEnabled()) {
            DelegationManager.debug.message("SubjectValues=" + svalues);
        }
        String realmName = null;
        String serviceName = null;
        String version = null;
        String configType = null;
        String subconfigName = null;
        String resource = null;
        Set actions = null;
        Set ruleNames = policy.getRuleNames();
        if ((ruleNames != null) && (!ruleNames.isEmpty())) {
            Iterator rit = ruleNames.iterator();
            while (rit.hasNext()) {
                String ruleName = (String) rit.next();
                // now try to get resource and action names
                Rule rule = policy.getRule(ruleName);
                String service = rule.getServiceTypeName();
                if (service.equalsIgnoreCase(DelegationManager.DELEGATION_SERVICE)) {
                    resource = rule.getResourceName();
                    actions = rule.getActionNames();
                    // required to construct a delegation permission
                    if (resource.startsWith(PREFIX)) {
                        String suffix = resource.substring(PREFIX.length());
                        if (suffix != null) {
                            StringTokenizer st = new StringTokenizer(suffix, DELIMITER);
                            realmName = st.nextToken();
                            if (st.hasMoreTokens()) {
                                serviceName = st.nextToken();
                                if (st.hasMoreTokens()) {
                                    version = st.nextToken();
                                    if (st.hasMoreTokens()) {
                                        configType = st.nextToken();
                                        if (st.hasMoreTokens()) {
                                            subconfigName = st.nextToken();
                                            while (st.hasMoreTokens()) {
                                                subconfigName += DELIMITER + st.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (DelegationManager.debug.messageEnabled()) {
                        DelegationManager.debug.message("DelegationPolicyImpl.policyToPrivilege(): " + "create DelegationPermission object with: " + "realm=" + realmName + "; service=" + serviceName + "; version=" + version + "; configType=" + configType + "; subconfig=" + subconfigName + "; actions=" + actions);
                    }
                    DelegationPermission dp = new DelegationPermission(realmName, serviceName, version, configType, subconfigName, actions, null);
                    permissions.add(dp);
                }
            }
        }
        return new DelegationPrivilege(pname, permissions, svalues);
    } catch (Exception e) {
        throw new DelegationException(e);
    }
}
Also used : DelegationPrivilege(com.sun.identity.delegation.DelegationPrivilege) StringTokenizer(java.util.StringTokenizer) Set(java.util.Set) HashSet(java.util.HashSet) Iterator(java.util.Iterator) DelegationException(com.sun.identity.delegation.DelegationException) Rule(com.sun.identity.policy.Rule) Subject(com.sun.identity.policy.interfaces.Subject) DelegationPermission(com.sun.identity.delegation.DelegationPermission) DelegationException(com.sun.identity.delegation.DelegationException) PolicyException(com.sun.identity.policy.PolicyException) SSOException(com.iplanet.sso.SSOException) IdRepoException(com.sun.identity.idm.IdRepoException) HashSet(java.util.HashSet)

Example 14 with DelegationPermission

use of com.sun.identity.delegation.DelegationPermission in project OpenAM by OpenRock.

the class RestUtils method isAdmin.

public static boolean isAdmin(Context context) {
    boolean isAdmin = false;
    try {
        String realm = context.asContext(RealmContext.class).getResolvedRealm();
        SSOToken userSSOToken = SSOTokenManager.getInstance().createSSOToken(getCookieFromServerContext(context));
        // Simple check to see if user is super user and if so dont need to perform delegation check
        if (SessionUtils.isAdmin(AccessController.doPrivileged(AdminTokenAction.getInstance()), userSSOToken)) {
            return true;
        }
        DelegationEvaluator delegationEvaluator = new DelegationEvaluatorImpl();
        DelegationPermission delegationPermission = new DelegationPermission();
        delegationPermission.setVersion("*");
        delegationPermission.setSubConfigName("default");
        delegationPermission.setOrganizationName(realm);
        delegationPermission.setActions(CollectionUtils.asSet("READ"));
        for (Iterator i = getServiceNames().iterator(); i.hasNext() && !isAdmin; ) {
            String name = (String) i.next();
            delegationPermission.setServiceName(name);
            isAdmin = delegationEvaluator.isAllowed(userSSOToken, delegationPermission, Collections.<String, Set<String>>emptyMap());
        }
    } catch (DelegationException | SSOException | SMSException e) {
        debug.error("RestUtils::Failed to determine if user is an admin", e);
    }
    return isAdmin;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) SMSException(com.sun.identity.sm.SMSException) DelegationEvaluator(com.sun.identity.delegation.DelegationEvaluator) DelegationException(com.sun.identity.delegation.DelegationException) SSOException(com.iplanet.sso.SSOException) DelegationPermission(com.sun.identity.delegation.DelegationPermission) DelegationEvaluatorImpl(com.sun.identity.delegation.DelegationEvaluatorImpl) Iterator(java.util.Iterator)

Example 15 with DelegationPermission

use of com.sun.identity.delegation.DelegationPermission in project OpenAM by OpenRock.

the class PrivilegeAuthzModule method evaluate.

/**
     * Given the calling context and the privilege definition attempts to authorise the calling subject.
     *
     * @param context
     *         the server context
     * @param definition
     *         the privilege definition
     *
     * @return the authorisation result
     */
protected Promise<AuthorizationResult, ResourceException> evaluate(final Context context, final PrivilegeDefinition definition) {
    // If no realm is specified default to the root realm.
    final String realm = (context.containsContext(RealmContext.class)) ? context.asContext(RealmContext.class).getResolvedRealm() : "/";
    final SubjectContext subjectContext = context.asContext(SubjectContext.class);
    final UriRouterContext routerContext = context.asContext(UriRouterContext.class);
    // Map the set of actions to a set of action strings.
    final Set<String> actions = transformSet(definition.getActions(), ACTION_TO_STRING_MAPPER);
    try {
        Session callerSession = subjectContext.getCallerSession();
        if (callerSession == null) {
            // you don't have a session so return access denied
            return Promises.newResultPromise(AuthorizationResult.accessDenied("No session for request."));
        }
        final String loggedInRealm = coreWrapper.convertOrgNameToRealmName(callerSession.getClientDomain());
        final DelegationPermission permissionRequest = permissionFactory.newInstance(loggedInRealm, REST, VERSION, routerContext.getMatchedUri(), definition.getCommonVerb(), actions, Collections.<String, String>emptyMap());
        if (evaluator.isAllowed(subjectContext.getCallerSSOToken(), permissionRequest, Collections.<String, Set<String>>emptyMap()) && loggedIntoValidRealm(realm, loggedInRealm)) {
            // Authorisation has been approved.
            return Promises.newResultPromise(AuthorizationResult.accessPermitted());
        }
    } catch (DelegationException dE) {
        return new InternalServerErrorException("Attempt to authorise the user has failed", dE).asPromise();
    } catch (SSOException e) {
        //you don't have a user so return access denied
        return Promises.newResultPromise(AuthorizationResult.accessDenied("No user supplied in request."));
    }
    return Promises.newResultPromise(AuthorizationResult.accessDenied("The user has insufficient privileges"));
}
Also used : Set(java.util.Set) CollectionUtils.transformSet(org.forgerock.openam.utils.CollectionUtils.transformSet) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) UriRouterContext(org.forgerock.http.routing.UriRouterContext) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) DelegationException(com.sun.identity.delegation.DelegationException) SSOException(com.iplanet.sso.SSOException) DelegationPermission(com.sun.identity.delegation.DelegationPermission) Session(com.iplanet.dpro.session.Session)

Aggregations

DelegationPermission (com.sun.identity.delegation.DelegationPermission)30 HashSet (java.util.HashSet)22 DelegationException (com.sun.identity.delegation.DelegationException)17 SSOException (com.iplanet.sso.SSOException)16 DelegationEvaluator (com.sun.identity.delegation.DelegationEvaluator)14 Set (java.util.Set)13 DelegationEvaluatorImpl (com.sun.identity.delegation.DelegationEvaluatorImpl)12 Test (org.testng.annotations.Test)12 FilterChain (org.forgerock.json.resource.FilterChain)9 ResourceException (org.forgerock.json.resource.ResourceException)9 Router (org.forgerock.json.resource.Router)9 RealmContext (org.forgerock.openam.rest.RealmContext)9 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)9 Matchers.anyString (org.mockito.Matchers.anyString)9 Context (org.forgerock.services.context.Context)8 SSOToken (com.iplanet.sso.SSOToken)7 Iterator (java.util.Iterator)6 JsonValue (org.forgerock.json.JsonValue)6 ResourceResponse (org.forgerock.json.resource.ResourceResponse)6 IdRepoException (com.sun.identity.idm.IdRepoException)4