Search in sources :

Example 11 with Identity

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

the class TestWebUi method testCustomPrincipalField.

@Test
public void testCustomPrincipalField() throws Exception {
    String accessToken = createTokenBuilder().setSubject("unknown").addClaims(ImmutableMap.of("preferred_username", "test-user@email.com")).compact();
    TestingHttpServer jwkServer = createTestingJwkServer();
    jwkServer.start();
    try (TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(OAUTH2_PROPERTIES).put("http-server.authentication.oauth2.jwks-url", jwkServer.getBaseUrl().toString()).put("http-server.authentication.oauth2.principal-field", "preferred_username").put("http-server.authentication.oauth2.user-mapping.pattern", "(.*)@.*").buildOrThrow()).setAdditionalModule(binder -> {
        newOptionalBinder(binder, OAuth2Client.class).setBinding().toInstance(new OAuth2ClientStub(accessToken));
        jaxrsBinder(binder).bind(AuthenticatedIdentityCapturingFilter.class);
    }).build()) {
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        assertAuth2Authentication(httpServerInfo, accessToken);
        Identity identity = server.getInstance(Key.get(AuthenticatedIdentityCapturingFilter.class)).getAuthenticatedIdentity();
        assertThat(identity.getUser()).isEqualTo("test-user");
        assertThat(identity.getPrincipal()).isEqualTo(Optional.of(new BasicPrincipal("test-user@email.com")));
    } finally {
        jwkServer.stop();
    }
}
Also used : ResourceSecurity(io.trino.server.security.ResourceSecurity) X_FORWARDED_PORT(com.google.common.net.HttpHeaders.X_FORWARDED_PORT) Date(java.util.Date) ZonedDateTime(java.time.ZonedDateTime) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) NodeInfo(io.airlift.node.NodeInfo) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) Test(org.testng.annotations.Test) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) HttpServerConfig(io.airlift.http.server.HttpServerConfig) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) FormBody(okhttp3.FormBody) JwtBuilder(io.jsonwebtoken.JwtBuilder) DISABLED_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.DISABLED_LOCATION) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Path(java.nio.file.Path) X_FORWARDED_PROTO(com.google.common.net.HttpHeaders.X_FORWARDED_PROTO) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) Request(okhttp3.Request) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) HttpServlet(javax.servlet.http.HttpServlet) ImmutableMap(com.google.common.collect.ImmutableMap) JavaNetCookieJar(okhttp3.JavaNetCookieJar) BeforeClass(org.testng.annotations.BeforeClass) AUTHENTICATED_IDENTITY(io.trino.server.HttpRequestSessionContextFactory.AUTHENTICATED_IDENTITY) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) GuardedBy(javax.annotation.concurrent.GuardedBy) BasicPrincipal(io.trino.spi.security.BasicPrincipal) Preconditions.checkState(com.google.common.base.Preconditions.checkState) UncheckedIOException(java.io.UncheckedIOException) SC_NOT_FOUND(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND) Base64(java.util.Base64) HttpServerInfo(io.airlift.http.server.HttpServerInfo) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) SecretKey(javax.crypto.SecretKey) Predicate.not(java.util.function.Predicate.not) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) UI_LOGIN(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOGIN) GET(javax.ws.rs.GET) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) CALLBACK_ENDPOINT(io.trino.server.security.oauth2.OAuth2CallbackResource.CALLBACK_ENDPOINT) Hashing(com.google.common.hash.Hashing) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) RequestBody(okhttp3.RequestBody) Inject(javax.inject.Inject) UI_LOGOUT(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOGOUT) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Identity(io.trino.spi.security.Identity) Objects.requireNonNull(java.util.Objects.requireNonNull) Response(okhttp3.Response) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) X_FORWARDED_HOST(com.google.common.net.HttpHeaders.X_FORWARDED_HOST) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) LOGIN_FORM(io.trino.server.ui.FormWebUiAuthenticationFilter.LOGIN_FORM) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) PasswordAuthenticatorManager(io.trino.server.security.PasswordAuthenticatorManager) OkHttpClient(okhttp3.OkHttpClient) LOCATION(com.google.common.net.HttpHeaders.LOCATION) Paths(java.nio.file.Paths) Assert.assertTrue(org.testng.Assert.assertTrue) BasicPrincipal(io.trino.spi.security.BasicPrincipal) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) Identity(io.trino.spi.security.Identity) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 12 with Identity

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

