Search in sources :

Example 6 with Resource

use of org.apache.druid.server.security.Resource in project druid by druid-io.

the class DruidPlannerResourceAnalyzeTest method testView.

@Test
public void testView() {
    final String sql = "SELECT COUNT(*) FROM view.aview as druid WHERE dim1_firstchar <> 'z'";
    Set<ResourceAction> requiredResources = analyzeResources(PLANNER_CONFIG_DEFAULT, sql, CalciteTests.REGULAR_USER_AUTH_RESULT);
    Assert.assertEquals(ImmutableSet.of(new ResourceAction(new Resource("aview", ResourceType.VIEW), Action.READ)), requiredResources);
}
Also used : Resource(org.apache.druid.server.security.Resource) ResourceAction(org.apache.druid.server.security.ResourceAction) Test(org.junit.Test)

Example 7 with Resource

use of org.apache.druid.server.security.Resource in project druid by druid-io.

the class DruidPlannerResourceAnalyzeTest method testJoin.

@Test
public void testJoin() {
    final String sql = "SELECT COUNT(*) FROM foo INNER JOIN numfoo ON foo.dim1 = numfoo.dim1 WHERE numfoo.dim1 <> 'z'";
    Set<ResourceAction> requiredResources = analyzeResources(PLANNER_CONFIG_DEFAULT, sql, CalciteTests.REGULAR_USER_AUTH_RESULT);
    Assert.assertEquals(ImmutableSet.of(new ResourceAction(new Resource("foo", ResourceType.DATASOURCE), Action.READ), new ResourceAction(new Resource("numfoo", ResourceType.DATASOURCE), Action.READ)), requiredResources);
}
Also used : Resource(org.apache.druid.server.security.Resource) ResourceAction(org.apache.druid.server.security.ResourceAction) Test(org.junit.Test)

Example 8 with Resource

use of org.apache.druid.server.security.Resource in project druid by druid-io.

the class SqlResourceCollectorShuttle method visit.

@Override
public SqlNode visit(SqlIdentifier id) {
    // raw tables and views and such will have a IdentifierNamespace
    // since we are scoped to identifiers here, we should only pick up these
    SqlValidatorNamespace namespace = validator.getNamespace(id);
    if (namespace != null && namespace.isWrapperFor(IdentifierNamespace.class)) {
        SqlValidatorTable validatorTable = namespace.getTable();
        // this should not probably be null if the namespace was not null,
        if (validatorTable != null) {
            List<String> qualifiedNameParts = validatorTable.getQualifiedName();
            // 'schema'.'identifier'
            if (qualifiedNameParts.size() == 2) {
                final String schema = qualifiedNameParts.get(0);
                final String resourceName = qualifiedNameParts.get(1);
                final String resourceType = plannerContext.getSchemaResourceType(schema, resourceName);
                if (resourceType != null) {
                    resourceActions.add(new ResourceAction(new Resource(resourceName, resourceType), Action.READ));
                }
            } else if (qualifiedNameParts.size() > 2) {
                // Don't expect to see more than 2 names (catalog?).
                throw new ISE("Cannot analyze table idetifier %s", qualifiedNameParts);
            }
        }
    }
    return super.visit(id);
}
Also used : SqlValidatorTable(org.apache.calcite.sql.validate.SqlValidatorTable) Resource(org.apache.druid.server.security.Resource) ISE(org.apache.druid.java.util.common.ISE) SqlValidatorNamespace(org.apache.calcite.sql.validate.SqlValidatorNamespace) IdentifierNamespace(org.apache.calcite.sql.validate.IdentifierNamespace) ResourceAction(org.apache.druid.server.security.ResourceAction)

Example 9 with Resource

use of org.apache.druid.server.security.Resource in project druid by druid-io.

the class QueryResourceTest method testSecuredCancelQuery.

