Search in sources :

Example 1 with OAUTH2_COOKIE

use of io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE in project trino by trinodb.

the class TestResourceSecurity method testOAuth2Groups.

@Test(dataProvider = "groups")
public void testOAuth2Groups(Optional<Set<String>> groups) throws Exception {
    try (TokenServer tokenServer = new TokenServer(Optional.empty());
        TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("web-ui.enabled", "true").put("http-server.authentication.type", "oauth2").putAll(getOAuth2Properties(tokenServer)).put("http-server.authentication.oauth2.groups-field", GROUPS_CLAIM).buildOrThrow()).setAdditionalModule(oauth2Module(tokenServer)).build()) {
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(TestSystemAccessControl.NO_IMPERSONATION);
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        String accessToken = tokenServer.issueAccessToken(groups);
        OkHttpClient clientWithOAuthToken = client.newBuilder().authenticator((route, response) -> response.request().newBuilder().header(AUTHORIZATION, "Bearer " + accessToken).build()).build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithOAuthToken);
        try (Response response = clientWithOAuthToken.newCall(new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/protocol/identity")).build()).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER);
            assertEquals(response.header("groups"), groups.map(TestResource::toHeader).orElse(""));
        }
        OkHttpClient clientWithOAuthCookie = client.newBuilder().cookieJar(new CookieJar() {

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                return ImmutableList.of(new Cookie.Builder().domain(httpServerInfo.getHttpsUri().getHost()).path(UI_LOCATION).name(OAUTH2_COOKIE).value(accessToken).httpOnly().secure().build());
            }
        }).build();
        try (Response response = clientWithOAuthCookie.newCall(new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/ui/api/identity")).build()).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER);
            assertEquals(response.header("groups"), groups.map(TestResource::toHeader).orElse(""));
        }
    }
}
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) HttpCookie(java.net.HttpCookie) Cookie(okhttp3.Cookie) OkHttpClient(okhttp3.OkHttpClient) JwtBuilder(io.jsonwebtoken.JwtBuilder) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CookieJar(okhttp3.CookieJar) JavaNetCookieJar(okhttp3.JavaNetCookieJar) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 2 with OAUTH2_COOKIE

use of io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE in project trino by trinodb.

the class BaseOAuth2WebUiAuthenticationFilterTest method testSuccessfulFlow.

@Test
public void testSuccessfulFlow() throws Exception {
    // create a new HttpClient which follows redirects and give access to cookies
    CookieManager cookieManager = new CookieManager();
    CookieStore cookieStore = cookieManager.getCookieStore();
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    setupInsecureSsl(httpClientBuilder);
    OkHttpClient httpClient = httpClientBuilder.followRedirects(true).cookieJar(new JavaNetCookieJar(cookieManager)).build();
    assertThat(cookieStore.get(uiUri)).isEmpty();
    // access UI and follow redirects in order to get OAuth2 cookie
    Response response = httpClient.newCall(new Request.Builder().url(uiUri.toURL()).get().build()).execute();
    assertEquals(response.code(), SC_OK);
    assertEquals(response.request().url().toString(), uiUri.toString());
    Optional<HttpCookie> oauth2Cookie = cookieStore.get(uiUri).stream().filter(cookie -> cookie.getName().equals(OAUTH2_COOKIE)).findFirst();
    assertThat(oauth2Cookie).isNotEmpty();
    assertTrinoCookie(oauth2Cookie.get());
    assertUICallWithCookie(oauth2Cookie.get().getValue());
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) Response(okhttp3.Response) URL(java.net.URL) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Closeables(io.airlift.testing.Closeables) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) Level(io.airlift.log.Level) HttpCookie(java.net.HttpCookie) Cookie(okhttp3.Cookie) ImmutableList(com.google.common.collect.ImmutableList) DefaultClaims(io.jsonwebtoken.impl.DefaultClaims) Duration(java.time.Duration) Logging(io.airlift.log.Logging) Response(okhttp3.Response) URI(java.net.URI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) CookieJar(okhttp3.CookieJar) CLIENT_SECRET_BASIC(io.trino.server.security.oauth2.TokenEndpointAuthMethod.CLIENT_SECRET_BASIC) KeyPairGenerator(java.security.KeyPairGenerator) AfterClass(org.testng.annotations.AfterClass) Request(okhttp3.Request) CookieStore(java.net.CookieStore) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) SEE_OTHER(javax.ws.rs.core.Response.Status.SEE_OTHER) ImmutableMap(com.google.common.collect.ImmutableMap) MalformedURLException(java.net.MalformedURLException) OK(javax.ws.rs.core.Response.Status.OK) JavaNetCookieJar(okhttp3.JavaNetCookieJar) BeforeClass(org.testng.annotations.BeforeClass) IOException(java.io.IOException) UUID(java.util.UUID) Instant(java.time.Instant) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) WebUiModule(io.trino.server.ui.WebUiModule) CookieManager(java.net.CookieManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) Optional(java.util.Optional) HttpUrl(okhttp3.HttpUrl) OkHttpUtil.setupInsecureSsl(io.trino.client.OkHttpUtil.setupInsecureSsl) OAuth2WebUiAuthenticationFilter(io.trino.server.ui.OAuth2WebUiAuthenticationFilter) CookieStore(java.net.CookieStore) OkHttpClient(okhttp3.OkHttpClient) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) Request(okhttp3.Request) HttpCookie(java.net.HttpCookie) CookieManager(java.net.CookieManager) Test(org.testng.annotations.Test)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 JwtUtil.newJwtBuilder (io.trino.server.security.jwt.JwtUtil.newJwtBuilder)2 TestingTrinoServer (io.trino.server.testing.TestingTrinoServer)2 OAUTH2_COOKIE (io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE)2 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Iterables.getOnlyElement (com.google.common.collect.Iterables.getOnlyElement)1 Resources (com.google.common.io.Resources)1 AUTHORIZATION (com.google.common.net.HttpHeaders.AUTHORIZATION)1 Key (com.google.inject.Key)1 Module (com.google.inject.Module)1 OptionalBinder.newOptionalBinder (com.google.inject.multibindings.OptionalBinder.newOptionalBinder)1 HttpUriBuilder.uriBuilderFrom (io.airlift.http.client.HttpUriBuilder.uriBuilderFrom)1 HttpServerConfig (io.airlift.http.server.HttpServerConfig)1 HttpServerInfo (io.airlift.http.server.HttpServerInfo)1 TestingHttpServer (io.airlift.http.server.testing.TestingHttpServer)1 JaxrsBinder.jaxrsBinder (io.airlift.jaxrs.JaxrsBinder.jaxrsBinder)1