the class TestSessionFunctions method testCurrentGroups.

@Test
public void testCurrentGroups() {
    Identity identityWithoutGroups = Identity.ofUser("test_current_user");
    Session session;
    session = testSessionBuilder().setIdentity(identityWithoutGroups).build();
    try (QueryAssertions queryAssertions = new QueryAssertions(session)) {
        assertThat(queryAssertions.query("SELECT current_groups()")).matches("SELECT CAST(ARRAY[] AS ARRAY(VARCHAR))");
    }
    Set<String> groups = ImmutableSet.of("group_a", "group_b");
    Identity identityWithGroups = new Identity.Builder("test_current_user").withGroups(groups).build();
    session = testSessionBuilder().setIdentity(identityWithGroups).build();
    try (QueryAssertions queryAssertions = new QueryAssertions(session)) {
        assertThat(queryAssertions.query("SELECT array_sort(current_groups())")).matches(format("SELECT CAST(ARRAY[%s] AS ARRAY(VARCHAR))", groups.stream().map(e -> format("'%s'", e)).collect(joining(","))));
    }
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PER_CLASS(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS) Set(java.util.Set) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) Test(org.junit.jupiter.api.Test) SqlPath(io.trino.sql.SqlPath) TestingSession.testSessionBuilder(io.trino.testing.TestingSession.testSessionBuilder) TestInstance(org.junit.jupiter.api.TestInstance) Identity(io.trino.spi.security.Identity) Optional(java.util.Optional) Session(io.trino.Session) TestingSession.testSessionBuilder(io.trino.testing.TestingSession.testSessionBuilder) Identity(io.trino.spi.security.Identity) Session(io.trino.Session) Test(org.junit.jupiter.api.Test)

Example 13 with Identity

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

the class TestFileBasedSystemAccessControl method testQuery.

@Test
public void testQuery() {
    SystemAccessControl accessControlManager = newFileBasedSystemAccessControl("query.json");
    accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(admin, queryId));
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(admin, queryId), any);
    assertEquals(accessControlManager.filterViewQueryOwnedBy(new SystemSecurityContext(admin, queryId), ImmutableSet.of("a", "b")), ImmutableSet.of("a", "b"));
    accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(admin, queryId), any);
    accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(alice, queryId));
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(alice, queryId), any);
    assertEquals(accessControlManager.filterViewQueryOwnedBy(new SystemSecurityContext(alice, queryId), ImmutableSet.of("a", "b")), ImmutableSet.of("a", "b"));
    assertThatThrownBy(() -> accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(alice, queryId), any)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertThatThrownBy(() -> accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(bob, queryId))).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertThatThrownBy(() -> accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(bob, queryId), any)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertEquals(accessControlManager.filterViewQueryOwnedBy(new SystemSecurityContext(bob, queryId), ImmutableSet.of("a", "b")), ImmutableSet.of());
    accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(bob, queryId), any);
    accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(dave, queryId));
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(dave, queryId), alice);
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(dave, queryId), dave);
    assertEquals(accessControlManager.filterViewQueryOwnedBy(new SystemSecurityContext(dave, queryId), ImmutableSet.of("alice", "bob", "dave", "admin")), ImmutableSet.of("alice", "dave"));
    assertThatThrownBy(() -> accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(dave, queryId), alice)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertThatThrownBy(() -> accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(dave, queryId), bob)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertThatThrownBy(() -> accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(dave, queryId), bob)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    assertThatThrownBy(() -> accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(dave, queryId), admin)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    Identity contractor = Identity.forUser("some-other-contractor").withGroups(ImmutableSet.of("contractors")).build();
    accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(contractor, queryId));
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(contractor, queryId), dave);
    assertThatThrownBy(() -> accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(contractor, queryId), dave)).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied: Cannot view query");
    accessControlManager.checkCanExecuteQuery(new SystemSecurityContext(nonAsciiUser, queryId));
    accessControlManager.checkCanViewQueryOwnedBy(new SystemSecurityContext(nonAsciiUser, queryId), any);
    assertEquals(accessControlManager.filterViewQueryOwnedBy(new SystemSecurityContext(nonAsciiUser, queryId), ImmutableSet.of("a", "b")), ImmutableSet.of("a", "b"));
    accessControlManager.checkCanKillQueryOwnedBy(new SystemSecurityContext(nonAsciiUser, queryId), any);
}
Also used : SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) AccessDeniedException(io.trino.spi.security.AccessDeniedException) SystemAccessControl(io.trino.spi.security.SystemAccessControl) Identity(io.trino.spi.security.Identity) Test(org.testng.annotations.Test)

