Search in sources :

Example 16 with TransactionId

use of io.trino.transaction.TransactionId in project trino by trinodb.

the class TestAccessControlManager method testReadOnlySystemAccessControl.

@Test
public void testReadOnlySystemAccessControl() {
    Identity identity = Identity.forUser(USER_NAME).withPrincipal(PRINCIPAL).build();
    QualifiedObjectName tableName = new QualifiedObjectName("catalog", "schema", "table");
    TransactionManager transactionManager = createTestTransactionManager();
    AccessControlManager accessControlManager = createAccessControlManager(transactionManager);
    accessControlManager.setSystemAccessControl(ReadOnlySystemAccessControl.NAME, ImmutableMap.of());
    accessControlManager.checkCanSetUser(Optional.of(PRINCIPAL), USER_NAME);
    accessControlManager.checkCanSetSystemSessionProperty(identity, "property");
    transaction(transactionManager, accessControlManager).execute(transactionId -> {
        SecurityContext context = new SecurityContext(transactionId, identity, queryId);
        accessControlManager.checkCanSetCatalogSessionProperty(context, "catalog", "property");
        accessControlManager.checkCanShowSchemas(context, "catalog");
        accessControlManager.checkCanShowTables(context, new CatalogSchemaName("catalog", "schema"));
        accessControlManager.checkCanSelectFromColumns(context, tableName, ImmutableSet.of("column"));
        accessControlManager.checkCanCreateViewWithSelectFromColumns(context, tableName, ImmutableSet.of("column"));
        accessControlManager.checkCanGrantExecuteFunctionPrivilege(context, "function", Identity.ofUser("bob"), false);
        accessControlManager.checkCanGrantExecuteFunctionPrivilege(context, "function", Identity.ofUser("bob"), true);
        Set<String> catalogs = ImmutableSet.of("catalog");
        assertEquals(accessControlManager.filterCatalogs(context, catalogs), catalogs);
        Set<String> schemas = ImmutableSet.of("schema");
        assertEquals(accessControlManager.filterSchemas(context, "catalog", schemas), schemas);
        Set<SchemaTableName> tableNames = ImmutableSet.of(new SchemaTableName("schema", "table"));
        assertEquals(accessControlManager.filterTables(context, "catalog", tableNames), tableNames);
    });
    assertThatThrownBy(() -> transaction(transactionManager, accessControlManager).execute(transactionId -> {
        accessControlManager.checkCanInsertIntoTable(new SecurityContext(transactionId, identity, queryId), tableName);
    })).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot insert into table catalog.schema.table");
}
Also used : QueryId(io.trino.spi.QueryId) TransactionBuilder.transaction(io.trino.transaction.TransactionBuilder.transaction) TransactionManager(io.trino.transaction.TransactionManager) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.testng.annotations.Test) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) CatalogName(io.trino.connector.CatalogName) MockConnectorFactory(io.trino.connector.MockConnectorFactory) Map(java.util.Map) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) TEST_SESSION(io.trino.SessionTestUtils.TEST_SESSION) Path(java.nio.file.Path) WRITE(java.nio.file.StandardOpenOption.WRITE) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) ViewExpression(io.trino.spi.security.ViewExpression) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) Set(java.util.Set) TrinoException(io.trino.spi.TrinoException) SchemaTableName(io.trino.spi.connector.SchemaTableName) BasicPrincipal(io.trino.spi.security.BasicPrincipal) TestingEventListenerManager.emptyEventListenerManager(io.trino.testing.TestingEventListenerManager.emptyEventListenerManager) List(java.util.List) Principal(java.security.Principal) BIGINT(io.trino.spi.type.BigintType.BIGINT) ReadOnlySystemAccessControl(io.trino.plugin.base.security.ReadOnlySystemAccessControl) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) Optional(java.util.Optional) SystemAccessControlFactory(io.trino.spi.security.SystemAccessControlFactory) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TestingEventListenerManager(io.trino.testing.TestingEventListenerManager) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) Type(io.trino.spi.type.Type) Assert.assertEquals(org.testng.Assert.assertEquals) AllowAllAccessControl(io.trino.plugin.base.security.AllowAllAccessControl) SystemAccessControl(io.trino.spi.security.SystemAccessControl) InMemoryTransactionManager.createTestTransactionManager(io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager) ImmutableList(com.google.common.collect.ImmutableList) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Identity(io.trino.spi.security.Identity) LocalQueryRunner(io.trino.testing.LocalQueryRunner) Objects.requireNonNull(java.util.Objects.requireNonNull) ConnectorSecurityContext(io.trino.spi.connector.ConnectorSecurityContext) Files(java.nio.file.Files) AccessDeniedException.denySelectTable(io.trino.spi.security.AccessDeniedException.denySelectTable) IOException(java.io.IOException) Files.createTempFile(java.nio.file.Files.createTempFile) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) DefaultSystemAccessControl(io.trino.plugin.base.security.DefaultSystemAccessControl) EventListenerManager(io.trino.eventlistener.EventListenerManager) CatalogManager(io.trino.metadata.CatalogManager) CREATE(java.nio.file.StandardOpenOption.CREATE) TransactionId(io.trino.transaction.TransactionId) EventListener(io.trino.spi.eventlistener.EventListener) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TransactionManager(io.trino.transaction.TransactionManager) InMemoryTransactionManager.createTestTransactionManager(io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) ConnectorSecurityContext(io.trino.spi.connector.ConnectorSecurityContext) Identity(io.trino.spi.security.Identity) SchemaTableName(io.trino.spi.connector.SchemaTableName) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) Test(org.testng.annotations.Test)