@Test(timeout = 60_000L)
public void testSecuredCancelQuery() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    final CountDownLatch cancelledCountDownLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT)).andReturn(AUTHENTICATION_RESULT).anyTimes();
    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(testServletRequest);
    AuthorizerMapper authMapper = new AuthorizerMapper(null) {

        @Override
        public Authorizer getAuthorizer(String name) {
            return new Authorizer() {

                @Override
                public Access authorize(AuthenticationResult authenticationResult, Resource resource, Action action) {
                    // WRITE corresponds to cancellation of query
                    if (action.equals(Action.READ)) {
                        try {
                            // Countdown startAwaitLatch as we want query cancellation to happen
                            // after we enter isAuthorized method so that we can handle the
                            // InterruptedException here because of query cancellation
                            startAwaitLatch.countDown();
                            waitForCancellationLatch.await();
                        } catch (InterruptedException e) {
                            // When the query is cancelled the control will reach here,
                            // countdown the latch and rethrow the exception so that error response is returned for the query
                            cancelledCountDownLatch.countDown();
                            throw new RuntimeException(e);
                        }
                        return new Access(true);
                    } else {
                        return new Access(true);
                    }
                }
            };
        }
    };
    queryResource = new QueryResource(new QueryLifecycleFactory(WAREHOUSE, TEST_SEGMENT_WALKER, new DefaultGenericQueryMetricsFactory(), new NoopServiceEmitter(), testRequestLogger, new AuthConfig(), authMapper, Suppliers.ofInstance(new DefaultQueryConfig(ImmutableMap.of()))), jsonMapper, smileMapper, queryScheduler, new AuthConfig(), authMapper, ResponseContextConfig.newConfig(true), DRUID_NODE);
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query<?> query = mapper.readValue(queryString, Query.class);
    ListenableFuture<?> future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes(StandardCharsets.UTF_8)), null, testServletRequest);
                Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryScheduler.registerQueryFuture(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            Response response = queryResource.cancelQuery("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
        }
    });
    waitFinishLatch.await();
    cancelledCountDownLatch.await();
}
Also used : Action(org.apache.druid.server.security.Action) Access(org.apache.druid.server.security.Access) AuthConfig(org.apache.druid.server.security.AuthConfig) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) Authorizer(org.apache.druid.server.security.Authorizer) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) DefaultQueryConfig(org.apache.druid.query.DefaultQueryConfig) DefaultGenericQueryMetricsFactory(org.apache.druid.query.DefaultGenericQueryMetricsFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DefaultObjectMapper(org.apache.druid.jackson.DefaultObjectMapper) Resource(org.apache.druid.server.security.Resource) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultObjectMapper(org.apache.druid.jackson.DefaultObjectMapper) Test(org.junit.Test)

Example 10 with Resource

use of org.apache.druid.server.security.Resource in project druid by druid-io.

the class QueryResourceTest method testDenySecuredCancelQuery.

@Test(timeout = 60_000L)
public void testDenySecuredCancelQuery() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT)).andReturn(AUTHENTICATION_RESULT).anyTimes();
    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);
    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, false);
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(testServletRequest);
    AuthorizerMapper authMapper = new AuthorizerMapper(null) {

        @Override
        public Authorizer getAuthorizer(String name) {
            return new Authorizer() {

                @Override
                public Access authorize(AuthenticationResult authenticationResult, Resource resource, Action action) {
                    // WRITE corresponds to cancellation of query
                    if (action.equals(Action.READ)) {
                        try {
                            waitForCancellationLatch.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        return new Access(true);
                    } else {
                        // Deny access to cancel the query
                        return new Access(false);
                    }
                }
            };
        }
    };
    queryResource = new QueryResource(new QueryLifecycleFactory(WAREHOUSE, TEST_SEGMENT_WALKER, new DefaultGenericQueryMetricsFactory(), new NoopServiceEmitter(), testRequestLogger, new AuthConfig(), authMapper, Suppliers.ofInstance(new DefaultQueryConfig(ImmutableMap.of()))), jsonMapper, smileMapper, queryScheduler, new AuthConfig(), authMapper, ResponseContextConfig.newConfig(true), DRUID_NODE);
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query<?> query = mapper.readValue(queryString, Query.class);
    ListenableFuture<?> future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                startAwaitLatch.countDown();
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes(StandardCharsets.UTF_8)), null, testServletRequest);
                Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryScheduler.registerQueryFuture(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            try {
                queryResource.cancelQuery("id_1", testServletRequest);
            } catch (ForbiddenException e) {
                waitForCancellationLatch.countDown();
                waitFinishLatch.countDown();
            }
        }
    });
    waitFinishLatch.await();
}
Also used : Action(org.apache.druid.server.security.Action) Access(org.apache.druid.server.security.Access) AuthConfig(org.apache.druid.server.security.AuthConfig) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) Authorizer(org.apache.druid.server.security.Authorizer) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) DefaultQueryConfig(org.apache.druid.query.DefaultQueryConfig) DefaultGenericQueryMetricsFactory(org.apache.druid.query.DefaultGenericQueryMetricsFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DefaultObjectMapper(org.apache.druid.jackson.DefaultObjectMapper) ForbiddenException(org.apache.druid.server.security.ForbiddenException) Resource(org.apache.druid.server.security.Resource) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultObjectMapper(org.apache.druid.jackson.DefaultObjectMapper) Test(org.junit.Test)

Aggregations

Resource (org.apache.druid.server.security.Resource)43 ResourceAction (org.apache.druid.server.security.ResourceAction)35 Test (org.junit.Test)26 Access (org.apache.druid.server.security.Access)23 AuthenticationResult (org.apache.druid.server.security.AuthenticationResult)12 ForbiddenException (org.apache.druid.server.security.ForbiddenException)12 Response (javax.ws.rs.core.Response)10 HashMap (java.util.HashMap)8 Action (org.apache.druid.server.security.Action)8 Authorizer (org.apache.druid.server.security.Authorizer)7 AuthorizerMapper (org.apache.druid.server.security.AuthorizerMapper)7 ImmutableList (com.google.common.collect.ImmutableList)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 BasicAuthorizerGroupMapping (org.apache.druid.security.basic.authorization.entity.BasicAuthorizerGroupMapping)4 Function (com.google.common.base.Function)3 Set (java.util.Set)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 JacksonConfigManager (org.apache.druid.common.config.JacksonConfigManager)3