Search in sources :

Example 26 with Identity

use of io.trino.spi.security.Identity in project trino by trinodb.

the class AuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext request) {
    if (InternalAuthenticationManager.isInternalRequest(request)) {
        internalAuthenticationManager.handleInternalRequest(request);
        return;
    }
    List<Authenticator> authenticators;
    if (request.getSecurityContext().isSecure()) {
        authenticators = this.authenticators;
    } else if (insecureAuthenticationOverHttpAllowed) {
        authenticators = ImmutableList.of(insecureAuthenticator);
    } else {
        throw new ForbiddenException("Authentication over HTTP is not enabled");
    }
    // try to authenticate, collecting errors and authentication headers
    Set<String> messages = new LinkedHashSet<>();
    Set<String> authenticateHeaders = new LinkedHashSet<>();
    for (Authenticator authenticator : authenticators) {
        Identity authenticatedIdentity;
        try {
            authenticatedIdentity = authenticator.authenticate(request);
        } catch (AuthenticationException e) {
            // Some authenticators (e.g. password) nest multiple internal authenticators.
            // Exceptions from additional failed login attempts are suppressed in the first exception
            Stream.concat(Stream.of(e), Arrays.stream(e.getSuppressed())).filter(ex -> ex instanceof AuthenticationException).map(AuthenticationException.class::cast).forEach(ex -> {
                if (ex.getMessage() != null) {
                    messages.add(ex.getMessage());
                }
                ex.getAuthenticateHeader().ifPresent(authenticateHeaders::add);
            });
            continue;
        }
        // authentication succeeded
        setAuthenticatedIdentity(request, authenticatedIdentity);
        return;
    }
    // authentication failed
    if (messages.isEmpty()) {
        messages.add("Unauthorized");
    }
    // The error string is used by clients for exception messages and
    // is presented to the end user, thus it should be a single line.
    String error = Joiner.on(" | ").join(messages);
    sendWwwAuthenticate(request, error, authenticateHeaders);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Arrays(java.util.Arrays) ForbiddenException(javax.ws.rs.ForbiddenException) Set(java.util.Set) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) ServletSecurityUtils.sendWwwAuthenticate(io.trino.server.ServletSecurityUtils.sendWwwAuthenticate) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Inject(javax.inject.Inject) Priority(javax.annotation.Priority) List(java.util.List) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Stream(java.util.stream.Stream) ImmutableList(com.google.common.collect.ImmutableList) InternalAuthenticationManager(io.trino.server.InternalAuthenticationManager) ServletSecurityUtils.setAuthenticatedIdentity(io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity) Identity(io.trino.spi.security.Identity) Objects.requireNonNull(java.util.Objects.requireNonNull) AUTHENTICATION(javax.ws.rs.Priorities.AUTHENTICATION) LinkedHashSet(java.util.LinkedHashSet) Joiner(com.google.common.base.Joiner) ForbiddenException(javax.ws.rs.ForbiddenException) ServletSecurityUtils.setAuthenticatedIdentity(io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity) Identity(io.trino.spi.security.Identity)

Example 27 with Identity

use of io.trino.spi.security.Identity in project trino by trinodb.

the class HeaderAuthenticator method authenticate.

@Override
public Identity authenticate(ContainerRequestContext request) throws AuthenticationException {
    AuthenticationException exception = null;
    Map<String, List<String>> lowerCasedHeaders = request.getHeaders().entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey().toLowerCase(Locale.ENGLISH), Map.Entry::getValue));
    for (io.trino.spi.security.HeaderAuthenticator authenticator : this.authenticatorManager.getAuthenticators()) {
        try {
            Principal principal = authenticator.createAuthenticatedPrincipal(name -> lowerCasedHeaders.get(name.toLowerCase(Locale.ENGLISH)));
            String authenticatedUser = this.userMapping.mapUser(principal.toString());
            return Identity.forUser(authenticatedUser).withPrincipal(principal).build();
        } catch (UserMappingException | AccessDeniedException e) {
            if (exception == null) {
                exception = new AuthenticationException(e.getMessage());
            } else {
                exception.addSuppressed(new AuthenticationException(e.getMessage()));
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("Authentication error", e);
        }
    }
    verify(exception != null, "exception is not set");
    throw exception;
}
Also used : AccessDeniedException(io.trino.spi.security.AccessDeniedException) List(java.util.List) Principal(java.security.Principal) Verify.verify(com.google.common.base.Verify.verify) Locale(java.util.Locale) Inject(com.google.inject.Inject) Identity(io.trino.spi.security.Identity) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) UserMapping.createUserMapping(io.trino.server.security.UserMapping.createUserMapping) Collectors(java.util.stream.Collectors) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) AccessDeniedException(io.trino.spi.security.AccessDeniedException) List(java.util.List) Map(java.util.Map) Principal(java.security.Principal)