Example 17 with TransactionId

use of io.trino.transaction.TransactionId in project trino by trinodb.

the class TestAccessControlManager method testDenySystemAccessControl.

@Test
public void testDenySystemAccessControl() {
    try (LocalQueryRunner queryRunner = LocalQueryRunner.create(TEST_SESSION)) {
        TransactionManager transactionManager = queryRunner.getTransactionManager();
        AccessControlManager accessControlManager = createAccessControlManager(transactionManager);
        TestSystemAccessControlFactory accessControlFactory = new TestSystemAccessControlFactory("test");
        accessControlManager.addSystemAccessControlFactory(accessControlFactory);
        accessControlManager.setSystemAccessControl("test", ImmutableMap.of());
        queryRunner.createCatalog("catalog", MockConnectorFactory.create(), ImmutableMap.of());
        accessControlManager.addCatalogAccessControl(new CatalogName("connector"), new DenyConnectorAccessControl());
        assertThatThrownBy(() -> transaction(transactionManager, accessControlManager).execute(transactionId -> {
            accessControlManager.checkCanSelectFromColumns(context(transactionId), new QualifiedObjectName("secured_catalog", "schema", "table"), ImmutableSet.of("column"));
        })).isInstanceOf(TrinoException.class).hasMessageMatching("Access Denied: Cannot select from table secured_catalog.schema.table");
    }
}
Also used : QueryId(io.trino.spi.QueryId) TransactionBuilder.transaction(io.trino.transaction.TransactionBuilder.transaction) TransactionManager(io.trino.transaction.TransactionManager) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.testng.annotations.Test) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) CatalogName(io.trino.connector.CatalogName) MockConnectorFactory(io.trino.connector.MockConnectorFactory) Map(java.util.Map) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) TEST_SESSION(io.trino.SessionTestUtils.TEST_SESSION) Path(java.nio.file.Path) WRITE(java.nio.file.StandardOpenOption.WRITE) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) ViewExpression(io.trino.spi.security.ViewExpression) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) Set(java.util.Set) TrinoException(io.trino.spi.TrinoException) SchemaTableName(io.trino.spi.connector.SchemaTableName) BasicPrincipal(io.trino.spi.security.BasicPrincipal) TestingEventListenerManager.emptyEventListenerManager(io.trino.testing.TestingEventListenerManager.emptyEventListenerManager) List(java.util.List) Principal(java.security.Principal) BIGINT(io.trino.spi.type.BigintType.BIGINT) ReadOnlySystemAccessControl(io.trino.plugin.base.security.ReadOnlySystemAccessControl) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) Optional(java.util.Optional) SystemAccessControlFactory(io.trino.spi.security.SystemAccessControlFactory) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TestingEventListenerManager(io.trino.testing.TestingEventListenerManager) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) Type(io.trino.spi.type.Type) Assert.assertEquals(org.testng.Assert.assertEquals) AllowAllAccessControl(io.trino.plugin.base.security.AllowAllAccessControl) SystemAccessControl(io.trino.spi.security.SystemAccessControl) InMemoryTransactionManager.createTestTransactionManager(io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager) ImmutableList(com.google.common.collect.ImmutableList) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Identity(io.trino.spi.security.Identity) LocalQueryRunner(io.trino.testing.LocalQueryRunner) Objects.requireNonNull(java.util.Objects.requireNonNull) ConnectorSecurityContext(io.trino.spi.connector.ConnectorSecurityContext) Files(java.nio.file.Files) AccessDeniedException.denySelectTable(io.trino.spi.security.AccessDeniedException.denySelectTable) IOException(java.io.IOException) Files.createTempFile(java.nio.file.Files.createTempFile) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) DefaultSystemAccessControl(io.trino.plugin.base.security.DefaultSystemAccessControl) EventListenerManager(io.trino.eventlistener.EventListenerManager) CatalogManager(io.trino.metadata.CatalogManager) CREATE(java.nio.file.StandardOpenOption.CREATE) TransactionId(io.trino.transaction.TransactionId) EventListener(io.trino.spi.eventlistener.EventListener) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) TransactionManager(io.trino.transaction.TransactionManager) InMemoryTransactionManager.createTestTransactionManager(io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager) TrinoException(io.trino.spi.TrinoException) CatalogName(io.trino.connector.CatalogName) LocalQueryRunner(io.trino.testing.LocalQueryRunner) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) Test(org.testng.annotations.Test)

