Search in sources :

Example 1 with Access

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

the class RulesResourceFilter method filter.

@Override
public ContainerRequest filter(ContainerRequest request) {
    final String dataSourceName = request.getPathSegments().get(Iterables.indexOf(request.getPathSegments(), new Predicate<PathSegment>() {

        @Override
        public boolean apply(PathSegment input) {
            return "rules".equals(input.getPath());
        }
    }) + 1).getPath();
    Preconditions.checkNotNull(dataSourceName);
    final ResourceAction resourceAction = new ResourceAction(new Resource(dataSourceName, ResourceType.DATASOURCE), getAction(request));
    final Access authResult = AuthorizationUtils.authorizeResourceAction(getReq(), resourceAction, getAuthorizerMapper());
    if (!authResult.isAllowed()) {
        throw new ForbiddenException(authResult.toString());
    }
    return request;
}
Also used : ForbiddenException(org.apache.druid.server.security.ForbiddenException) Resource(org.apache.druid.server.security.Resource) Access(org.apache.druid.server.security.Access) PathSegment(javax.ws.rs.core.PathSegment) Predicate(com.google.common.base.Predicate) ResourceAction(org.apache.druid.server.security.ResourceAction)

Example 2 with Access

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

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

the class StateResourceFilter method filter.

@Override
public ContainerRequest filter(ContainerRequest request) {
    final ResourceAction resourceAction = new ResourceAction(Resource.STATE_RESOURCE, getAction(request));
    final Access authResult = AuthorizationUtils.authorizeResourceAction(getReq(), resourceAction, getAuthorizerMapper());
    if (!authResult.isAllowed()) {
        throw new ForbiddenException(authResult.toString());
    }
    return request;
}
Also used : ForbiddenException(org.apache.druid.server.security.ForbiddenException) Access(org.apache.druid.server.security.Access) ResourceAction(org.apache.druid.server.security.ResourceAction)

Example 4 with Access

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

the class NativeQueryMaker method execute.

private <T> Sequence<Object[]> execute(Query<T> query, final List<String> newFields, final List<SqlTypeName> newTypes) {
    Hook.QUERY_PLAN.run(query);
    if (query.getId() == null) {
        final String queryId = UUID.randomUUID().toString();
        plannerContext.addNativeQueryId(queryId);
        query = query.withId(queryId);
    }
    query = query.withSqlQueryId(plannerContext.getSqlQueryId());
    final AuthenticationResult authenticationResult = plannerContext.getAuthenticationResult();
    final Access authorizationResult = plannerContext.getAuthorizationResult();
    final QueryLifecycle queryLifecycle = queryLifecycleFactory.factorize();
    // After calling "runSimple" the query will start running. We need to do this before reading the toolChest, since
    // otherwise it won't yet be initialized. (A bummer, since ideally, we'd verify the toolChest exists and can do
    // array-based results before starting the query; but in practice we don't expect this to happen since we keep
    // tight control over which query types we generate in the SQL layer. They all support array-based results.)
    final Sequence<T> results = queryLifecycle.runSimple(query, authenticationResult, authorizationResult);
    // noinspection unchecked
    final QueryToolChest<T, Query<T>> toolChest = queryLifecycle.getToolChest();
    final List<String> resultArrayFields = toolChest.resultArraySignature(query).getColumnNames();
    final Sequence<Object[]> resultArrays = toolChest.resultsAsArrays(query, results);
    return mapResultSequence(resultArrays, resultArrayFields, newFields, newTypes);
}
Also used : QueryLifecycle(org.apache.druid.server.QueryLifecycle) TimeseriesQuery(org.apache.druid.query.timeseries.TimeseriesQuery) Query(org.apache.druid.query.Query) DruidQuery(org.apache.druid.sql.calcite.rel.DruidQuery) Access(org.apache.druid.server.security.Access) NlsString(org.apache.calcite.util.NlsString) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult)

Example 5 with Access

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

Aggregations

Access (org.apache.druid.server.security.Access)35 Resource (org.apache.druid.server.security.Resource)22 ForbiddenException (org.apache.druid.server.security.ForbiddenException)18 ResourceAction (org.apache.druid.server.security.ResourceAction)18 AuthenticationResult (org.apache.druid.server.security.AuthenticationResult)15 Test (org.junit.Test)11 Response (javax.ws.rs.core.Response)8 Action (org.apache.druid.server.security.Action)8 Authorizer (org.apache.druid.server.security.Authorizer)8 AuthorizerMapper (org.apache.druid.server.security.AuthorizerMapper)8 Produces (javax.ws.rs.Produces)7 List (java.util.List)5 Consumes (javax.ws.rs.Consumes)5 POST (javax.ws.rs.POST)5 Path (javax.ws.rs.Path)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4