Search in sources :

Example 11 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class Netty4HttpServerTransportTests method testCorsRequest.

public void testCorsRequest() throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            logger.error("--> Unexpected successful request [{}]", FakeRestRequest.requestToString(request));
            throw new AssertionError();
        }

        @Override
        public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            logger.error(new ParameterizedMessage("--> Unexpected bad request [{}]", FakeRestRequest.requestToString(channel.request())), cause);
            throw new AssertionError();
        }
    };
    final Settings settings = createBuilderWithPort().put(SETTING_CORS_ENABLED.getKey(), true).put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "test-cors.org").build();
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), new SharedGroupFactory(settings))) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        // Test pre-flight request
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/");
            request.headers().add(CorsHandler.ORIGIN, "test-cors.org");
            request.headers().add(CorsHandler.ACCESS_CONTROL_REQUEST_METHOD, "POST");
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(HttpResponseStatus.OK));
                assertThat(response.headers().get(CorsHandler.ACCESS_CONTROL_ALLOW_ORIGIN), equalTo("test-cors.org"));
                assertThat(response.headers().get(CorsHandler.VARY), equalTo(CorsHandler.ORIGIN));
                assertTrue(response.headers().contains(CorsHandler.DATE));
            } finally {
                response.release();
            }
        }
        // Test short-circuited request
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
            request.headers().add(CorsHandler.ORIGIN, "google.com");
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(HttpResponseStatus.FORBIDDEN));
            } finally {
                response.release();
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) SharedGroupFactory(org.opensearch.transport.SharedGroupFactory) HttpServerTransport(org.opensearch.http.HttpServerTransport) NullDispatcher(org.opensearch.http.NullDispatcher) FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Settings(org.opensearch.common.settings.Settings) HttpTransportSettings(org.opensearch.http.HttpTransportSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings)

Example 12 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class Netty4BadRequestTests method testBadParameterEncoding.

public void testBadParameterEncoding() throws Exception {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            fail();
        }

        @Override
        public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) {
            try {
                final Exception e = cause instanceof Exception ? (Exception) cause : new OpenSearchException(cause);
                channel.sendResponse(new BytesRestResponse(channel, RestStatus.BAD_REQUEST, e));
            } catch (final IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    };
    Settings settings = Settings.builder().put(HttpTransportSettings.SETTING_HTTP_PORT.getKey(), getPortRange()).build();
    try (HttpServerTransport httpServerTransport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), new SharedGroupFactory(Settings.EMPTY))) {
        httpServerTransport.start();
        final TransportAddress transportAddress = randomFrom(httpServerTransport.boundAddress().boundAddresses());
        try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
            final Collection<FullHttpResponse> responses = nettyHttpClient.get(transportAddress.address(), "/_cluster/settings?pretty=%");
            try {
                assertThat(responses, hasSize(1));
                assertThat(responses.iterator().next().status().code(), equalTo(400));
                final Collection<String> responseBodies = Netty4HttpClient.returnHttpResponseBodies(responses);
                assertThat(responseBodies, hasSize(1));
                assertThat(responseBodies.iterator().next(), containsString("\"type\":\"bad_parameter_exception\""));
                assertThat(responseBodies.iterator().next(), containsString("\"reason\":\"java.lang.IllegalArgumentException: unterminated escape sequence at end of string: %\""));
            } finally {
                responses.forEach(ReferenceCounted::release);
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) UncheckedIOException(java.io.UncheckedIOException) SharedGroupFactory(org.opensearch.transport.SharedGroupFactory) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpServerTransport(org.opensearch.http.HttpServerTransport) OpenSearchException(org.opensearch.OpenSearchException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) RestRequest(org.opensearch.rest.RestRequest) BytesRestResponse(org.opensearch.rest.BytesRestResponse) OpenSearchException(org.opensearch.OpenSearchException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpTransportSettings(org.opensearch.http.HttpTransportSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings) ReferenceCounted(io.netty.util.ReferenceCounted)

Example 13 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class NioHttpServerTransportTests method testCorsRequest.

public void testCorsRequest() throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            logger.error("--> Unexpected successful request [{}]", FakeRestRequest.requestToString(request));
            throw new AssertionError();
        }

        @Override
        public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            logger.error(new ParameterizedMessage("--> Unexpected bad request [{}]", FakeRestRequest.requestToString(channel.request())), cause);
            throw new AssertionError();
        }
    };
    final Settings settings = createBuilderWithPort().put(SETTING_CORS_ENABLED.getKey(), true).put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "test-cors.org").build();
    try (NioHttpServerTransport transport = new NioHttpServerTransport(settings, networkService, bigArrays, pageRecycler, threadPool, xContentRegistry(), dispatcher, new NioGroupFactory(settings, logger), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS))) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        // Test pre-flight request
        try (NioHttpClient client = new NioHttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/");
            request.headers().add(CorsHandler.ORIGIN, "test-cors.org");
            request.headers().add(CorsHandler.ACCESS_CONTROL_REQUEST_METHOD, "POST");
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(HttpResponseStatus.OK));
                assertThat(response.headers().get(CorsHandler.ACCESS_CONTROL_ALLOW_ORIGIN), equalTo("test-cors.org"));
                assertThat(response.headers().get(CorsHandler.VARY), equalTo(CorsHandler.ORIGIN));
                assertTrue(response.headers().contains(CorsHandler.DATE));
            } finally {
                response.release();
            }
        }
        // Test short-circuited request
        try (NioHttpClient client = new NioHttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
            request.headers().add(CorsHandler.ORIGIN, "google.com");
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(HttpResponseStatus.FORBIDDEN));
            } finally {
                response.release();
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) HttpServerTransport(org.opensearch.http.HttpServerTransport) NullDispatcher(org.opensearch.http.NullDispatcher) FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) NioGroupFactory(org.opensearch.transport.nio.NioGroupFactory) Settings(org.opensearch.common.settings.Settings) HttpTransportSettings(org.opensearch.http.HttpTransportSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings)

