Search in sources :

Example 1 with AuthorizerMapper

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

the class DataSourcesResourceTest method testSecuredGetFullQueryableDataSources.

@Test
public void testSecuredGetFullQueryableDataSources() {
    AuthenticationResult authenticationResult = new AuthenticationResult("druid", "druid", null, null);
    // first request
    EasyMock.expect(server.getDataSources()).andReturn(ImmutableList.of(listDataSources.get(0), listDataSources.get(1))).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED)).andReturn(null).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT)).andReturn(authenticationResult).once();
    request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);
    EasyMock.expect(inventoryView.getInventory()).andReturn(ImmutableList.of(server)).once();
    // second request
    EasyMock.expect(server.getDataSources()).andReturn(ImmutableList.of(listDataSources.get(0), listDataSources.get(1))).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED)).andReturn(null).once();
    EasyMock.expect(request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT)).andReturn(authenticationResult).once();
    request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);
    EasyMock.expect(inventoryView.getInventory()).andReturn(ImmutableList.of(server)).once();
    EasyMock.replay(inventoryView, server, request);
    AuthorizerMapper authMapper = new AuthorizerMapper(null) {

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

                @Override
                public Access authorize(AuthenticationResult authenticationResult1, Resource resource, Action action) {
                    if (resource.getName().equals("datasource1")) {
                        return new Access(true);
                    } else {
                        return new Access(false);
                    }
                }
            };
        }
    };
    DataSourcesResource dataSourcesResource = new DataSourcesResource(inventoryView, null, null, null, authMapper, null);
    Response response = dataSourcesResource.getQueryableDataSources("full", null, request);
    Set<ImmutableDruidDataSource> result = (Set<ImmutableDruidDataSource>) response.getEntity();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(1, result.size());
    ImmutableDruidDataSourceTestUtils.assertEquals(listDataSources.get(0).toImmutableDruidDataSource(), Iterables.getOnlyElement(result));
    response = dataSourcesResource.getQueryableDataSources(null, null, request);
    List<String> result1 = (List<String>) response.getEntity();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(1, result1.size());
    Assert.assertTrue(result1.contains("datasource1"));
    EasyMock.verify(inventoryView, server, request);
}
Also used : Action(org.apache.druid.server.security.Action) ImmutableDruidDataSource(org.apache.druid.client.ImmutableDruidDataSource) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) TreeSet(java.util.TreeSet) Resource(org.apache.druid.server.security.Resource) Access(org.apache.druid.server.security.Access) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) Response(javax.ws.rs.core.Response) Authorizer(org.apache.druid.server.security.Authorizer) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Test(org.junit.Test)

Example 2 with AuthorizerMapper

use of org.apache.druid.server.security.AuthorizerMapper 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 3 with AuthorizerMapper

use of org.apache.druid.server.security.AuthorizerMapper 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)

Example 4 with AuthorizerMapper

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

the class AsyncQueryForwardingServletTest method setupInjector.

@Override
protected Injector setupInjector() {
    return Initialization.makeInjectorWithModules(GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of(new Module() {

        @Override
        public void configure(Binder binder) {
            JsonConfigProvider.bindInstance(binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", false, null, null, true, false));
            binder.bind(JettyServerInitializer.class).to(ProxyJettyServerInit.class).in(LazySingleton.class);
            binder.bind(AuthorizerMapper.class).toInstance(new AuthorizerMapper(null) {

                @Override
                public Authorizer getAuthorizer(String name) {
                    return new AllowAllAuthorizer();
                }
            });
            Jerseys.addResource(binder, SlowResource.class);
            Jerseys.addResource(binder, ExceptionResource.class);
            Jerseys.addResource(binder, DefaultResource.class);
            LifecycleModule.register(binder, Server.class);
        }
    }));
}
Also used : Binder(com.google.inject.Binder) Authorizer(org.apache.druid.server.security.Authorizer) AllowAllAuthorizer(org.apache.druid.server.security.AllowAllAuthorizer) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) Self(org.apache.druid.guice.annotations.Self) AllowAllAuthorizer(org.apache.druid.server.security.AllowAllAuthorizer) Module(com.google.inject.Module) LifecycleModule(org.apache.druid.guice.LifecycleModule)

Example 5 with AuthorizerMapper

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

the class CoordinatorPollingBasicAuthorizerCacheManager method initUserMaps.

private void initUserMaps() {
    AuthorizerMapper authorizerMapper = injector.getInstance(AuthorizerMapper.class);
    if (authorizerMapper == null || authorizerMapper.getAuthorizerMap() == null) {
        return;
    }
    for (Map.Entry<String, Authorizer> entry : authorizerMapper.getAuthorizerMap().entrySet()) {
        Authorizer authorizer = entry.getValue();
        if (authorizer instanceof BasicRoleBasedAuthorizer) {
            String authorizerName = entry.getKey();
            authorizerPrefixes.add(authorizerName);
            UserAndRoleMap userAndRoleMap = fetchUserAndRoleMapFromCoordinator(authorizerName, true);
            if (userAndRoleMap != null) {
                cachedUserMaps.put(authorizerName, userAndRoleMap.getUserMap());
                cachedRoleMaps.put(authorizerName, userAndRoleMap.getRoleMap());
            }
            GroupMappingAndRoleMap groupMappingAndRoleMap = fetchGroupAndRoleMapFromCoordinator(authorizerName, true);
            if (groupMappingAndRoleMap != null) {
                cachedGroupMappingMaps.put(authorizerName, groupMappingAndRoleMap.getGroupMappingMap());
                cachedGroupMappingRoleMaps.put(authorizerName, groupMappingAndRoleMap.getRoleMap());
            }
        }
    }
}
Also used : UserAndRoleMap(org.apache.druid.security.basic.authorization.entity.UserAndRoleMap) GroupMappingAndRoleMap(org.apache.druid.security.basic.authorization.entity.GroupMappingAndRoleMap) BasicRoleBasedAuthorizer(org.apache.druid.security.basic.authorization.BasicRoleBasedAuthorizer) Authorizer(org.apache.druid.server.security.Authorizer) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) BasicRoleBasedAuthorizer(org.apache.druid.security.basic.authorization.BasicRoleBasedAuthorizer) UserAndRoleMap(org.apache.druid.security.basic.authorization.entity.UserAndRoleMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GroupMappingAndRoleMap(org.apache.druid.security.basic.authorization.entity.GroupMappingAndRoleMap)

Aggregations

AuthorizerMapper (org.apache.druid.server.security.AuthorizerMapper)18 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)10 Response (javax.ws.rs.core.Response)10 Access (org.apache.druid.server.security.Access)10 Action (org.apache.druid.server.security.Action)10 List (java.util.List)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 Set (java.util.Set)7 Resource (org.apache.druid.server.security.Resource)7 Collections (java.util.Collections)6 Map (java.util.Map)6 Nullable (javax.annotation.Nullable)6 Path (javax.ws.rs.Path)6 Produces (javax.ws.rs.Produces)6 Context (javax.ws.rs.core.Context)6 MediaType (javax.ws.rs.core.MediaType)6 ForbiddenException (org.apache.druid.server.security.ForbiddenException)6 Collectors (java.util.stream.Collectors)5 GET (javax.ws.rs.GET)5 POST (javax.ws.rs.POST)5