Search in sources :

Example 1 with Permission

use of com.b2international.snowowl.core.identity.Permission in project snow-owl by b2ihealthcare.

the class CommitInfoSearchRequest method addSecurityFilter.

private void addSecurityFilter(final ExpressionBuilder builder, RepositoryContext context) {
    final User user = context.service(User.class);
    if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) {
        return;
    }
    final List<Permission> readPermissions = user.getPermissions().stream().filter(p -> Permission.ALL.equals(p.getOperation()) || Permission.OPERATION_BROWSE.equals(p.getOperation())).collect(Collectors.toList());
    final Set<String> exactResourceIds = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> !resource.endsWith("*")).collect(Collectors.toSet());
    final Set<String> resourceIdPrefixes = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> isWildCardResource(resource)).map(resource -> resource.substring(0, resource.length() - 1)).collect(Collectors.toSet());
    SetView<String> resourceIds = Sets.union(exactResourceIds, resourceIdPrefixes);
    ExpressionBuilder branchFilter = Expressions.builder();
    ResourceRequests.prepareSearch().filterByIds(resourceIds).setLimit(resourceIds.size()).setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE).buildAsync().getRequest().execute(context).stream().filter(TerminologyResource.class::isInstance).map(TerminologyResource.class::cast).forEach(r -> {
        if (resourceIdPrefixes.contains(r.getId())) {
            final String branchPattern = String.format("%s(/[a-zA-Z0-9.~_\\-]{1,%d})?", r.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH);
            branchFilter.should(regexp(BRANCH, branchPattern));
        }
    });
    builder.filter(branchFilter.build());
}
Also used : TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Expressions(com.b2international.index.revision.Commit.Expressions) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) ResourceRequests(com.b2international.snowowl.core.request.ResourceRequests) Hits(com.b2international.index.Hits) DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH(com.b2international.index.revision.RevisionBranch.DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH) Collection(java.util.Collection) Set(java.util.Set) Commit(com.b2international.index.revision.Commit) SetView(com.google.common.collect.Sets.SetView) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ResourceDocument(com.b2international.snowowl.core.internal.ResourceDocument) Expressions.regexp(com.b2international.index.query.Expressions.regexp) List(java.util.List) SearchIndexResourceRequest(com.b2international.snowowl.core.request.SearchIndexResourceRequest) Expressions(com.b2international.index.query.Expressions) Permission.isWildCardResource(com.b2international.snowowl.core.identity.Permission.isWildCardResource) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder) Expression(com.b2international.index.query.Expression) Permission(com.b2international.snowowl.core.identity.Permission) User(com.b2international.snowowl.core.identity.User) BRANCH(com.b2international.index.revision.Commit.Fields.BRANCH) User(com.b2international.snowowl.core.identity.User) Permission(com.b2international.snowowl.core.identity.Permission) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder)

Example 2 with Permission

use of com.b2international.snowowl.core.identity.Permission in project snow-owl by b2ihealthcare.

the class CommitInfoRequestTest method searchCommitInfoByBranch.

@Test
public void searchCommitInfoByBranch() {
    final String oid = UUID.randomUUID().toString();
    final String shortName = "Resource6";
    final String comment = "Code system for commit info 6";
    final String branchName = "Test6";
    final String term = "Test Description 6";
    createCodeSystem(shortName, oid, comment);
    final String branchPath = createBranch(String.format("%s/%s", BRANCH, shortName), branchName);
    createDescription(ResourceURI.branch(CodeSystem.RESOURCE_TYPE, shortName, branchName), term, comment);
    // Search as admin
    assertEquals(1, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByBranch(branchPath).build(REPOSITORY_ID).execute(bus).getSync().getTotal());
    final Permission userPermission = Permission.requireAll(Permission.OPERATION_BROWSE, String.format("%s*", shortName));
    final List<Role> roles = List.of(new Role("Editor", List.of(userPermission)));
    final String userName = "User6";
    final User user = new User(userName, roles);
    final IEventBus authorizedBus = new AuthorizedEventBus(bus, ImmutableMap.of(AuthorizedRequest.AUTHORIZATION_HEADER, Services.service(JWTGenerator.class).generate(user)));
    // Search as user with limited permissions
    assertEquals(1, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByBranch(branchPath).build(REPOSITORY_ID).execute(authorizedBus).getSync().getTotal());
}
Also used : Role(com.b2international.snowowl.core.identity.Role) User(com.b2international.snowowl.core.identity.User) JWTGenerator(com.b2international.snowowl.core.identity.JWTGenerator) Permission(com.b2international.snowowl.core.identity.Permission) AuthorizedEventBus(com.b2international.snowowl.core.authorization.AuthorizedEventBus) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Test(org.junit.Test)

