Search in sources :

Example 11 with AuthConfig

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

the class QueryResourceTest method testSecuredQuery.

@Test
public void testSecuredQuery() throws Exception {
    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, false);
    EasyMock.expectLastCall().times(1);
    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) {
                    if (resource.getName().equals("allow")) {
                        return new Access(true);
                    } else {
                        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);
    try {
        queryResource.doPost(new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)), null, /*pretty*/
        testServletRequest);
        Assert.fail("doPost did not throw ForbiddenException for an unauthorized query");
    } catch (ForbiddenException e) {
    }
    Response response = queryResource.doPost(new ByteArrayInputStream("{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"}".getBytes(StandardCharsets.UTF_8)), null, /*pretty*/
    testServletRequest);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ((StreamingOutput) response.getEntity()).write(baos);
    final List<Result<TimeBoundaryResultValue>> responses = jsonMapper.readValue(baos.toByteArray(), new TypeReference<List<Result<TimeBoundaryResultValue>>>() {
    });
    Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    Assert.assertEquals(0, responses.size());
    Assert.assertEquals(1, testRequestLogger.getNativeQuerylogs().size());
    Assert.assertEquals(true, testRequestLogger.getNativeQuerylogs().get(0).getQueryStats().getStats().get("success"));
    Assert.assertEquals("druid", testRequestLogger.getNativeQuerylogs().get(0).getQueryStats().getStats().get("identity"));
}
Also used : Action(org.apache.druid.server.security.Action) ForbiddenException(org.apache.druid.server.security.ForbiddenException) Resource(org.apache.druid.server.security.Resource) Access(org.apache.druid.server.security.Access) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) StreamingOutput(javax.ws.rs.core.StreamingOutput) AuthConfig(org.apache.druid.server.security.AuthConfig) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) Result(org.apache.druid.query.Result) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) Authorizer(org.apache.druid.server.security.Authorizer) TimeBoundaryResultValue(org.apache.druid.query.timeboundary.TimeBoundaryResultValue) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) DefaultQueryConfig(org.apache.druid.query.DefaultQueryConfig) DefaultGenericQueryMetricsFactory(org.apache.druid.query.DefaultGenericQueryMetricsFactory) Test(org.junit.Test)

Example 12 with AuthConfig

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

the class WebserverTestUtils method createServer.

