Search in sources :

Example 1 with Permission

use of org.apache.shiro.authz.Permission in project camel by apache.

the class ShiroSecurityProcessor method authorizeUser.

private void authorizeUser(Subject currentUser, Exchange exchange) throws CamelAuthorizationException {
    boolean authorized = false;
    if (!policy.getPermissionsList().isEmpty()) {
        if (policy.isAllPermissionsRequired()) {
            authorized = currentUser.isPermittedAll(policy.getPermissionsList());
        } else {
            for (Permission permission : policy.getPermissionsList()) {
                if (currentUser.isPermitted(permission)) {
                    authorized = true;
                    break;
                }
            }
        }
    } else if (!policy.getRolesList().isEmpty()) {
        if (policy.isAllRolesRequired()) {
            authorized = currentUser.hasAllRoles(policy.getRolesList());
        } else {
            for (String role : policy.getRolesList()) {
                if (currentUser.hasRole(role)) {
                    authorized = true;
                    break;
                }
            }
        }
    } else {
        LOG.trace("Valid Permissions or Roles List not specified for ShiroSecurityPolicy. " + "No authorization checks will be performed for current user.");
        authorized = true;
    }
    if (!authorized) {
        throw new CamelAuthorizationException("Authorization Failed. Subject's role set does " + "not have the necessary roles or permissions to perform further processing.", exchange);
    }
    LOG.debug("Current user {} is successfully authorized.", currentUser.getPrincipal());
}
Also used : CamelAuthorizationException(org.apache.camel.CamelAuthorizationException) Permission(org.apache.shiro.authz.Permission)

Example 2 with Permission

use of org.apache.shiro.authz.Permission in project camel by apache.

the class ShiroAuthorizationTest method createRouteBuilders.