Example 3 with Permission

use of com.b2international.snowowl.core.identity.Permission in project snow-owl by b2ihealthcare.

the class AuthorizedRequest method execute.

@Override
public R execute(ServiceProvider context) {
    final RequestHeaders requestHeaders = context.service(RequestHeaders.class);
    final String authorizationToken = requestHeaders.header(AUTHORIZATION_HEADER);
    final IdentityProvider identityProvider = context.service(IdentityProvider.class);
    final Collection<Request<?, ?>> requests = getNestedRequests();
    final User user;
    // if there is no authentication configured
    if (IdentityProvider.NOOP == identityProvider) {
        // allow execution as SYSTEM user
        user = User.SYSTEM;
    } else if (Strings.isNullOrEmpty(authorizationToken)) {
        // allow login requests in
        if (requests.stream().allMatch(req -> req.getClass().isAnnotationPresent(Unprotected.class))) {
            user = User.SYSTEM;
        } else {
            // if there is authentication configured, but no authorization token found prevent execution and throw UnauthorizedException
            if (PlatformUtil.isDevVersion()) {
                Request<?, ?> request = Iterables.getFirst(requests, null);
                System.err.println(request);
            }
            throw new UnauthorizedException("Missing authorization token");
        }
    } else {
        // verify authorization header value
        user = context.service(AuthorizationHeaderVerifier.class).auth(authorizationToken);
        if (user == null) {
            throw new UnauthorizedException("Incorrect authorization token");
        }
    }
    ServiceProvider userContext = context.inject().bind(User.class, user).bind(IEventBus.class, new AuthorizedEventBus(context.service(IEventBus.class), requestHeaders.headers())).build();
    if (!User.SYSTEM.equals(user) && !user.isAdministrator()) {
        // authorize user whether it is permitted to execute the request(s) or not
        requests.stream().filter(AccessControl.class::isInstance).map(AccessControl.class::cast).flatMap(ac -> {
            List<Permission> permissions = ac.getPermissions(userContext, next());
            if (permissions.isEmpty()) {
                context.log().warn("No permissions required to execute request '{}'.", MonitoredRequest.toJson(context, next(), Map.of()));
            }
            return permissions.stream();
        }).forEach(permissionRequirement -> {
            if (!user.hasPermission(permissionRequirement)) {
                throw new ForbiddenException("Operation not permitted. '%s' permission is required. User has '%s'.", permissionRequirement.getPermission(), user.getPermissions());
            }
        });
    }
    return next(userContext);
}
Also used : ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) Iterables(com.google.common.collect.Iterables) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Strings(com.google.common.base.Strings) List(java.util.List) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) PlatformUtil(com.b2international.snowowl.core.util.PlatformUtil) Map(java.util.Map) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) Permission(com.b2international.snowowl.core.identity.Permission) User(com.b2international.snowowl.core.identity.User) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) User(com.b2international.snowowl.core.identity.User) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) Request(com.b2international.snowowl.core.events.Request) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) List(java.util.List) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) IEventBus(com.b2international.snowowl.eventbus.IEventBus)

Example 4 with Permission

use of com.b2international.snowowl.core.identity.Permission in project snow-owl by b2ihealthcare.

the class LdapIdentityProvider method getAllLdapRoles.

protected Collection<LdapRole> getAllLdapRoles(InitialLdapContext context) throws NamingException {
    NamingEnumeration<SearchResult> enumeration = null;
    try {
        final ImmutableList.Builder<LdapRole> results = ImmutableList.builder();
        final String permissionProperty = conf.getPermissionProperty();
        final String memberProperty = conf.getMemberProperty();
        enumeration = context.search(conf.getRoleBaseDn(), conf.getRoleFilter(), createSearchControls(ATTR_CN, permissionProperty, memberProperty));
        NamingEnumeration<?> permissionEnumeration = null;
        NamingEnumeration<?> uniqueMemberEnumeration = null;
        for (final SearchResult searchResult : ImmutableList.copyOf(Iterators.forEnumeration(enumeration))) {
            final Attributes attributes = searchResult.getAttributes();
            final String name = (String) attributes.get(ATTR_CN).get();
            final ImmutableList.Builder<String> uniqueMembers = ImmutableList.builder();
            final ImmutableList.Builder<Permission> permissions = ImmutableList.builder();
            try {
                permissionEnumeration = getNamingEnumeration(attributes, permissionProperty);
                uniqueMemberEnumeration = getNamingEnumeration(attributes, memberProperty);
                // process permissions
                for (final Object permission : ImmutableList.copyOf(Iterators.forEnumeration(permissionEnumeration))) {
                    if ("unused".equals(permission)) {
                        continue;
                    }
                    permissions.add(Permission.valueOf(((String) permission).trim()));
                }
                // process members
                for (final Object member : ImmutableList.copyOf(Iterators.forEnumeration(uniqueMemberEnumeration))) {
                    uniqueMembers.add((String) member);
                }
            } finally {
                closeNamingEnumeration(permissionEnumeration);
                closeNamingEnumeration(uniqueMemberEnumeration);
            }
            results.add(new LdapRole(name, permissions.build(), uniqueMembers.build()));
        }
        return results.build();
    } finally {
        closeNamingEnumeration(enumeration);
    }
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) Attributes(javax.naming.directory.Attributes) Permission(com.b2international.snowowl.core.identity.Permission) SearchResult(javax.naming.directory.SearchResult)

