Search in sources :

Example 1 with NettyHttpService

use of io.cdap.http.NettyHttpService in project cdap by caskdata.

the class HttpsEnablerTest method testClientAuth.

/**
 * Private method to verify client side authentication.
 *
 * @param useClientAuth if {@code true}, enable client side authentication from the https client
 * @param trustClient if {@code true}, server trust the client using the client trust store
 */
private void testClientAuth(boolean useClientAuth, boolean trustClient) throws Exception {
    String ksPass = "abc";
    KeyStore serverKeyStore = KeyStores.generatedCertKeyStore(1, ksPass);
    KeyStore clientKeyStore = KeyStores.generatedCertKeyStore(1, ksPass);
    // Start the http server
    HttpsEnabler serverEnabler = new HttpsEnabler().setKeyStore(serverKeyStore, ksPass::toCharArray);
    if (trustClient) {
        serverEnabler.setTrustStore(KeyStores.createTrustStore(clientKeyStore));
    } else {
        // Generates a different trust store used by the server
        serverEnabler.setTrustStore(KeyStores.createTrustStore(KeyStores.generatedCertKeyStore(1, ksPass)));
    }
    NettyHttpService httpService = serverEnabler.enable(NettyHttpService.builder("test").setHttpHandlers(new PingHandler())).build();
    httpService.start();
    try {
        // Hit the server with an optional client side authentication
        InetSocketAddress address = httpService.getBindAddress();
        URL url = new URL(String.format("https://%s:%d/ping", address.getHostName(), address.getPort()));
        HttpsEnabler clientEnabler = new HttpsEnabler().setTrustAll(true);
        if (useClientAuth) {
            clientEnabler.setKeyStore(clientKeyStore, ksPass::toCharArray);
        }
        HttpsURLConnection urlConn = clientEnabler.enable((HttpsURLConnection) url.openConnection());
        Assert.assertEquals(200, urlConn.getResponseCode());
    } finally {
        httpService.stop();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NettyHttpService(io.cdap.http.NettyHttpService) KeyStore(java.security.KeyStore) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 2 with NettyHttpService

use of io.cdap.http.NettyHttpService in project cdap by caskdata.

the class HttpHandlerGeneratorTest method testHttpHandlerGenerator.

@Test
public void testHttpHandlerGenerator() throws Exception {
    HttpHandlerFactory factory = new HttpHandlerFactory("/prefix", TransactionControl.IMPLICIT);
    HttpHandler httpHandler = factory.createHttpHandler(TypeToken.of(MyHttpHandler.class), new AbstractDelegatorContext<MyHttpHandler>() {

        @Override
        protected MyHttpHandler createHandler() {
            return new MyHttpHandler();
        }
    }, new NoopMetricsContext());
    HttpHandler httpHandlerWithoutAnnotation = factory.createHttpHandler(TypeToken.of(NoAnnotationHandler.class), new AbstractDelegatorContext<NoAnnotationHandler>() {

        @Override
        protected NoAnnotationHandler createHandler() {
            return new NoAnnotationHandler();
        }
    }, new NoopMetricsContext());
    NettyHttpService service = NettyHttpService.builder("test-handler-generator").setHttpHandlers(httpHandler, httpHandlerWithoutAnnotation).build();
    service.start();
    try {
        InetSocketAddress bindAddress = service.getBindAddress();
        // Make a GET call
        URLConnection urlConn = new URL(String.format("http://%s:%d/prefix/p2/handle", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        urlConn.setReadTimeout(2000);
        Assert.assertEquals("Hello World", new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8));
        // Make a POST call
        urlConn = new URL(String.format("http://%s:%d/prefix/p2/echo/test", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        urlConn.setReadTimeout(2000);
        urlConn.setDoOutput(true);
        ByteStreams.copy(ByteStreams.newInputStreamSupplier("Hello".getBytes(Charsets.UTF_8)), urlConn.getOutputStream());
        Assert.assertEquals("Hello test", new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8));
        // Ensure that even though the handler did not have a class-level annotation, we still prefix the path that it
        // handles by "/prefix"
        urlConn = new URL(String.format("http://%s:%d/prefix/ping", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        urlConn.setReadTimeout(2000);
        Assert.assertEquals("OK", new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8));
        // Call to a method that raise exception
        urlConn = new URL(String.format("http://%s:%d/prefix/p2/exception", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        Assert.assertEquals(500, ((HttpURLConnection) urlConn).getResponseCode());
        Assert.assertEquals("Exception occurred while handling request: exception", new String(ByteStreams.toByteArray(((HttpURLConnection) urlConn).getErrorStream()), "UTF-8"));
        urlConn = new URL(String.format("http://%s:%d/prefix/p2/exceptionNoTx", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        Assert.assertEquals(500, ((HttpURLConnection) urlConn).getResponseCode());
        Assert.assertEquals("Exception occurred while handling request: exceptionNoTx", new String(ByteStreams.toByteArray(((HttpURLConnection) urlConn).getErrorStream()), "UTF-8"));
    } finally {
        service.stop();
    }
}
Also used : HttpHandler(io.cdap.http.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) NoopMetricsContext(io.cdap.cdap.api.metrics.NoopMetricsContext) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URL(java.net.URL) NettyHttpService(io.cdap.http.NettyHttpService) Test(org.junit.Test)

Example 3 with NettyHttpService

use of io.cdap.http.NettyHttpService in project cdap by caskdata.

the class TrafficRelayServerTest method testRelay.

@Test
public void testRelay() throws Exception {
    NettyHttpService httpServer = NettyHttpService.builder("test").setHttpHandlers(new TestHandler()).build();
    httpServer.start();
    try {
        TrafficRelayServer relayServer = new TrafficRelayServer(InetAddress.getLoopbackAddress(), httpServer::getBindAddress);
        relayServer.startAndWait();
        try {
            InetSocketAddress relayAddr = relayServer.getBindAddress();
            // GET
            URL url = new URL(String.format("http://%s:%d/ping", relayAddr.getHostName(), relayAddr.getPort()));
            HttpResponse response = HttpRequests.execute(HttpRequest.get(url).build(), new DefaultHttpRequestConfig(false));
            Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
            // POST
            url = new URL(String.format("http://%s:%d/echo", relayAddr.getHostName(), relayAddr.getPort()));
            response = HttpRequests.execute(HttpRequest.post(url).withBody("Testing").build(), new DefaultHttpRequestConfig(false));
            Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
            Assert.assertEquals("Testing", response.getResponseBodyAsString());
        } finally {
            relayServer.stopAndWait();
        }
    } finally {
        httpServer.stop();
    }
}
Also used : TestHandler(io.cdap.cdap.internal.app.runtime.monitor.proxy.TestHandler) InetSocketAddress(java.net.InetSocketAddress) DefaultHttpRequestConfig(io.cdap.cdap.common.http.DefaultHttpRequestConfig) NettyHttpService(io.cdap.http.NettyHttpService) HttpResponse(io.cdap.common.http.HttpResponse) URL(java.net.URL) TrafficRelayServer(io.cdap.cdap.internal.app.runtime.monitor.TrafficRelayServer) Test(org.junit.Test)

Example 4 with NettyHttpService

use of io.cdap.http.NettyHttpService in project cdap by caskdata.

the class LogBufferHandlerTest method testHandler.

@Test
public void testHandler() throws Exception {
    CConfiguration cConf = CConfiguration.create();
    String absolutePath = TMP_FOLDER.newFolder().getAbsolutePath();
    cConf.set(Constants.LogBuffer.LOG_BUFFER_BASE_DIR, absolutePath);
    cConf.setLong(Constants.LogBuffer.LOG_BUFFER_MAX_FILE_SIZE_BYTES, 100000);
    LoggerContext loggerContext = LogPipelineTestUtil.createLoggerContext("WARN", ImmutableMap.of("test.logger", "INFO"), MockAppender.class.getName());
    final MockAppender appender = LogPipelineTestUtil.getAppender(loggerContext.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME), "Test", MockAppender.class);
    LogBufferProcessorPipeline pipeline = getLogPipeline(loggerContext);
    pipeline.startAndWait();
    ConcurrentLogBufferWriter writer = new ConcurrentLogBufferWriter(cConf, ImmutableList.of(pipeline), () -> {
    });
    NettyHttpService httpService = NettyHttpService.builder("RemoteAppenderTest").setHttpHandlers(new LogBufferHandler(writer)).setExceptionHandler(new HttpExceptionHandler()).build();
    httpService.start();
    RemoteLogAppender remoteLogAppender = getRemoteAppender(cConf, httpService);
    remoteLogAppender.start();
    List<ILoggingEvent> events = getLoggingEvents();
    WorkerLoggingContext loggingContext = new WorkerLoggingContext("default", "app1", "worker1", "run1", "instance1");
    for (int i = 0; i < 1000; i++) {
        remoteLogAppender.append(new LogMessage(events.get(i % events.size()), loggingContext));
    }
    Tasks.waitFor(1000, () -> appender.getEvents().size(), 120, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    remoteLogAppender.stop();
    httpService.stop();
    pipeline.stopAndWait();
    loggerContext.stop();
}
Also used : WorkerLoggingContext(io.cdap.cdap.logging.context.WorkerLoggingContext) RemoteLogAppender(io.cdap.cdap.logging.appender.remote.RemoteLogAppender) HttpExceptionHandler(io.cdap.cdap.common.HttpExceptionHandler) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) LoggerContext(ch.qos.logback.classic.LoggerContext) MockAppender(io.cdap.cdap.logging.pipeline.MockAppender) LogMessage(io.cdap.cdap.logging.appender.LogMessage) LogBufferProcessorPipeline(io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline) NettyHttpService(io.cdap.http.NettyHttpService) ConcurrentLogBufferWriter(io.cdap.cdap.logging.logbuffer.ConcurrentLogBufferWriter) Test(org.junit.Test)

Example 5 with NettyHttpService

use of io.cdap.http.NettyHttpService in project cdap by caskdata.

the class HttpsEnablerTest method testConfigure.

@Test
public void testConfigure() throws Exception {
    String password = "testing";
    KeyStore keyStore = KeyStores.generatedCertKeyStore(1, password);
    File pemFile = KeyStoresTest.writePEMFile(TEMP_FOLDER.newFile(), keyStore, KeyStores.CERT_ALIAS, password);
    CConfiguration cConf = CConfiguration.create();
    SConfiguration sConf = SConfiguration.create();
    cConf.set(Constants.Security.SSL.INTERNAL_CERT_PATH, pemFile.getAbsolutePath());
    sConf.set(Constants.Security.SSL.INTERNAL_CERT_PASSWORD, password);
    // Start the server with SSL enabled
    NettyHttpService httpService = new HttpsEnabler().configureKeyStore(cConf, sConf).enable(NettyHttpService.builder("test").setHttpHandlers(new PingHandler())).build();
    httpService.start();
    try {
        // Create a client that trust the server
        InetSocketAddress address = httpService.getBindAddress();
        URL url = new URL(String.format("https://%s:%d/ping", address.getHostName(), address.getPort()));
        HttpsURLConnection urlConn = new HttpsEnabler().configureTrustStore(cConf, sConf).enable((HttpsURLConnection) url.openConnection());
        Assert.assertEquals(200, urlConn.getResponseCode());
    } finally {
        httpService.stop();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SConfiguration(io.cdap.cdap.common.conf.SConfiguration) NettyHttpService(io.cdap.http.NettyHttpService) KeyStore(java.security.KeyStore) File(java.io.File) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Aggregations

NettyHttpService (io.cdap.http.NettyHttpService)12 InetSocketAddress (java.net.InetSocketAddress)9 URL (java.net.URL)8 Test (org.junit.Test)8 NoopMetricsContext (io.cdap.cdap.api.metrics.NoopMetricsContext)4 HttpHandler (io.cdap.http.HttpHandler)4 File (java.io.File)3 HttpURLConnection (java.net.HttpURLConnection)3 KeyStore (java.security.KeyStore)3 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)3 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)2 HttpResponse (io.cdap.common.http.HttpResponse)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)1 ImmutableList (com.google.common.collect.ImmutableList)1 AccessException (io.cdap.cdap.api.security.AccessException)1 AuthorizationClient (io.cdap.cdap.client.AuthorizationClient)1 FeatureDisabledException (io.cdap.cdap.common.FeatureDisabledException)1 HttpExceptionHandler (io.cdap.cdap.common.HttpExceptionHandler)1 SConfiguration (io.cdap.cdap.common.conf.SConfiguration)1