Example 28 with Identity

use of io.trino.spi.security.Identity in project trino by trinodb.

the class CreateViewTask method execute.

@Override
public ListenableFuture<Void> execute(CreateView statement, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) {
    Session session = stateMachine.getSession();
    QualifiedObjectName name = createQualifiedObjectName(session, statement, statement.getName());
    accessControl.checkCanCreateView(session.toSecurityContext(), name);
    if (metadata.isMaterializedView(session, name)) {
        throw semanticException(TABLE_ALREADY_EXISTS, statement, "Materialized view already exists: '%s'", name);
    }
    if (metadata.isView(session, name)) {
        if (!statement.isReplace()) {
            throw semanticException(TABLE_ALREADY_EXISTS, statement, "View already exists: '%s'", name);
        }
    } else if (metadata.getTableHandle(session, name).isPresent()) {
        throw semanticException(TABLE_ALREADY_EXISTS, statement, "Table already exists: '%s'", name);
    }
    String sql = getFormattedSql(statement.getQuery(), sqlParser);
    Analysis analysis = analyzerFactory.createAnalyzer(session, parameters, parameterExtractor(statement, parameters), stateMachine.getWarningCollector()).analyze(statement);
    List<ViewColumn> columns = analysis.getOutputDescriptor(statement.getQuery()).getVisibleFields().stream().map(field -> new ViewColumn(field.getName().get(), field.getType().getTypeId())).collect(toImmutableList());
    // use DEFINER security by default
    Optional<Identity> owner = Optional.of(session.getIdentity());
    if (statement.getSecurity().orElse(null) == INVOKER) {
        owner = Optional.empty();
    }
    ViewDefinition definition = new ViewDefinition(sql, session.getCatalog(), session.getSchema(), columns, statement.getComment(), owner);
    metadata.createView(session, name, definition, statement.isReplace());
    stateMachine.setOutput(analysis.getTarget());
    stateMachine.setReferencedTables(analysis.getReferencedTables());
    return immediateVoidFuture();
}
Also used : CreateView(io.trino.sql.tree.CreateView) ViewColumn(io.trino.metadata.ViewColumn) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) INVOKER(io.trino.sql.tree.CreateView.Security.INVOKER) AnalyzerFactory(io.trino.sql.analyzer.AnalyzerFactory) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) Inject(javax.inject.Inject) TABLE_ALREADY_EXISTS(io.trino.spi.StandardErrorCode.TABLE_ALREADY_EXISTS) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) Identity(io.trino.spi.security.Identity) Objects.requireNonNull(java.util.Objects.requireNonNull) SqlParser(io.trino.sql.parser.SqlParser) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ViewDefinition(io.trino.metadata.ViewDefinition) List(java.util.List) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) AccessControl(io.trino.security.AccessControl) SqlFormatterUtil.getFormattedSql(io.trino.sql.SqlFormatterUtil.getFormattedSql) WarningCollector(io.trino.execution.warnings.WarningCollector) Metadata(io.trino.metadata.Metadata) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) Session(io.trino.Session) Analysis(io.trino.sql.analyzer.Analysis) Analysis(io.trino.sql.analyzer.Analysis) ViewColumn(io.trino.metadata.ViewColumn) ViewDefinition(io.trino.metadata.ViewDefinition) Identity(io.trino.spi.security.Identity) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) Session(io.trino.Session)

Aggregations

Identity (io.trino.spi.security.Identity)28 Objects.requireNonNull (java.util.Objects.requireNonNull)13 ImmutableSet (com.google.common.collect.ImmutableSet)12 List (java.util.List)12 Map (java.util.Map)12 Optional (java.util.Optional)12 SystemSecurityContext (io.trino.spi.security.SystemSecurityContext)10 Principal (java.security.Principal)10 Set (java.util.Set)10 ImmutableList (com.google.common.collect.ImmutableList)9 String.format (java.lang.String.format)9 TrinoException (io.trino.spi.TrinoException)8 SystemAccessControl (io.trino.spi.security.SystemAccessControl)8 Paths (java.nio.file.Paths)8 AccessDeniedException.denyImpersonateUser (io.trino.spi.security.AccessDeniedException.denyImpersonateUser)7 AccessDeniedException.denyReadSystemInformationAccess (io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess)7 Pattern (java.util.regex.Pattern)7 CatalogSchemaName (io.trino.spi.connector.CatalogSchemaName)6 CatalogSchemaTableName (io.trino.spi.connector.CatalogSchemaTableName)6 Suppliers.memoizeWithExpiration (com.google.common.base.Suppliers.memoizeWithExpiration)5