Search in sources :

Example 1 with User

use of com.b2international.snowowl.core.identity.User 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 User

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

the class RemoteJob method run.

@Override
protected final IStatus run(IProgressMonitor monitor) {
    final ObjectMapper mapper = this.context.service(ObjectMapper.class);
    final IProgressMonitor trackerMonitor = this.context.service(RemoteJobTracker.class).createMonitor(id, monitor);
    try {
        // override user when necessary
        User user = context.service(User.class);
        if (User.isSystem(this.user)) {
            user = User.SYSTEM;
        } else if (!user.getUsername().equals(this.user)) {
            user = UserRequests.prepareGet(this.user).build().execute(this.context);
        }
        // seed the monitor instance into the current context, so the request can use it for progress reporting
        final ServiceProvider context = this.context.inject().bind(IProgressMonitor.class, trackerMonitor).bind(RemoteJob.class, this).bind(User.class, user).build();
        final Object response = request.execute(context);
        if (response != null) {
            final Class<? extends Object> responseType = response.getClass();
            if (Primitives.isWrapperType(responseType) || String.class.isAssignableFrom(responseType) || UUID.class.isAssignableFrom(responseType)) {
                this.response = toJson(mapper, ImmutableMap.of("value", response));
            } else {
                this.response = toJson(mapper, response);
            }
        }
        final IStatus status = (IStatus) getProperty(REQUEST_STATUS);
        return (status != null) ? status : Statuses.ok();
    } catch (OperationCanceledException e) {
        return Statuses.cancel();
    } catch (Throwable e) {
        final ApiError apiError;
        if (e instanceof ApiException) {
            apiError = ((ApiException) e).toApiError();
        } else {
            apiError = ApiError.builder(e.getMessage()).status(500).developerMessage("Exception caught while executing request in remote job.").addInfo("exception-class", e.getClass().getSimpleName()).build();
        }
        this.response = toJson(mapper, apiError);
        // XXX: Don't delete remote jobs with errors
        autoClean = false;
        return Statuses.error(CoreActivator.PLUGIN_ID, "Failed to execute long running request", e);
    } finally {
        if (autoClean) {
            context.service(RemoteJobTracker.class).requestDeletes(Collections.singleton(id));
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) User(com.b2international.snowowl.core.identity.User) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ApiError(com.b2international.commons.exceptions.ApiError) UUID(java.util.UUID) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiException(com.b2international.commons.exceptions.ApiException)

Example 3 with User

use of com.b2international.snowowl.core.identity.User 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 4 with User

use of com.b2international.snowowl.core.identity.User 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 5 with User

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

the class LdapIdentityProvider method searchUsers.

@Override
public Promise<Users> searchUsers(Collection<String> usernames, int limit) {
    final ImmutableList.Builder<User> resultBuilder = ImmutableList.builder();
    final String uidProp = conf.getUserIdProperty();
    InitialLdapContext context = null;
    NamingEnumeration<SearchResult> searchResultEnumeration = null;
    try {
        context = createLdapContext();
        Collection<LdapRole> ldapRoles = getAllLdapRoles(context);
        searchResultEnumeration = context.search(conf.getBaseDn(), conf.getUserFilter(), createSearchControls(ATTRIBUTE_DN, uidProp));
        for (final SearchResult searchResult : ImmutableList.copyOf(Iterators.forEnumeration(searchResultEnumeration))) {
            final Attributes attributes = searchResult.getAttributes();
            if (hasAttribute(attributes, uidProp)) {
                final String userName = (String) attributes.get(uidProp).get();
                final List<Role> userRoles = ldapRoles.stream().filter(role -> role.getUniqueMembers().contains(searchResult.getNameInNamespace())).map(role -> new Role(role.getName(), role.getPermissions())).collect(Collectors.toList());
                resultBuilder.add(new User(userName, userRoles));
            }
        }
        final List<User> users = resultBuilder.build().stream().sorted((u1, u2) -> u1.getUsername().compareTo(u2.getUsername())).filter(user -> usernames.isEmpty() || usernames.contains(user.getUsername())).limit(limit).collect(Collectors.toList());
        return Promise.immediate(new Users(users, limit, users.size()));
    } catch (final NamingException e) {
        LOG.error("Couldn't search users/roles due to LDAP communication error: {}", e.getMessage(), e);
        throw new SnowowlRuntimeException(e);
    } finally {
        closeNamingEnumeration(searchResultEnumeration);
        closeLdapContext(context);
    }
}
Also used : Iterables(com.google.common.collect.Iterables) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Promise(com.b2international.snowowl.core.events.util.Promise) LoggerFactory(org.slf4j.LoggerFactory) NamingException(javax.naming.NamingException) SearchControls(javax.naming.directory.SearchControls) Iterators(com.google.common.collect.Iterators) Attribute(javax.naming.directory.Attribute) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Permission(com.b2international.snowowl.core.identity.Permission) Context(javax.naming.Context) NoSuchElementException(java.util.NoSuchElementException) Hashtable(java.util.Hashtable) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) Logger(org.slf4j.Logger) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) DirContext(javax.naming.directory.DirContext) Role(com.b2international.snowowl.core.identity.Role) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) TreeMap(java.util.TreeMap) Attributes(javax.naming.directory.Attributes) Users(com.b2international.snowowl.core.identity.Users) NamingEnumeration(javax.naming.NamingEnumeration) User(com.b2international.snowowl.core.identity.User) Preconditions(com.google.common.base.Preconditions) Collections(java.util.Collections) SearchResult(javax.naming.directory.SearchResult) User(com.b2international.snowowl.core.identity.User) ImmutableList(com.google.common.collect.ImmutableList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) Users(com.b2international.snowowl.core.identity.Users) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Role(com.b2international.snowowl.core.identity.Role) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException)

Aggregations

User (com.b2international.snowowl.core.identity.User)9 Permission (com.b2international.snowowl.core.identity.Permission)7 Collection (java.util.Collection)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)3 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)3 Role (com.b2international.snowowl.core.identity.Role)3 IEventBus (com.b2international.snowowl.eventbus.IEventBus)3 Expression (com.b2international.index.query.Expression)2 Expressions (com.b2international.index.query.Expressions)2 ExpressionBuilder (com.b2international.index.query.Expressions.ExpressionBuilder)2 AuthorizedEventBus (com.b2international.snowowl.core.authorization.AuthorizedEventBus)2 Request (com.b2international.snowowl.core.events.Request)2 IdentityProvider (com.b2international.snowowl.core.identity.IdentityProvider)2 JWTGenerator (com.b2international.snowowl.core.identity.JWTGenerator)2 ResourceDocument (com.b2international.snowowl.core.internal.ResourceDocument)2 Strings (com.google.common.base.Strings)2 Iterables (com.google.common.collect.Iterables)2 Map (java.util.Map)2