Example 14 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class NioHttpServerTransportTests method testLargeCompressedResponse.

public void testLargeCompressedResponse() throws InterruptedException {
    final String responseString = randomAlphaOfLength(4 * 1024 * 1024);
    final String url = "/thing";
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            if (url.equals(request.uri())) {
                channel.sendResponse(new BytesRestResponse(OK, responseString));
            } else {
                logger.error("--> Unexpected successful uri [{}]", request.uri());
                throw new AssertionError();
            }
        }

        @Override
        public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            logger.error(new ParameterizedMessage("--> Unexpected bad request [{}]", FakeRestRequest.requestToString(channel.request())), cause);
            throw new AssertionError();
        }
    };
    try (NioHttpServerTransport transport = new NioHttpServerTransport(Settings.EMPTY, networkService, bigArrays, pageRecycler, threadPool, xContentRegistry(), dispatcher, new NioGroupFactory(Settings.EMPTY, logger), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS))) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (NioHttpClient client = new NioHttpClient()) {
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, randomFrom("deflate", "gzip"));
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(HttpResponseStatus.OK));
                byte[] bytes = new byte[response.content().readableBytes()];
                response.content().readBytes(bytes);
                assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo(responseString));
            } finally {
                response.release();
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpServerTransport(org.opensearch.http.HttpServerTransport) NullDispatcher(org.opensearch.http.NullDispatcher) FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) BytesRestResponse(org.opensearch.rest.BytesRestResponse) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) NioGroupFactory(org.opensearch.transport.nio.NioGroupFactory)

Example 15 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class ActionModuleTests method testSetupRestHandlerContainsKnownBuiltin.

public void testSetupRestHandlerContainsKnownBuiltin() {
    SettingsModule settings = new SettingsModule(Settings.EMPTY);
    UsageService usageService = new UsageService();
    ActionModule actionModule = new ActionModule(settings.getSettings(), new IndexNameExpressionResolver(new ThreadContext(Settings.EMPTY)), settings.getIndexScopedSettings(), settings.getClusterSettings(), settings.getSettingsFilter(), null, emptyList(), null, null, usageService, null);
    actionModule.initRestHandlers(null);
    // At this point the easiest way to confirm that a handler is loaded is to try to register another one on top of it and to fail
    Exception e = expectThrows(IllegalArgumentException.class, () -> actionModule.getRestController().registerHandler(new RestHandler() {

        @Override
        public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
        }

        @Override
        public List<Route> routes() {
            return singletonList(new Route(Method.GET, "/"));
        }
    }));
    assertThat(e.getMessage(), startsWith("Cannot replace existing handler for [/] for method: GET"));
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) UsageService(org.opensearch.usage.UsageService) RestHandler(org.opensearch.rest.RestHandler) RestRequest(org.opensearch.rest.RestRequest) SettingsModule(org.opensearch.common.settings.SettingsModule) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) IOException(java.io.IOException)

Aggregations

RestChannel (org.opensearch.rest.RestChannel)17 RestRequest (org.opensearch.rest.RestRequest)17 ThreadContext (org.opensearch.common.util.concurrent.ThreadContext)15 ClusterSettings (org.opensearch.common.settings.ClusterSettings)12 FakeRestRequest (org.opensearch.test.rest.FakeRestRequest)12 TransportAddress (org.opensearch.common.transport.TransportAddress)11 HttpServerTransport (org.opensearch.http.HttpServerTransport)11 NullDispatcher (org.opensearch.http.NullDispatcher)10 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)9 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)8 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8 Settings (org.opensearch.common.settings.Settings)8 HttpTransportSettings (org.opensearch.http.HttpTransportSettings)7 BytesRestResponse (org.opensearch.rest.BytesRestResponse)7 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)6 IOException (java.io.IOException)6 SharedGroupFactory (org.opensearch.transport.SharedGroupFactory)6 NioGroupFactory (org.opensearch.transport.nio.NioGroupFactory)5 OpenSearchException (org.opensearch.OpenSearchException)3