Example 14 with Identity

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

the class TestResourceSecurity method testPasswordAuthenticatorUserMapping.

@Test
public void testPasswordAuthenticatorUserMapping() throws Exception {
    try (TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("password-authenticator.config-files", passwordConfigDummy.toString()).put("http-server.authentication.type", "password").put("http-server.authentication.password.user-mapping.pattern", ALLOWED_USER_MAPPING_PATTERN).buildOrThrow()).setAdditionalModule(binder -> jaxrsBinder(binder).bind(TestResource.class)).build()) {
        server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticators(TestResourceSecurity::authenticate);
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(TestSystemAccessControl.WITH_IMPERSONATION);
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        // Test sets basic auth user and X-Trino-User, and the authenticator is performing user mapping.
        // Normally this would result in an impersonation check to the X-Trino-User, but the password
        // authenticator has a hack to clear X-Trino-User in this case.
        Request request = new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/protocol/identity")).addHeader("Authorization", Credentials.basic(TEST_USER_LOGIN, TEST_PASSWORD)).addHeader("X-Trino-User", TEST_USER_LOGIN).build();
        try (Response response = client.newCall(request).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER_LOGIN);
        }
    }
}
Also used : AccessDeniedException.denyReadSystemInformationAccess(io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) AccessControlManager(io.trino.security.AccessControlManager) ZonedDateTime(java.time.ZonedDateTime) NodeInfo(io.airlift.node.NodeInfo) Test(org.testng.annotations.Test) HttpServerConfig(io.airlift.http.server.HttpServerConfig) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) Matcher(java.util.regex.Matcher) JwtBuilder(io.jsonwebtoken.JwtBuilder) Map(java.util.Map) Path(java.nio.file.Path) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) CookieJar(okhttp3.CookieJar) Request(okhttp3.Request) HttpServlet(javax.servlet.http.HttpServlet) SET_COOKIE(javax.ws.rs.core.HttpHeaders.SET_COOKIE) JavaNetCookieJar(okhttp3.JavaNetCookieJar) Set(java.util.Set) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) BasicPrincipal(io.trino.spi.security.BasicPrincipal) HttpServerInfo(io.airlift.http.server.HttpServerInfo) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) GET(javax.ws.rs.GET) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) HttpServletRequest(javax.servlet.http.HttpServletRequest) Identity(io.trino.spi.security.Identity) Response(okhttp3.Response) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) WWW_AUTHENTICATE(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE) OkHttpClient(okhttp3.OkHttpClient) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) Module(com.google.inject.Module) AUTHENTICATED_USER(io.trino.server.security.ResourceSecurity.AccessType.AUTHENTICATED_USER) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) Assert.assertNotNull(org.testng.Assert.assertNotNull) Credentials(okhttp3.Credentials) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Base64(java.util.Base64) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) Instant.now(java.time.Instant.now) DataProvider(org.testng.annotations.DataProvider) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) Headers(okhttp3.Headers) AtomicReference(java.util.concurrent.atomic.AtomicReference) Inject(javax.inject.Inject) Cookie(okhttp3.Cookie) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) UI_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOCATION) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) AccessDeniedException.denyImpersonateUser(io.trino.spi.security.AccessDeniedException.denyImpersonateUser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) SC_FORBIDDEN(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN) Assert.assertTrue(org.testng.Assert.assertTrue) TRINO_HEADERS(io.trino.client.ProtocolHeaders.TRINO_HEADERS) Response(okhttp3.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JwtBuilder(io.jsonwebtoken.JwtBuilder) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) Request(okhttp3.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 15 with Identity

use of io.trino.spi.security.Identity 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)

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