Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: dispatch OPTIONS requests #10011

Merged
merged 13 commits into from
Nov 10, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package io.micronaut.http.client.jdk

import io.micronaut.context.ApplicationContext
import io.micronaut.context.annotation.Requires
import io.micronaut.core.util.StringUtils
import io.micronaut.http.HttpAttributes
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MutableHttpResponse
import io.micronaut.http.annotation.Controller
Expand All @@ -23,7 +26,7 @@ class OptionsRequestAttributesSpec extends Specification {

def 'test OPTIONS requests attributes'() {
EmbeddedServer server = ApplicationContext.run(EmbeddedServer, ['spec.name': 'OptionsRequestAttributesSpec'])
def ctx = server.applicationContext
ApplicationContext ctx = server.applicationContext
HttpClient client = ctx.createBean(HttpClient, server.getURL())

when:
Expand All @@ -32,6 +35,32 @@ class OptionsRequestAttributesSpec extends Specification {
then:
HttpClientResponseException e = thrown()
e.response.status == HttpStatus.METHOD_NOT_ALLOWED

cleanup:
ctx.close()
server.close()
}

def 'test OPTIONS requests attributes with micronaut.server.dispatch-options-requests enabled'() {
EmbeddedServer server = ApplicationContext.run(EmbeddedServer, ['spec.name': 'OptionsRequestAttributesSpec', 'micronaut.server.dispatch-options-requests': StringUtils.TRUE])
ApplicationContext ctx = server.applicationContext
HttpClient client = ctx.createBean(HttpClient, server.getURL())

when:
HttpResponse<?> response = client.toBlocking().exchange(HttpRequest.OPTIONS('/foo'), String)

then:
noExceptionThrown()
response.status == HttpStatus.OK
response.getHeaders().getAll(HttpHeaders.ALLOW)
3 == response.getHeaders().getAll(HttpHeaders.ALLOW).size()
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('GET')
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('OPTIONS')
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('HEAD')

cleanup:
ctx.close()
server.close()
}

@Singleton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package io.micronaut.http.server.netty

import io.micronaut.context.ApplicationContext
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpAttributes
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.MutableHttpResponse
import io.micronaut.core.util.StringUtils
import io.micronaut.http.*
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Filter
import io.micronaut.http.annotation.Get
Expand All @@ -23,7 +21,7 @@ class OptionsRequestAttributesSpec extends Specification {

def 'test OPTIONS requests attributes'() {
EmbeddedServer server = ApplicationContext.run(EmbeddedServer, ['spec.name': 'OptionsRequestAttributesSpec'])
def ctx = server.applicationContext
ApplicationContext ctx = server.applicationContext
HttpClient client = ctx.createBean(HttpClient, server.getURL())

when:
Expand All @@ -32,6 +30,32 @@ class OptionsRequestAttributesSpec extends Specification {
then:
HttpClientResponseException e = thrown()
e.response.status == HttpStatus.METHOD_NOT_ALLOWED

cleanup:
ctx.close()
server.close()
}

def 'test OPTIONS requests attributes with micronaut.server.dispatch-options-requests enabled'() {
EmbeddedServer server = ApplicationContext.run(EmbeddedServer, ['spec.name': 'OptionsRequestAttributesSpec', 'micronaut.server.dispatch-options-requests': StringUtils.TRUE])
ApplicationContext ctx = server.applicationContext
HttpClient client = ctx.createBean(HttpClient, server.getURL())

when:
HttpResponse<?> response = client.toBlocking().exchange(HttpRequest.OPTIONS('/foo'), String)

then:
noExceptionThrown()
response.status == HttpStatus.OK
response.getHeaders().getAll(HttpHeaders.ALLOW)
3 == response.getHeaders().getAll(HttpHeaders.ALLOW).size()
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('GET')
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('OPTIONS')
response.getHeaders().getAll(HttpHeaders.ALLOW).contains('HEAD')

cleanup:
ctx.close()
server.close()
}

@Singleton
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright 2017-2023 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server.tck.tests.filter.options;

import io.micronaut.context.annotation.Requires;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpMethod;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.*;
import io.micronaut.http.tck.AssertionUtils;
import io.micronaut.http.tck.HttpResponseAssertion;
import io.micronaut.http.tck.ServerUnderTest;
import io.micronaut.http.tck.TestScenario;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.function.BiConsumer;

import static org.junit.jupiter.api.Assertions.*;

@SuppressWarnings({
"java:S5960", // We're allowed assertions, as these are used in tests only
"checkstyle:MissingJavadocType",
"checkstyle:DesignForExtension"
})
public class OptionsFilterTest {
private static final String SPEC_NAME = "OptionsFilterTest";

@Test
public void optionsByDefaultResponds405() throws IOException {
TestScenario.builder()
.specName(SPEC_NAME)
.request(HttpRequest.OPTIONS("/foo/bar"))
.assertion(AssertionUtils.assertThrowsStatus(HttpStatus.METHOD_NOT_ALLOWED))
.run();
}

@Test
public void getTest() throws IOException {
assertion(HttpRequest.GET("/foo/bar"),
(server, request) ->
AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.build()));
}

@Test
public void optionsRoute() throws IOException {
assertion(HttpRequest.OPTIONS("/options/route"),
(server, request) ->
AssertionUtils.assertThrows(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.I_AM_A_TEAPOT)
.build()));
}

@Test
public void postTest() throws IOException {
assertion(HttpRequest.POST("/foo/bar", Collections.emptyMap()),
(server, request) ->
AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.CREATED)
.build()));
}

@Test
public void optionsTest() throws IOException {
assertion(HttpRequest.OPTIONS("/foo/bar"),
(server, request) ->
AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.assertResponse(httpResponse -> {
assertNotNull(httpResponse.getHeaders().get(HttpHeaders.ALLOW));
assertNotNull(httpResponse.getHeaders().getAll(HttpHeaders.ALLOW));
assertEquals(4, httpResponse.getHeaders().getAll(HttpHeaders.ALLOW).size());
assertTrue(httpResponse.getHeaders().getAll(HttpHeaders.ALLOW).stream().anyMatch(v -> v.equals(HttpMethod.GET.toString())));
assertTrue(httpResponse.getHeaders().getAll(HttpHeaders.ALLOW).stream().anyMatch(v -> v.equals(HttpMethod.POST.toString())));
assertTrue(httpResponse.getHeaders().getAll(HttpHeaders.ALLOW).stream().anyMatch(v -> v.equals(HttpMethod.OPTIONS.toString())));
assertTrue(httpResponse.getHeaders().getAll(HttpHeaders.ALLOW).stream().anyMatch(v -> v.equals(HttpMethod.HEAD.toString())));
})
.build()));
}

