Search in sources :

Example 16 with Identity

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

the class HttpRequestSessionContextFactory method extractAuthorizedIdentity.

public Identity extractAuthorizedIdentity(Optional<Identity> optionalAuthenticatedIdentity, MultivaluedMap<String, String> headers, Optional<String> alternateHeaderName) throws AccessDeniedException {
    ProtocolHeaders protocolHeaders;
    try {
        protocolHeaders = detectProtocol(alternateHeaderName, headers.keySet());
    } catch (ProtocolDetectionException e) {
        throw badRequest(e.getMessage());
    }
    Identity identity = buildSessionIdentity(optionalAuthenticatedIdentity, protocolHeaders, headers);
    accessControl.checkCanSetUser(identity.getPrincipal(), identity.getUser());
    // authenticated may not present for HTTP or if authentication is not setup
    optionalAuthenticatedIdentity.ifPresent(authenticatedIdentity -> {
        // only check impersonation if authenticated user is not the same as the explicitly set user
        if (!authenticatedIdentity.getUser().equals(identity.getUser())) {
            // load enabled roles for authenticated identity, so impersonation permissions can be assigned to roles
            authenticatedIdentity = Identity.from(authenticatedIdentity).withEnabledRoles(metadata.listEnabledRoles(authenticatedIdentity)).build();
            accessControl.checkCanImpersonateUser(authenticatedIdentity, identity.getUser());
        }
    });
    return addEnabledRoles(identity, parseSystemRoleHeaders(protocolHeaders, headers), metadata);
}
Also used : ProtocolHeaders(io.trino.client.ProtocolHeaders) ProtocolDetectionException(io.trino.client.ProtocolDetectionException) Identity(io.trino.spi.security.Identity)

Example 17 with Identity

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

the class HttpRequestSessionContextFactory method createSessionContext.

public SessionContext createSessionContext(MultivaluedMap<String, String> headers, Optional<String> alternateHeaderName, Optional<String> remoteAddress, Optional<Identity> authenticatedIdentity) throws WebApplicationException {
    ProtocolHeaders protocolHeaders;
    try {
        protocolHeaders = detectProtocol(alternateHeaderName, headers.keySet());
    } catch (ProtocolDetectionException e) {
        throw badRequest(e.getMessage());
    }
    Optional<String> catalog = Optional.ofNullable(trimEmptyToNull(headers.getFirst(protocolHeaders.requestCatalog())));
    Optional<String> schema = Optional.ofNullable(trimEmptyToNull(headers.getFirst(protocolHeaders.requestSchema())));
    Optional<String> path = Optional.ofNullable(trimEmptyToNull(headers.getFirst(protocolHeaders.requestPath())));
    assertRequest((catalog.isPresent()) || (schema.isEmpty()), "Schema is set but catalog is not");
    requireNonNull(authenticatedIdentity, "authenticatedIdentity is null");
    Identity identity = buildSessionIdentity(authenticatedIdentity, protocolHeaders, headers);
    SelectedRole selectedRole = parseSystemRoleHeaders(protocolHeaders, headers);
    Optional<String> source = Optional.ofNullable(headers.getFirst(protocolHeaders.requestSource()));
    Optional<String> traceToken = Optional.ofNullable(trimEmptyToNull(headers.getFirst(protocolHeaders.requestTraceToken())));
    Optional<String> userAgent = Optional.ofNullable(headers.getFirst(USER_AGENT));
    Optional<String> remoteUserAddress = requireNonNull(remoteAddress, "remoteAddress is null");
    Optional<String> timeZoneId = Optional.ofNullable(headers.getFirst(protocolHeaders.requestTimeZone()));
    Optional<String> language = Optional.ofNullable(headers.getFirst(protocolHeaders.requestLanguage()));
    Optional<String> clientInfo = Optional.ofNullable(headers.getFirst(protocolHeaders.requestClientInfo()));
    Set<String> clientTags = parseClientTags(protocolHeaders, headers);
    Set<String> clientCapabilities = parseClientCapabilities(protocolHeaders, headers);
    ResourceEstimates resourceEstimates = parseResourceEstimate(protocolHeaders, headers);
    // parse session properties
    ImmutableMap.Builder<String, String> systemProperties = ImmutableMap.builder();
    Map<String, Map<String, String>> catalogSessionProperties = new HashMap<>();
    for (Entry<String, String> entry : parseSessionHeaders(protocolHeaders, headers).entrySet()) {
        String fullPropertyName = entry.getKey();
        String propertyValue = entry.getValue();
        List<String> nameParts = DOT_SPLITTER.splitToList(fullPropertyName);
        if (nameParts.size() == 1) {
            String propertyName = nameParts.get(0);
            assertRequest(!propertyName.isEmpty(), "Invalid %s header", protocolHeaders.requestSession());
            // catalog session properties cannot be validated until the transaction has stated, so we delay system property validation also
            systemProperties.put(propertyName, propertyValue);
        } else if (nameParts.size() == 2) {
            String catalogName = nameParts.get(0);
            String propertyName = nameParts.get(1);
            assertRequest(!catalogName.isEmpty(), "Invalid %s header", protocolHeaders.requestSession());
            assertRequest(!propertyName.isEmpty(), "Invalid %s header", protocolHeaders.requestSession());
            // catalog session properties cannot be validated until the transaction has stated
            catalogSessionProperties.computeIfAbsent(catalogName, id -> new HashMap<>()).put(propertyName, propertyValue);
        } else {
            throw badRequest(format("Invalid %s header", protocolHeaders.requestSession()));
        }
    }
    requireNonNull(catalogSessionProperties, "catalogSessionProperties is null");
    catalogSessionProperties = catalogSessionProperties.entrySet().stream().collect(toImmutableMap(Entry::getKey, entry -> ImmutableMap.copyOf(entry.getValue())));
    Map<String, String> preparedStatements = parsePreparedStatementsHeaders(protocolHeaders, headers);
    String transactionIdHeader = headers.getFirst(protocolHeaders.requestTransactionId());
    boolean clientTransactionSupport = transactionIdHeader != null;
    Optional<TransactionId> transactionId = parseTransactionId(transactionIdHeader);
    return new SessionContext(protocolHeaders, catalog, schema, path, authenticatedIdentity, identity, selectedRole, source, traceToken, userAgent, remoteUserAddress, timeZoneId, language, clientTags, clientCapabilities, resourceEstimates, systemProperties.buildOrThrow(), catalogSessionProperties, preparedStatements, transactionId, clientTransactionSupport, clientInfo);
}
Also used : ResourceEstimates(io.trino.spi.session.ResourceEstimates) HashMap(java.util.HashMap) SelectedRole(io.trino.spi.security.SelectedRole) ProtocolDetectionException(io.trino.client.ProtocolDetectionException) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) TransactionId(io.trino.transaction.TransactionId) ProtocolHeaders(io.trino.client.ProtocolHeaders) Entry(java.util.Map.Entry) Identity(io.trino.spi.security.Identity) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 18 with Identity

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