Example 5 with Permission

use of com.b2international.snowowl.core.identity.Permission in project snow-owl by b2ihealthcare.

the class CommitInfoRequestTest method searchCommitOnSubBranch.

@Test
public void searchCommitOnSubBranch() {
    // Search with no branch filter, to test security filter for user with limited resources
    final String oid = UUID.randomUUID().toString();
    final String shortName = "Resource7";
    final String comment = "Code system for commit info 7";
    final String branchName = "Test7";
    final String commitComment = "Create Description 7";
    final String term = "Test Description 7";
    // Commit on resource branch
    createCodeSystem(shortName, oid, comment);
    createDescription(ResourceURI.of(CodeSystem.RESOURCE_TYPE, shortName), term, commitComment);
    // Commit on version branch
    final String branchPath = createBranch(String.format("%s/%s", BRANCH, shortName), branchName);
    createDescription(ResourceURI.branch(CodeSystem.RESOURCE_TYPE, shortName, branchName), term, commitComment);
    // Commit on deeper branch
    final String newBranchName = String.format("%s/%s", branchName, branchName);
    createBranch(branchPath, branchName);
    createDescription(ResourceURI.branch(CodeSystem.RESOURCE_TYPE, shortName, newBranchName), term, commitComment);
    final Permission userPermission = Permission.requireAll(Permission.OPERATION_BROWSE, String.format("%s*", shortName));
    final List<Role> roles = List.of(new Role("Editor", List.of(userPermission)));
    final String userName = "User7";
    final User user = new User(userName, roles);
    final IEventBus authorizedBus = new AuthorizedEventBus(bus, ImmutableMap.of(AuthorizedRequest.AUTHORIZATION_HEADER, Services.service(JWTGenerator.class).generate(user)));
    // Search as user with permission only to access the resource and one sub branch
    assertEquals(2, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByComment(commitComment).build(REPOSITORY_ID).execute(authorizedBus).getSync().getTotal());
    // Search as admin user with permission to access all
    assertEquals(3, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByComment(commitComment).build(REPOSITORY_ID).execute(bus).getSync().getTotal());
}
Also used : Role(com.b2international.snowowl.core.identity.Role) User(com.b2international.snowowl.core.identity.User) JWTGenerator(com.b2international.snowowl.core.identity.JWTGenerator) Permission(com.b2international.snowowl.core.identity.Permission) AuthorizedEventBus(com.b2international.snowowl.core.authorization.AuthorizedEventBus) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Test(org.junit.Test)

Aggregations

Permission (com.b2international.snowowl.core.identity.Permission)6 User (com.b2international.snowowl.core.identity.User)5 IEventBus (com.b2international.snowowl.eventbus.IEventBus)3 Collection (java.util.Collection)3 List (java.util.List)3 Expression (com.b2international.index.query.Expression)2 Expressions (com.b2international.index.query.Expressions)2 ExpressionBuilder (com.b2international.index.query.Expressions.ExpressionBuilder)2 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)2 AuthorizedEventBus (com.b2international.snowowl.core.authorization.AuthorizedEventBus)2 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)2 JWTGenerator (com.b2international.snowowl.core.identity.JWTGenerator)2 Role (com.b2international.snowowl.core.identity.Role)2 ResourceDocument (com.b2international.snowowl.core.internal.ResourceDocument)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 Test (org.junit.Test)2 ForbiddenException (com.b2international.commons.exceptions.ForbiddenException)1 UnauthorizedException (com.b2international.commons.exceptions.UnauthorizedException)1 Hits (com.b2international.index.Hits)1