private static void assertion(HttpRequest<?> request, BiConsumer<ServerUnderTest, HttpRequest<?>> assertion) throws IOException {
TestScenario.builder()
.specName(SPEC_NAME)
.configuration(Collections.singletonMap("micronaut.server.dispatch-options-requests", StringUtils.TRUE))
.request(request)
.assertion(assertion)
.run();
}

@Controller
@Requires(property = "spec.name", value = SPEC_NAME)
public static class MyController {
@Get("/foo/{id}")
@Status(HttpStatus.OK)
public void fooGet(String id) {
}

@Post("/foo/{id}")
@Status(HttpStatus.CREATED)
public void fooPost(String id) {
}

@Options("/options/route")
@Status(HttpStatus.I_AM_A_TEAPOT)
public void optionsRoute() {
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ public class HttpServerConfiguration implements ServerContextPathProvider {
@SuppressWarnings("WeakerAccess")
public static final boolean DEFAULT_HTTP_TO_HTTPS_REDIRECT = false;


/**
* The default value whether to dispatch OPTIONS Requests.
*/
@SuppressWarnings("WeakerAccess")
public static final boolean DEFAULT_DISPATCH_OPTIONS_REQUESTS = false;
private Integer port;
private String host;
private Integer readTimeout;
Expand All @@ -134,6 +140,9 @@ public class HttpServerConfiguration implements ServerContextPathProvider {
private String contextPath;
private boolean dualProtocol = DEFAULT_DUAL_PROTOCOL;
private boolean httpToHttpsRedirect = DEFAULT_HTTP_TO_HTTPS_REDIRECT;

private boolean dispatchOptionsRequests = DEFAULT_DISPATCH_OPTIONS_REQUESTS;

private HttpVersion httpVersion = HttpVersion.HTTP_1_1;
private final ApplicationConfiguration applicationConfiguration;
private Charset defaultCharset;
Expand Down Expand Up @@ -339,6 +348,15 @@ public boolean isHttpToHttpsRedirect() {
return httpToHttpsRedirect;
}

/**
* Set to true to dispatch OPTIONS requests. Default value ({@value #DEFAULT_DISPATCH_OPTIONS_REQUESTS}.
* @return Whether OPTIONS requests should be dispatched.
* @since 4.2.0
*/
public boolean isDispatchOptionsRequests() {
sdelamo marked this conversation as resolved.
Show resolved Hide resolved
return dispatchOptionsRequests;
}

/**
* @param defaultCharset The default charset to use
*/
Expand Down Expand Up @@ -506,6 +524,15 @@ public void setHttpToHttpsRedirect(boolean httpToHttpsRedirect) {
this.httpToHttpsRedirect = httpToHttpsRedirect;
}

/**
* Set to true to dispatch OPTIONS requests. Default value ({@value #DEFAULT_DISPATCH_OPTIONS_REQUESTS}.
* @param dispatchOptionsRequests Set to true to dispatch OPTIONS requests.
* @since 4.2.0
*/
public void setDispatchOptionsRequests(boolean dispatchOptionsRequests) {
sdelamo marked this conversation as resolved.
Show resolved Hide resolved
this.dispatchOptionsRequests = dispatchOptionsRequests;
}

/**
* Configuration for multipart handling.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2017-2023 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server;

import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.order.Ordered;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.*;
import io.micronaut.http.annotation.RequestFilter;
import io.micronaut.http.annotation.ServerFilter;
import io.micronaut.http.server.cors.CorsUtil;
import io.micronaut.web.router.Router;
import io.micronaut.web.router.UriRouteMatch;
import io.micronaut.web.router.RouteMatch;

import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN;
import static io.micronaut.http.server.cors.CorsFilter.CORS_FILTER_ORDER;

/**
* This Filter intercepts HTTP OPTIONS requests which are not CORS Preflight requests.
* It responds with a NO_CONTENT(204) response, and it populates the Allow HTTP Header with the supported HTTP methods for the request URI.
* @author Sergio del Amo
* @since 4.2.0
*/
@Requires(property = OptionsFilter.PREFIX, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE)
@ServerFilter(MATCH_ALL_PATTERN)
@Internal
public final class OptionsFilter implements Ordered {

@SuppressWarnings("WeakerAccess")
public static final String PREFIX = HttpServerConfiguration.PREFIX + ".dispatch-options-requests";

private final Router router;

/**
*
* @param router Router
*/
public OptionsFilter(Router router) {
this.router = router;
}

@RequestFilter
@Nullable
@Internal
public HttpResponse<?> filterRequest(HttpRequest<?> request) {
if (request.getMethod() != HttpMethod.OPTIONS) {
return null; // proceed
}
if (CorsUtil.isPreflightRequest(request)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be better to run the CORS filter first instead of this check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added a commit to ensure the CorsFilter happens before the Optionsfilter. However, I think it is more correct to leave this if check in place.

return null; // proceed
}
if (hasOptionsRouteMatch(request)) {
return null; // proceed
}
MutableHttpResponse<?> mutableHttpResponse = HttpResponse.status(HttpStatus.OK);
router.findAny(request.getUri().toString(), request)
.map(UriRouteMatch::getHttpMethod)
.map(HttpMethod::toString)
.forEach(allow -> mutableHttpResponse.header(HttpHeaders.ALLOW, allow));
mutableHttpResponse.header(HttpHeaders.ALLOW, HttpMethod.OPTIONS.toString());
return mutableHttpResponse;
}

private boolean hasOptionsRouteMatch(HttpRequest<?> request) {
return request.getAttribute(HttpAttributes.ROUTE_MATCH, RouteMatch.class).map(routeMatch -> {
if (routeMatch instanceof UriRouteMatch<?, ?> uriRouteMatch) {
return uriRouteMatch.getHttpMethod() == HttpMethod.OPTIONS;
}
return true;
}).orElse(false);
}

@Override
public int getOrder() {
return CORS_FILTER_ORDER + 10;
}
}
Loading
Loading