Search in sources :

Example 16 with AccessDeniedException

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

the class UiQueryResource method failQuery.

private Response failQuery(QueryId queryId, TrinoException queryException, HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders) {
    requireNonNull(queryId, "queryId is null");
    try {
        BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId);
        checkCanKillQueryOwnedBy(sessionContextFactory.extractAuthorizedIdentity(servletRequest, httpHeaders, alternateHeaderName), queryInfo.getSession().toIdentity(), accessControl);
        // check before killing to provide the proper error code (this is racy)
        if (queryInfo.getState().isDone()) {
            return Response.status(Status.CONFLICT).build();
        }
        dispatchManager.failQuery(queryId, queryException);
        return Response.status(Status.ACCEPTED).build();
    } catch (AccessDeniedException e) {
        throw new ForbiddenException();
    } catch (NoSuchElementException e) {
        return Response.status(Status.GONE).build();
    }
}
Also used : AccessDeniedException(io.trino.spi.security.AccessDeniedException) ForbiddenException(javax.ws.rs.ForbiddenException) BasicQueryInfo(io.trino.server.BasicQueryInfo) NoSuchElementException(java.util.NoSuchElementException)

Example 17 with AccessDeniedException

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

the class DefaultJdbcMetadata method listTableColumns.

@Override
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) {
    ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder();
    List<SchemaTableName> tables = prefix.toOptionalSchemaTableName().<List<SchemaTableName>>map(ImmutableList::of).orElseGet(() -> listTables(session, prefix.getSchema()));
    for (SchemaTableName tableName : tables) {
        try {
            jdbcClient.getTableHandle(session, tableName).ifPresent(tableHandle -> columns.put(tableName, getTableMetadata(session, tableHandle).getColumns()));
        } catch (TableNotFoundException | AccessDeniedException e) {
        // table disappeared during listing operation or user is not allowed to access it
        // these exceptions are ignored because listTableColumns is used for metadata queries (SELECT FROM information_schema)
        }
    }
    return columns.buildOrThrow();
}
Also used : TableNotFoundException(io.trino.spi.connector.TableNotFoundException) AccessDeniedException(io.trino.spi.security.AccessDeniedException) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) SchemaTableName(io.trino.spi.connector.SchemaTableName) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap)

Example 18 with AccessDeniedException

use of io.trino.spi.security.AccessDeniedException 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 19 with AccessDeniedException

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

the class SalesforceBasicAuthenticator method doLogin.

// This does the work of logging into Salesforce.
private Principal doLogin(Credential credential) {
    log.debug("Logging into Salesforce.");
    String username = credential.getUser();
    String password = credential.getPassword();
    // Login requests must be POSTs
    String loginSoapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<env:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" + "xmlns:urn=\"urn:enterprise.soap.sforce.com\"\n" + "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "   xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <env:Header>\n" + "     <urn:CallOptions>\n" + "       <urn:client>presto</urn:client>\n" + "     </urn:CallOptions>\n" + " </env:Header>\n" + " <env:Body>\n" + "   <n1:login xmlns:n1=\"urn:partner.soap.sforce.com\">\n" + "     <n1:username>%s</n1:username>\n" + "     <n1:password>%s</n1:password>\n" + "   </n1:login>\n" + " </env:Body>\n" + "</env:Envelope>\n";
    String apiVersion = "46.0";
    String loginUrl = "https://login.salesforce.com/services/Soap/u/";
    Escaper escaper = xmlContentEscaper();
    Request request = new Request.Builder().setUri(URI.create(loginUrl + apiVersion)).setHeader("Content-Type", "text/xml;charset=UTF-8").setHeader("SOAPAction", "login").setMethod("POST").setBodyGenerator(createStaticBodyGenerator(format(loginSoapMessage, escaper.escape(username), escaper.escape(password)), UTF_8)).build();
    StringResponseHandler.StringResponse response = httpClient.execute(request, StringResponseHandler.createStringResponseHandler());
    if (response.getStatusCode() != 200) {
        throw new AccessDeniedException(format("Invalid response for login\n.%s", response.getBody()));
    }
    Document xmlResponse;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        xmlResponse = builder.parse(new InputSource(new StringReader(response.getBody())));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new RuntimeException(format("Error parsing response: %s\n\tReceived error message: %s", response.getBody(), e.getMessage()));
    }
    // Make sure a Session Id has been returned.
    getElementValue(xmlResponse, "sessionId");
    // We want the organizationId from the response to compare it to the configured org from password-authenticator.properties.
    String returnedOrg = getElementValue(xmlResponse, "organizationId");
    // The organizationId is always in Locale.US, regardless of the user's locale and language.
    if (!allowedOrganizations.equals(ImmutableSet.of("all"))) {
        if (!allowedOrganizations.contains(returnedOrg.toLowerCase(Locale.US))) {
            throw new AccessDeniedException(format("Login successful, but for wrong Salesforce org.  Got %s, but expected a different org.", returnedOrg));
        }
    }
    return new BasicPrincipal(username);
}
Also used : AccessDeniedException(io.trino.spi.security.AccessDeniedException) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) StringResponseHandler(io.airlift.http.client.StringResponseHandler) BasicPrincipal(io.trino.spi.security.BasicPrincipal) DocumentBuilder(javax.xml.parsers.DocumentBuilder) CacheBuilder(com.google.common.cache.CacheBuilder) Request(io.airlift.http.client.Request) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Escaper(com.google.common.escape.Escaper) XmlEscapers.xmlContentEscaper(com.google.common.xml.XmlEscapers.xmlContentEscaper)

Aggregations

AccessDeniedException (io.trino.spi.security.AccessDeniedException)19 ForbiddenException (javax.ws.rs.ForbiddenException)7 ResourceSecurity (io.trino.server.security.ResourceSecurity)5 Path (javax.ws.rs.Path)5 QueryInfo (io.trino.execution.QueryInfo)3 NoSuchElementException (java.util.NoSuchElementException)3 GET (javax.ws.rs.GET)3 Test (org.testng.annotations.Test)3 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 BasicQueryInfo (io.trino.server.BasicQueryInfo)2 QueryId (io.trino.spi.QueryId)2 InMemoryTransactionManager.createTestTransactionManager (io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager)2 TransactionManager (io.trino.transaction.TransactionManager)2 Principal (java.security.Principal)2 List (java.util.List)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Verify.verify (com.google.common.base.Verify.verify)1