@Override
protected RouteBuilder[] createRouteBuilders() throws Exception {
    return new RouteBuilder[] { new RouteBuilder() {

        public void configure() {
            List<Permission> permissionsList = new ArrayList<Permission>();
            Permission permission = new WildcardPermission("zone1:readwrite:*");
            permissionsList.add(permission);
            final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
            onException(CamelAuthorizationException.class).to("mock:authorizationException");
            from("direct:secureEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
        }
    }, new RouteBuilder() {

        public void configure() {
            List<Permission> permissionsList = new ArrayList<Permission>();
            Permission permission = new WildcardPermission("zone1:readonly:*");
            permissionsList.add(permission);
            permission = new WildcardPermission("zone1:writeonly:*");
            permissionsList.add(permission);
            final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
            onException(CamelAuthorizationException.class).to("mock:authorizationException");
            from("direct:secureAnyEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
        }
    }, new RouteBuilder() {

        public void configure() {
            List<Permission> permissionsList = new ArrayList<Permission>();
            Permission permission = new WildcardPermission("zone1:readonly:*");
            permissionsList.add(permission);
            permission = new WildcardPermission("zone1:writeonly:*");
            permissionsList.add(permission);
            final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
            securityPolicy.setAllPermissionsRequired(true);
            onException(CamelAuthorizationException.class).to("mock:authorizationException");
            from("direct:secureAllEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
        }
    } };
}
Also used : CamelAuthorizationException(org.apache.camel.CamelAuthorizationException) RouteBuilder(org.apache.camel.builder.RouteBuilder) ArrayList(java.util.ArrayList) Permission(org.apache.shiro.authz.Permission) WildcardPermission(org.apache.shiro.authz.permission.WildcardPermission) WildcardPermission(org.apache.shiro.authz.permission.WildcardPermission)

Example 3 with Permission

use of org.apache.shiro.authz.Permission in project ddf by codice.

the class MatchOneCollectionPermission method implies.

/**
     * Overrides the implies method to handle checking for the existence of one attribute - the
     * "match one" scenario rather than the "match all" behavior of the overridden classes.
     * Specifically, this permission will imply another permission if that permission matches at
     * least one of our permission attributes.
     *
     * @param p
     *            the permission to check for behavior/functionality comparison.
     * @return {@code true} if this current instance <em>implies</em> the specified
     *         {@code Permission} argument, {@code false} otherwise.
     */
@Override
public boolean implies(Permission p) {
    if (permissionList.isEmpty()) {
        return false;
    }
    if (p instanceof CollectionPermission) {
        for (Permission perm : ((CollectionPermission) p).getPermissionList()) {
            boolean result = false;
            for (Permission ourPerm : permissionList) {
                // the permission.
                if (ourPerm instanceof KeyValuePermission) {
                    for (String value : ((KeyValuePermission) ourPerm).getValues()) {
                        // Since this is "match one" we know that only one of these values needs
                        // to match in order
                        // for the entire permission at that key to be implied
                        // So here we loop through all of the values assigned to that key and
                        // create new
                        // single valued key value permissions
                        KeyValuePermission kvp = new KeyValuePermission(((KeyValuePermission) ourPerm).getKey());
                        kvp.addValue(value);
                        if (perm.implies(kvp)) {
                            result = true;
                            break;
                        }
                    }
                // Currently we use key value permissions for everything. However, we still need
                // to be able to handle
                // permissions other than KV, so this else block will serve as the catch all for
                // everything else.
                } else {
                    // the implies to make it match one
                    if (perm.implies(ourPerm)) {
                        result = true;
                        break;
                    }
                }
            }
            if (!result) {
                return false;
            }
        }
        return true;
    }
    // default catch all permission check
    for (Permission permission : permissionList) {
        // to make it match one
        if (p.implies(permission)) {
            return true;
        }
    }
    return false;
}
Also used : Permission(org.apache.shiro.authz.Permission)

Example 4 with Permission

use of org.apache.shiro.authz.Permission in project ddf by codice.

the class TestWorkspaceQueryService method testRun.

@SuppressWarnings("unchecked")
@Test
public void testRun() throws SchedulerException, UnsupportedQueryException, SourceUnavailableException, FederationException {
    String workspaceId = "3";
    QueryUpdateSubscriber queryUpdateSubscriber = mock(QueryUpdateSubscriber.class);
    WorkspaceService workspaceService = mock(WorkspaceService.class);
    CatalogFramework catalogFramework = mock(CatalogFramework.class);
    FilterBuilder filterBuilder = mock(FilterBuilder.class);
    Scheduler scheduler = mock(Scheduler.class);
    when(scheduler.getContext()).thenReturn(mock(SchedulerContext.class));
    Supplier<Optional<Scheduler>> schedulerSupplier = () -> Optional.of(scheduler);
    SecurityService securityService = new SecurityService() {

        @Override
        public Subject getSystemSubject() {
            return mock(Subject.class);
        }

        @Override
        public Map<String, Serializable> addSystemSubject(Map<String, Serializable> properties) {
            return properties;
        }
    };
    FilterService filterService = mock(FilterService.class);
    when(filterService.getModifiedDateFilter(any())).thenReturn(mock(Filter.class));
    when(filterBuilder.anyOf(Mockito.any(Filter.class))).thenReturn(mock(Or.class));
    when(filterBuilder.allOf(Mockito.<Filter>anyVararg())).thenReturn(mock(And.class));
    WorkspaceQueryServiceImpl workspaceQueryServiceImpl = new WorkspaceQueryServiceImpl(queryUpdateSubscriber, workspaceService, catalogFramework, filterBuilder, schedulerSupplier, securityService, filterService);
    workspaceQueryServiceImpl.setQueryTimeInterval(60);
    String ecql = "area( Polygon((10 10, 20 10, 20 20, 10 10)) ) BETWEEN 10000 AND 30000";
    WorkspaceMetacardImpl workspaceMetacard = mock(WorkspaceMetacardImpl.class);
    when(workspaceMetacard.getId()).thenReturn(workspaceId);
    QueryMetacardImpl queryMetacardWithSource = mock(QueryMetacardImpl.class);
    when(queryMetacardWithSource.getSources()).thenReturn(Collections.singletonList("SomeSource"));
    when(queryMetacardWithSource.getCql()).thenReturn(ecql);
    Attribute id1 = mock(Attribute.class);
    when(id1.getValue()).thenReturn("1");
    when(queryMetacardWithSource.getAttribute(Metacard.ID)).thenReturn(id1);
    QueryMetacardImpl queryMetacardWithoutSource = mock(QueryMetacardImpl.class);
    when(queryMetacardWithoutSource.getSources()).thenReturn(Collections.emptyList());
    when(queryMetacardWithoutSource.getCql()).thenReturn(ecql);
    Attribute id2 = mock(Attribute.class);
    when(id2.getValue()).thenReturn("2");
    when(queryMetacardWithoutSource.getAttribute(Metacard.ID)).thenReturn(id2);
    Map<String, Pair<WorkspaceMetacardImpl, List<QueryMetacardImpl>>> queryMetacards = Collections.singletonMap(id2.getValue().toString(), new ImmutablePair<>(workspaceMetacard, Arrays.asList(queryMetacardWithSource, queryMetacardWithoutSource)));
    when(workspaceService.getQueryMetacards()).thenReturn(queryMetacards);
    long hitCount1 = 10;
    long hitCount2 = 20;
    QueryResponse queryResponse = mock(QueryResponse.class);
    when(queryResponse.getHits()).thenReturn(hitCount1).thenReturn(hitCount2);
    when(catalogFramework.query(any())).thenReturn(queryResponse);
    workspaceQueryServiceImpl.setSubject(new Subject() {

        @Override
        public boolean isGuest() {
            return false;
        }

        @Override
        public Object getPrincipal() {
            return null;
        }

        @Override
        public PrincipalCollection getPrincipals() {
            return null;
        }

        @Override
        public boolean isPermitted(String s) {
            return false;
        }

        @Override
        public boolean isPermitted(Permission permission) {
            return false;
        }

        @Override
        public boolean[] isPermitted(String... strings) {
            return new boolean[0];
        }

        @Override
        public boolean[] isPermitted(List<Permission> list) {
            return new boolean[0];
        }

        @Override
        public boolean isPermittedAll(String... strings) {
            return false;
        }

        @Override
        public boolean isPermittedAll(Collection<Permission> collection) {
            return false;
        }

        @Override
        public void checkPermission(String s) throws AuthorizationException {
        }

        @Override
        public void checkPermission(Permission permission) throws AuthorizationException {
        }

        @Override
        public void checkPermissions(String... strings) throws AuthorizationException {
        }

        @Override
        public void checkPermissions(Collection<Permission> collection) throws AuthorizationException {
        }

        @Override
        public boolean hasRole(String s) {
            return false;
        }

        @Override
        public boolean[] hasRoles(List<String> list) {
            return new boolean[0];
        }

        @Override
        public boolean hasAllRoles(Collection<String> collection) {
            return false;
        }

        @Override
        public void checkRole(String s) throws AuthorizationException {
        }

        @Override
        public void checkRoles(Collection<String> collection) throws AuthorizationException {
        }

        @Override
        public void checkRoles(String... strings) throws AuthorizationException {
        }

        @Override
        public void login(AuthenticationToken authenticationToken) throws AuthenticationException {
        }

        @Override
        public boolean isAuthenticated() {
            return false;
        }

        @Override
        public boolean isRemembered() {
            return false;
        }

        @Override
        public Session getSession() {
            return null;
        }

        @Override
        public Session getSession(boolean b) {
            return null;
        }

        @Override
        public void logout() {
        }

        @Override
        public <V> V execute(Callable<V> callable) throws ExecutionException {
            try {
                return callable.call();
            } catch (Exception e) {
                throw new ExecutionException(e);
            }
        }

        @Override
        public void execute(Runnable runnable) {
        }

        @Override
        public <V> Callable<V> associateWith(Callable<V> callable) {
            return null;
        }

        @Override
        public Runnable associateWith(Runnable runnable) {
            return null;
        }

        @Override
        public void runAs(PrincipalCollection principalCollection) throws NullPointerException, IllegalStateException {
        }

        @Override
        public boolean isRunAs() {
            return false;
        }

        @Override
        public PrincipalCollection getPreviousPrincipals() {
            return null;
        }

        @Override
        public PrincipalCollection releaseRunAs() {
            return null;
        }
    });
    workspaceQueryServiceImpl.setCronString("0 0 0 * * ?");
    workspaceQueryServiceImpl.setQueryTimeoutMinutes(5L);
    workspaceQueryServiceImpl.run();
    ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class);
    verify(queryUpdateSubscriber).notify(argumentCaptor.capture());
    Map queryUpdateSubscriberArgumentRaw = argumentCaptor.getValue();
    Map<String, Pair<WorkspaceMetacardImpl, Long>> queryUpdateSubscriberArgument = (Map<String, Pair<WorkspaceMetacardImpl, Long>>) queryUpdateSubscriberArgumentRaw;
    assertThat(queryUpdateSubscriberArgument.get(workspaceId).getRight(), is(hitCount1 + hitCount2));
}
Also used : Serializable(java.io.Serializable) Or(org.opengis.filter.Or) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthorizationException(org.apache.shiro.authz.AuthorizationException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) QueryMetacardImpl(org.codice.ddf.catalog.ui.metacard.workspace.QueryMetacardImpl) CatalogFramework(ddf.catalog.CatalogFramework) SchedulerContext(org.quartz.SchedulerContext) Permission(org.apache.shiro.authz.Permission) Optional(java.util.Optional) WorkspaceService(org.codice.ddf.catalog.ui.query.monitor.api.WorkspaceService) And(org.opengis.filter.And) QueryUpdateSubscriber(org.codice.ddf.catalog.ui.query.monitor.api.QueryUpdateSubscriber) Map(java.util.Map) Attribute(ddf.catalog.data.Attribute) Scheduler(org.quartz.Scheduler) FilterService(org.codice.ddf.catalog.ui.query.monitor.api.FilterService) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) Callable(java.util.concurrent.Callable) FilterBuilder(ddf.catalog.filter.FilterBuilder) SecurityService(org.codice.ddf.catalog.ui.query.monitor.api.SecurityService) ExecutionException(org.apache.shiro.subject.ExecutionException) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Subject(ddf.security.Subject) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) SchedulerException(org.quartz.SchedulerException) FederationException(ddf.catalog.federation.FederationException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) ExecutionException(org.apache.shiro.subject.ExecutionException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) Filter(org.opengis.filter.Filter) QueryResponse(ddf.catalog.operation.QueryResponse) WorkspaceMetacardImpl(org.codice.ddf.catalog.ui.metacard.workspace.WorkspaceMetacardImpl) Session(org.apache.shiro.session.Session) Test(org.junit.Test)