Example 18 with TransactionId

use of io.trino.transaction.TransactionId 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 19 with TransactionId

use of io.trino.transaction.TransactionId in project trino by trinodb.

the class TestInformationSchemaMetadata method testInformationSchemaPredicatePushdownWithConstraintPredicate.

@Test
public void testInformationSchemaPredicatePushdownWithConstraintPredicate() {
    TransactionId transactionId = transactionManager.beginTransaction(false);
    Constraint constraint = new Constraint(TupleDomain.all(), TestInformationSchemaMetadata::testConstraint, testConstraintColumns());
    ConnectorSession session = createNewSession(transactionId);
    ConnectorMetadata metadata = new InformationSchemaMetadata("test_catalog", this.metadata);
    InformationSchemaTableHandle tableHandle = (InformationSchemaTableHandle) metadata.getTableHandle(session, new SchemaTableName("information_schema", "columns"));
    tableHandle = metadata.applyFilter(session, tableHandle, constraint).map(ConstraintApplicationResult::getHandle).map(InformationSchemaTableHandle.class::cast).orElseThrow(AssertionError::new);
    assertEquals(tableHandle.getPrefixes(), ImmutableSet.of(new QualifiedTablePrefix("test_catalog", "test_schema", "test_view")));
}
Also used : InformationSchemaTableHandle(io.trino.connector.informationschema.InformationSchemaTableHandle) Constraint(io.trino.spi.connector.Constraint) ConnectorSession(io.trino.spi.connector.ConnectorSession) ConnectorMetadata(io.trino.spi.connector.ConnectorMetadata) InformationSchemaMetadata(io.trino.connector.informationschema.InformationSchemaMetadata) SchemaTableName(io.trino.spi.connector.SchemaTableName) TransactionId(io.trino.transaction.TransactionId) Test(org.testng.annotations.Test)

Example 20 with TransactionId

use of io.trino.transaction.TransactionId in project trino by trinodb.

the class TestInformationSchemaMetadata method testInformationSchemaPredicatePushdownForEmptyNames.