the class HttpRequestSessionContextFactory method buildSessionIdentity.

private Identity buildSessionIdentity(Optional<Identity> authenticatedIdentity, ProtocolHeaders protocolHeaders, MultivaluedMap<String, String> headers) {
    String trinoUser = trimEmptyToNull(headers.getFirst(protocolHeaders.requestUser()));
    String user = trinoUser != null ? trinoUser : authenticatedIdentity.map(Identity::getUser).orElse(null);
    assertRequest(user != null, "User must be set");
    SelectedRole systemRole = parseSystemRoleHeaders(protocolHeaders, headers);
    ImmutableSet.Builder<String> systemEnabledRoles = ImmutableSet.builder();
    if (systemRole.getType() == Type.ROLE) {
        systemEnabledRoles.add(systemRole.getRole().orElseThrow());
    }
    return authenticatedIdentity.map(identity -> Identity.from(identity).withUser(user)).orElseGet(() -> Identity.forUser(user)).withEnabledRoles(systemEnabledRoles.build()).withAdditionalConnectorRoles(parseConnectorRoleHeaders(protocolHeaders, headers)).withAdditionalExtraCredentials(parseExtraCredentials(protocolHeaders, headers)).withAdditionalGroups(groupProvider.getGroups(user)).build();
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) SelectedRole(io.trino.spi.security.SelectedRole) Identity(io.trino.spi.security.Identity)

Example 19 with Identity

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

the class InternalAuthenticationManager method handleInternalRequest.

public void handleInternalRequest(ContainerRequestContext request) {
    String subject;
    try {
        subject = parseJwt(request.getHeaders().getFirst(TRINO_INTERNAL_BEARER));
    } catch (JwtException e) {
        log.error(e, "Internal authentication failed");
        request.abortWith(Response.status(UNAUTHORIZED).type(TEXT_PLAIN_TYPE.toString()).build());
        return;
    } catch (RuntimeException e) {
        throw new RuntimeException("Authentication error", e);
    }
    Identity identity = Identity.forUser("<internal>").withPrincipal(new InternalPrincipal(subject)).build();
    setAuthenticatedIdentity(request, identity);
}
Also used : JwtException(io.jsonwebtoken.JwtException) ServletSecurityUtils.setAuthenticatedIdentity(io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity) Identity(io.trino.spi.security.Identity) InternalPrincipal(io.trino.server.security.InternalPrincipal)

Example 20 with Identity

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

the class FileBasedSystemAccessControl method checkCanSetCatalogSessionProperty.

@Override
public void checkCanSetCatalogSessionProperty(SystemSecurityContext context, String catalogName, String propertyName) {
    Identity identity = context.getIdentity();
    boolean allowed = canAccessCatalog(context, catalogName, READ_ONLY) && catalogSessionPropertyRules.stream().map(rule -> rule.match(identity.getUser(), identity.getEnabledRoles(), identity.getGroups(), catalogName, propertyName)).flatMap(Optional::stream).findFirst().orElse(false);
    if (!allowed) {
        denySetCatalogSessionProperty(propertyName);
    }
}
Also used : Identity(io.trino.spi.security.Identity)

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