public static HttpServer createServer(String SERVICE_NAME, URI baseUri, String resourceClassName, Consumer<Binder> extender) throws IOException {
    Injector injector = Initialization.makeInjectorWithModules(GuiceInjectors.makeStartupInjector(), ImmutableList.of(binder -> {
        binder.bindConstant().annotatedWith(Names.named("serviceName")).to(SERVICE_NAME);
        binder.bindConstant().annotatedWith(Names.named("servicePort")).to(baseUri.getPort());
        binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(baseUri.getPort() + 1);
        binder.bind(Key.get(ServiceEmitter.class)).toInstance(new NoopServiceEmitter());
        binder.bind(Key.get(AuthConfig.class)).toInstance(new AuthConfig());
        binder.bind(AuthorizerMapper.class).toInstance(AuthTestUtils.TEST_AUTHORIZER_MAPPER);
        binder.bind(AuthenticatorMapper.class).toInstance(AuthTestUtils.TEST_AUTHENTICATOR_MAPPER);
        binder.bind(Key.get(HttpClient.class, Client.class)).toInstance(EasyMock.createMock(HttpClient.class));
        extender.accept(binder);
    }));
    ResourceConfig resourceConfig = new ClassNamesResourceConfig(resourceClassName + ';' + MockHttpServletRequest.class.getName());
    IoCComponentProviderFactory ioc = new GuiceComponentProviderFactory(resourceConfig, injector);
    HttpServer server = GrizzlyServerFactory.createHttpServer(baseUri, resourceConfig, ioc);
    return server;
}
Also used : HttpClient(org.apache.druid.java.util.http.client.HttpClient) Provider(javax.ws.rs.ext.Provider) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) Key(com.google.inject.Key) ResourceConfig(com.sun.jersey.api.core.ResourceConfig) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) ImmutableList(com.google.common.collect.ImmutableList) Binder(com.google.inject.Binder) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) AuthTestUtils(org.apache.druid.server.security.AuthTestUtils) HttpServer(org.glassfish.grizzly.http.server.HttpServer) UriBuilder(javax.ws.rs.core.UriBuilder) AuthConfig(org.apache.druid.server.security.AuthConfig) URI(java.net.URI) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) Context(javax.ws.rs.core.Context) GuiceComponentProviderFactory(com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory) AuthenticatorMapper(org.apache.druid.server.security.AuthenticatorMapper) ClassNamesResourceConfig(com.sun.jersey.api.core.ClassNamesResourceConfig) SingletonTypeInjectableProvider(com.sun.jersey.spi.inject.SingletonTypeInjectableProvider) IOException(java.io.IOException) Names(com.google.inject.name.Names) EasyMock(org.easymock.EasyMock) GrizzlyServerFactory(com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory) GuiceInjectors(org.apache.druid.guice.GuiceInjectors) Injector(com.google.inject.Injector) Consumer(java.util.function.Consumer) IoCComponentProviderFactory(com.sun.jersey.core.spi.component.ioc.IoCComponentProviderFactory) Initialization(org.apache.druid.initialization.Initialization) ServiceEmitter(org.apache.druid.java.util.emitter.service.ServiceEmitter) Client(org.apache.druid.guice.annotations.Client) Collections(java.util.Collections) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) ServiceEmitter(org.apache.druid.java.util.emitter.service.ServiceEmitter) Injector(com.google.inject.Injector) ClassNamesResourceConfig(com.sun.jersey.api.core.ClassNamesResourceConfig) HttpClient(org.apache.druid.java.util.http.client.HttpClient) HttpServer(org.glassfish.grizzly.http.server.HttpServer) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) AuthConfig(org.apache.druid.server.security.AuthConfig) ResourceConfig(com.sun.jersey.api.core.ResourceConfig) ClassNamesResourceConfig(com.sun.jersey.api.core.ClassNamesResourceConfig) HttpClient(org.apache.druid.java.util.http.client.HttpClient) Client(org.apache.druid.guice.annotations.Client) GuiceComponentProviderFactory(com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory) IoCComponentProviderFactory(com.sun.jersey.core.spi.component.ioc.IoCComponentProviderFactory)

Example 13 with AuthConfig

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

the class ResourceFilterTestHelper method getRequestPaths.