Example 5 with Permission

use of org.apache.shiro.authz.Permission in project ddf by codice.

the class WorkspacePolicyExtensionTest method testShouldRemoveRolesAndEmailsWhenOverridden1.

@Test
public void testShouldRemoveRolesAndEmailsWhenOverridden1() {
    List<Permission> before = ImmutableList.of(RANDOM, ROLES, EMAILS);
    doReturn(before).when(match).getPermissionList();
    extension.setSystemUserAttribute(Constants.EMAIL_ADDRESS_CLAIM_URI);
    extension.setSystemUserAttributeValue("admin@localhost");
    CollectionPermission subject = subjectFrom(ADMIN_EMAIL);
    List<Permission> after = extension.isPermittedMatchAll(subject, match).getPermissionList();
    assertThat(after, is(ImmutableList.of(RANDOM)));
}
Also used : CollectionPermission(ddf.security.permission.CollectionPermission) KeyValuePermission(ddf.security.permission.KeyValuePermission) Permission(org.apache.shiro.authz.Permission) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) CollectionPermission(ddf.security.permission.CollectionPermission) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Test(org.junit.Test)

Aggregations

Permission (org.apache.shiro.authz.Permission)42 CollectionPermission (ddf.security.permission.CollectionPermission)22 KeyValueCollectionPermission (ddf.security.permission.KeyValueCollectionPermission)21 KeyValuePermission (ddf.security.permission.KeyValuePermission)20 Test (org.junit.Test)15 SimpleAuthorizationInfo (org.apache.shiro.authz.SimpleAuthorizationInfo)8 WildcardPermission (org.apache.shiro.authz.permission.WildcardPermission)8 ArrayList (java.util.ArrayList)7 KeyValuePermissionImpl (ddf.security.permission.impl.KeyValuePermissionImpl)6 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)5 ImmutableSet (com.google.common.collect.ImmutableSet)4 KeyValueCollectionPermissionImpl (ddf.security.permission.impl.KeyValueCollectionPermissionImpl)4 MatchOneCollectionPermission (ddf.security.permission.impl.MatchOneCollectionPermission)4 AuthorizationException (org.apache.shiro.authz.AuthorizationException)4 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 List (java.util.List)3 RolePermissionResolver (org.apache.shiro.authz.permission.RolePermissionResolver)3 GRN (org.graylog.grn.GRN)3 CaseSensitiveWildcardPermission (org.graylog.security.permissions.CaseSensitiveWildcardPermission)3