@Test
public void testInformationSchemaPredicatePushdownForEmptyNames() {
    TransactionId transactionId = transactionManager.beginTransaction(false);
    ConnectorSession session = createNewSession(transactionId);
    ConnectorMetadata metadata = new InformationSchemaMetadata("test_catalog", this.metadata);
    InformationSchemaColumnHandle tableSchemaColumn = new InformationSchemaColumnHandle("table_schema");
    InformationSchemaColumnHandle tableNameColumn = new InformationSchemaColumnHandle("table_name");
    ConnectorTableHandle tableHandle = metadata.getTableHandle(session, new SchemaTableName("information_schema", "tables"));
    // Empty schema name
    InformationSchemaTableHandle filtered = metadata.applyFilter(session, tableHandle, new Constraint(TupleDomain.withColumnDomains(ImmutableMap.of(tableSchemaColumn, Domain.singleValue(VARCHAR, Slices.utf8Slice("")))))).map(ConstraintApplicationResult::getHandle).map(InformationSchemaTableHandle.class::cast).orElseThrow(AssertionError::new);
    // "" schema name is valid schema name, but is (currently) valid for QualifiedTablePrefix
    assertEquals(filtered.getPrefixes(), ImmutableSet.of(new QualifiedTablePrefix("test_catalog", "")));
    // Empty table name
    filtered = metadata.applyFilter(session, tableHandle, new Constraint(TupleDomain.withColumnDomains(ImmutableMap.of(tableNameColumn, Domain.singleValue(VARCHAR, Slices.utf8Slice("")))))).map(ConstraintApplicationResult::getHandle).map(InformationSchemaTableHandle.class::cast).orElseThrow(AssertionError::new);
    // "" table name is valid schema name, but is (currently) valid for QualifiedTablePrefix
    // filter blindly applies filter to all visible schemas, so information_schema must be included
    assertEquals(filtered.getPrefixes(), ImmutableSet.of(new QualifiedTablePrefix("test_catalog", "test_schema", ""), new QualifiedTablePrefix("test_catalog", "information_schema", "")));
}
Also used : InformationSchemaTableHandle(io.trino.connector.informationschema.InformationSchemaTableHandle) Constraint(io.trino.spi.connector.Constraint) InformationSchemaColumnHandle(io.trino.connector.informationschema.InformationSchemaColumnHandle) ConstraintApplicationResult(io.trino.spi.connector.ConstraintApplicationResult) ConnectorSession(io.trino.spi.connector.ConnectorSession) ConnectorMetadata(io.trino.spi.connector.ConnectorMetadata) InformationSchemaMetadata(io.trino.connector.informationschema.InformationSchemaMetadata) SchemaTableName(io.trino.spi.connector.SchemaTableName) TransactionId(io.trino.transaction.TransactionId) ConnectorTableHandle(io.trino.spi.connector.ConnectorTableHandle) Test(org.testng.annotations.Test)

Aggregations

TransactionId (io.trino.transaction.TransactionId)22 Test (org.testng.annotations.Test)12 SchemaTableName (io.trino.spi.connector.SchemaTableName)11 ImmutableMap (com.google.common.collect.ImmutableMap)8 ConnectorSession (io.trino.spi.connector.ConnectorSession)8 Session (io.trino.Session)7 InformationSchemaMetadata (io.trino.connector.informationschema.InformationSchemaMetadata)7 InformationSchemaTableHandle (io.trino.connector.informationschema.InformationSchemaTableHandle)7 ConnectorMetadata (io.trino.spi.connector.ConnectorMetadata)7 Constraint (io.trino.spi.connector.Constraint)7 QualifiedObjectName (io.trino.metadata.QualifiedObjectName)6 TrinoException (io.trino.spi.TrinoException)6 CatalogName (io.trino.connector.CatalogName)5 ImmutableList (com.google.common.collect.ImmutableList)4 MockConnectorFactory (io.trino.connector.MockConnectorFactory)4 TransactionManager (io.trino.transaction.TransactionManager)4 Map (java.util.Map)4 ImmutableSet (com.google.common.collect.ImmutableSet)3 TEST_SESSION (io.trino.SessionTestUtils.TEST_SESSION)3 InformationSchemaColumnHandle (io.trino.connector.informationschema.InformationSchemaColumnHandle)3