// Feeds in an array of [ PathName, MethodName, ResourceFilter , Injector]
public static Collection<Object[]> getRequestPaths(final AnnotatedElement classOrMethod, final Iterable<Class<?>> mockableInjections, final Iterable<Key<?>> mockableKeys, final Iterable<?> injectedObjs) {
    final Injector injector = Guice.createInjector(new Module() {

        @Override
        public void configure(Binder binder) {
            for (Class clazz : mockableInjections) {
                binder.bind(clazz).toInstance(EasyMock.createNiceMock(clazz));
            }
            for (Object obj : injectedObjs) {
                binder.bind((Class) obj.getClass()).toInstance(obj);
            }
            for (Key<?> key : mockableKeys) {
                binder.bind((Key<Object>) key).toInstance(EasyMock.createNiceMock(key.getTypeLiteral().getRawType()));
            }
            binder.bind(AuthConfig.class).toInstance(new AuthConfig());
        }
    });
    // Ignore the first "/"
    final String basepath = classOrMethod.getAnnotation(Path.class).value().substring(1);
    final List<Class<? extends ResourceFilter>> baseResourceFilters = classOrMethod.getAnnotation(ResourceFilters.class) == null ? Collections.emptyList() : ImmutableList.copyOf(classOrMethod.getAnnotation(ResourceFilters.class).value());
    List<Method> methods;
    if (classOrMethod instanceof Class<?>) {
        methods = ImmutableList.copyOf(((Class<?>) classOrMethod).getDeclaredMethods());
    } else {
        methods = Collections.singletonList((Method) classOrMethod);
    }
    return ImmutableList.copyOf(Iterables.concat(// Step 3 - Merge all the Objects arrays for each endpoints
    Iterables.transform(// - Resource Filter instance for the endpoint
    Iterables.filter(// ResourceFilters applied to them
    methods, new Predicate<Method>() {

        @Override
        public boolean apply(Method input) {
            return input.getAnnotation(GET.class) != null || input.getAnnotation(POST.class) != null || input.getAnnotation(DELETE.class) != null && (input.getAnnotation(ResourceFilters.class) != null || !baseResourceFilters.isEmpty());
        }
    }), new Function<Method, Collection<Object[]>>() {

        @Override
        public Collection<Object[]> apply(final Method method) {
            final List<Class<? extends ResourceFilter>> resourceFilters = method.getAnnotation(ResourceFilters.class) == null ? baseResourceFilters : ImmutableList.copyOf(method.getAnnotation(ResourceFilters.class).value());
            return Collections2.transform(resourceFilters, new Function<Class<? extends ResourceFilter>, Object[]>() {

                @Override
                public Object[] apply(Class<? extends ResourceFilter> input) {
                    if (method.getAnnotation(Path.class) != null) {
                        return new Object[] { StringUtils.format("%s%s", basepath, method.getAnnotation(Path.class).value()), httpMethodFromAnnotation(input, method), injector.getInstance(input), injector };
                    } else {
                        return new Object[] { basepath, httpMethodFromAnnotation(input, method), injector.getInstance(input), injector };
                    }
                }
            });
        }
    })));
}
Also used : Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) AuthConfig(org.apache.druid.server.security.AuthConfig) Method(java.lang.reflect.Method) Predicate(com.google.common.base.Predicate) Binder(com.google.inject.Binder) ResourceFilters(com.sun.jersey.spi.container.ResourceFilters) Function(com.google.common.base.Function) ResourceFilter(com.sun.jersey.spi.container.ResourceFilter) DELETE(javax.ws.rs.DELETE) Injector(com.google.inject.Injector) GET(javax.ws.rs.GET) Collection(java.util.Collection) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Module(com.google.inject.Module) Key(com.google.inject.Key)

Example 14 with AuthConfig

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

the class CoordinatorJettyServerInitializer method initialize.

@Override
public void initialize(Server server, Injector injector) {
    final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
    root.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
    root.addServlet(holderPwd, "/");
    final AuthConfig authConfig = injector.getInstance(AuthConfig.class);
    final ObjectMapper jsonMapper = injector.getInstance(Key.get(ObjectMapper.class, Json.class));
    final AuthenticatorMapper authenticatorMapper = injector.getInstance(AuthenticatorMapper.class);
    AuthenticationUtils.addSecuritySanityCheckFilter(root, jsonMapper);
    // perform no-op authorization/authentication for these resources
    AuthenticationUtils.addNoopAuthenticationAndAuthorizationFilters(root, UNSECURED_PATHS);
    WebConsoleJettyServerInitializer.intializeServerForWebConsoleRoot(root);
    AuthenticationUtils.addNoopAuthenticationAndAuthorizationFilters(root, authConfig.getUnsecuredPaths());
    if (beOverlord) {
        AuthenticationUtils.addNoopAuthenticationAndAuthorizationFilters(root, CliOverlord.UNSECURED_PATHS);
    }
    List<Authenticator> authenticators = authenticatorMapper.getAuthenticatorChain();
    AuthenticationUtils.addAuthenticationFilterChain(root, authenticators);
    AuthenticationUtils.addAllowOptionsFilter(root, authConfig.isAllowUnauthenticatedHttpOptions());
    JettyServerInitUtils.addAllowHttpMethodsFilter(root, serverConfig.getAllowedHttpMethods());
    JettyServerInitUtils.addExtensionFilters(root, injector);
    // Check that requests were authorized before sending responses
    AuthenticationUtils.addPreResponseAuthorizationCheckFilter(root, authenticators, jsonMapper);
    // add some paths not to be redirected to leader.
    root.addFilter(GuiceFilter.class, "/status/*", null);
    root.addFilter(GuiceFilter.class, "/druid-internal/*", null);
    // redirect anything other than status to the current lead
    root.addFilter(new FilterHolder(injector.getInstance(RedirectFilter.class)), "/*", null);
    // The coordinator really needs a standarized api path
    // Can't use '/*' here because of Guice and Jetty static content conflicts
    root.addFilter(GuiceFilter.class, "/info/*", null);
    root.addFilter(GuiceFilter.class, "/druid/coordinator/*", null);
    if (beOverlord) {
        root.addFilter(GuiceFilter.class, "/druid/indexer/*", null);
    }
    root.addFilter(GuiceFilter.class, "/druid-ext/*", null);
    // this will be removed in the next major release
    root.addFilter(GuiceFilter.class, "/coordinator/*", null);
    if (!beOverlord) {
        root.addServlet(new ServletHolder(injector.getInstance(OverlordProxyServlet.class)), "/druid/indexer/*");
    }
    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[] { WebConsoleJettyServerInitializer.createWebConsoleRewriteHandler(), JettyServerInitUtils.getJettyRequestLogHandler(), JettyServerInitUtils.wrapWithDefaultGzipHandler(root, serverConfig.getInflateBufferSize(), serverConfig.getCompressionLevel()) });
    server.setHandler(handlerList);
}
Also used : AuthenticatorMapper(org.apache.druid.server.security.AuthenticatorMapper) HandlerList(org.eclipse.jetty.server.handler.HandlerList) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AuthConfig(org.apache.druid.server.security.AuthConfig) Json(org.apache.druid.guice.annotations.Json) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Authenticator(org.apache.druid.server.security.Authenticator)

