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

conjure-undertow supports OPTIONS requests. #480

Merged
merged 4 commits into from
Aug 2, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.palantir.conjure.java.undertow.runtime;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Lists;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.palantir.conjure.java.undertow.lib.Endpoint;
Expand All @@ -31,6 +32,7 @@
import io.undertow.server.handlers.BlockingHandler;
import io.undertow.server.handlers.ResponseCodeHandler;
import io.undertow.server.handlers.URLDecodingHandler;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -51,6 +53,22 @@ private ConjureHandler(
List<Endpoint> endpoints) {
this.routingHandler = Handlers.routing().setFallbackHandler(fallback);
endpoints.forEach(this::register);
registerOptionsEndpoints(endpoints);
}

private void registerOptionsEndpoints(List<Endpoint> endpoints) {
ImmutableSetMultimap<String, HttpString> pathToMethod = endpoints.stream()
.filter(endpoint -> !Methods.OPTIONS.equals(endpoint.method()))
.collect(ImmutableSetMultimap.toImmutableSetMultimap(
endpoint -> normalizeTemplate(endpoint.template()),
Endpoint::method));
// Once UNDERTOW-1581 is fixed we should register OPTIONS handling directly with routingHandler
// instead of using setInvalidMethodHandler.
RoutingHandler optionalRoutingHandler = Handlers.routing()
.setFallbackHandler(ResponseCodeHandler.HANDLE_405);
pathToMethod.keySet().forEach(normalizedPath -> optionalRoutingHandler.add(Methods.OPTIONS, normalizedPath,
new WebSecurityHandler(new OptionsHandler(pathToMethod.get(normalizedPath)))));
routingHandler.setInvalidMethodHandler(optionalRoutingHandler);
}

@Override
Expand Down Expand Up @@ -170,7 +188,7 @@ private void checkOverlappingPaths() {
endpoint -> String.format(
"%s: %s",
endpoint.method(),
endpoint.template().replaceAll("\\{.*?\\}", "{param}"))))
normalizeTemplate(endpoint.template()))))
.entrySet()
.stream().filter(groups -> groups.getValue().size() > 1)
.map(entry -> {
Expand All @@ -186,4 +204,8 @@ private void checkOverlappingPaths() {
}
}
}

private static String normalizeTemplate(String template) {
return template.replaceAll("\\{.*?\\}", "{param}");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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
*
* http://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 com.palantir.conjure.java.undertow.runtime;

import com.google.common.base.Joiner;
import com.palantir.logsafe.Preconditions;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.StatusCodes;
import java.util.Set;

final class OptionsHandler implements HttpHandler {

private final String allowValue;

OptionsHandler(Set<HttpString> methods) {
this.allowValue = Joiner.on(", ").join(methods);
}

@Override
public void handleRequest(HttpServerExchange exchange) {
Preconditions.checkState(Methods.OPTIONS.equals(exchange.getRequestMethod()), "Expected an OPTIONS request");
exchange.getResponseHeaders().put(Headers.ALLOW, allowValue);
exchange.setStatusCode(StatusCodes.NO_CONTENT);
Copy link
Contributor

@iamdanfox iamdanfox Aug 2, 2019

Choose a reason for hiding this comment

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

Do we want Access-Control-Max-Age too? https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request I assume this lets browsers cache this for a bit?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If we want to set Access-Control headers, I think that belongs in WebSecurityHandler. I don't think there's anything specific to options requests for access control headers beyond standard browser use, but I'm not completely confident on that.

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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
*
* http://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 com.palantir.conjure.java.undertow.runtime;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.net.HttpHeaders;
import com.palantir.conjure.java.undertow.lib.Endpoint;
import io.undertow.Undertow;
import io.undertow.server.handlers.ResponseCodeHandler;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import java.io.IOException;
import java.util.UUID;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public final class OptionsRequestTest {

private static final OkHttpClient client = new OkHttpClient.Builder()
.followRedirects(false)
.retryOnConnectionFailure(false)
.build();

private Undertow server;

@BeforeEach
public void before() {
server = Undertow.builder()
.addHttpListener(12346, "localhost")
.setHandler(ConjureHandler.builder()
.endpoints(endpoint(Methods.GET, "/first"))
.endpoints(endpoint(Methods.POST, "/first"))
.endpoints(endpoint(Methods.PUT, "/second/{param}"))
.build())
.build();
server.start();
}

@AfterEach
public void after() {
server.stop();
}

@Test
public void test_getAndPost() {
Response response = execute("/first");
assertThat(response.code()).isEqualTo(204);
assertThat(response.header(HttpHeaders.ALLOW)).isEqualTo("GET, POST");
}

@Test
public void test_webSecurityHeaders() {
Response response = execute("/first");
assertThat(response.code()).isEqualTo(204);
assertThat(response.header(HttpHeaders.CONTENT_SECURITY_POLICY)).isNotNull();
}

@Test
public void test_parameterized() {
Response response = execute("/second/paramValue");
assertThat(response.code()).isEqualTo(204);
assertThat(response.header(HttpHeaders.ALLOW)).isEqualTo("PUT");
}

private static Response execute(String path) {
Request request = new Request.Builder()
.method("OPTIONS", null)
.url("http://localhost:12346" + path)
.build();
try {
return client.newCall(request).execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private static Endpoint endpoint(HttpString method, String template) {
return Endpoint.builder()
.handler(ResponseCodeHandler.HANDLE_500)
.method(method)
.template(template)
.serviceName(UUID.randomUUID().toString())
.name(UUID.randomUUID().toString())
.build();
}
}