Example 15 with AuthConfig

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

the class IntervalsResourceTest method testGetSpecificIntervals.

@Test
public void testGetSpecificIntervals() {
    EasyMock.expect(inventoryView.getInventory()).andReturn(ImmutableList.of(server)).atLeastOnce();
    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(new AuthenticationResult("druid", "druid", null, null)).once();
    request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(inventoryView, request);
    IntervalsResource intervalsResource = new IntervalsResource(inventoryView, new AuthConfig(), AuthTestUtils.TEST_AUTHORIZER_MAPPER);
    Response response = intervalsResource.getSpecificIntervals("2010-01-01T00:00:00.000Z/P1D", null, null, request);
    Map<String, Object> actualIntervals = (Map) response.getEntity();
    Assert.assertEquals(2, actualIntervals.size());
    Assert.assertEquals(25L, actualIntervals.get("size"));
    Assert.assertEquals(2, actualIntervals.get("count"));
}
Also used : Response(javax.ws.rs.core.Response) AuthConfig(org.apache.druid.server.security.AuthConfig) TreeMap(java.util.TreeMap) Map(java.util.Map) AuthenticationResult(org.apache.druid.server.security.AuthenticationResult) Test(org.junit.Test)

Aggregations

AuthConfig (org.apache.druid.server.security.AuthConfig)16 Response (javax.ws.rs.core.Response)11 AuthenticationResult (org.apache.druid.server.security.AuthenticationResult)11 Test (org.junit.Test)11 NoopServiceEmitter (org.apache.druid.server.metrics.NoopServiceEmitter)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 DefaultGenericQueryMetricsFactory (org.apache.druid.query.DefaultGenericQueryMetricsFactory)7 DefaultQueryConfig (org.apache.druid.query.DefaultQueryConfig)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 ImmutableList (com.google.common.collect.ImmutableList)6 AuthorizerMapper (org.apache.druid.server.security.AuthorizerMapper)6 IOException (java.io.IOException)5 List (java.util.List)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Map (java.util.Map)4 TreeMap (java.util.TreeMap)4 StreamingOutput (javax.ws.rs.core.StreamingOutput)4 Result (org.apache.druid.query.Result)4 TimeBoundaryResultValue (org.apache.druid.query.timeboundary.TimeBoundaryResultValue)4 Access (org.apache.druid.server.security.Access)4