diff --git a/src/main/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilter.java new file mode 100644 index 0000000000..b9230e942d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilter.java @@ -0,0 +1,127 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.vertx.http.runtime.CurrentVertxRequest; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.SocketAddress; +import io.vertx.ext.web.RoutingContext; +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.ext.Provider; +import org.jboss.logging.Logger; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Gives an HTTP/1.0 request that omitted {@code Host} the authority it never sent. + * + *

{@code Host} is mandatory only from HTTP/1.1 on: Vert.x answers 400 to a 1.1 request without + * one and exempts 1.0 by design. A 1.0 request then reaches the application with no authority + * anywhere, so {@code HttpServerRequest.absoluteURI()} is null and + * {@code UriInfo.getRequestUri()} fails inside {@code new URI(null)}. Every host-routing filter + * reads the request URI, through {@link RequestHost} or directly, so a plain + * {@code GET /_floci/health HTTP/1.0} answered 500 on a healthy emulator, which reads as a hard + * outage to a probe written without a {@code Host} header. Nothing about it is health-specific: + * every endpoint answered 500 the same way. + * + *

The repair is the request URI rather than the {@code Host} header. Vert.x resolves the + * authority once, in {@code RoutingContextImpl.route()}, before any handler runs, and caches the + * absence; a header set afterwards is never looked at again. Rewriting the JAX-RS request URI + * instead gives {@code UriInfo} the scheme, authority and path it needs, which is the same + * mechanism the virtual-host filters use to reroute a request. + * + *

An origin-form target names no host anywhere, so the authority filled in for one is the local + * socket the request arrived on, the address the client actually reached. It carries no virtual-host + * meaning: an address literal names no S3 bucket, Lambda function URL, or custom domain, so the + * request routes path-style, which is what a client sending no {@code Host} asked for. + * + *

An absolute-form target, which RFC 9112 section 3.2.2 requires a server to accept, states an + * authority of its own: {@code GET http://bucket.s3.localhost:4566/key HTTP/1.0} names a bucket and + * has to keep routing to it. It is broken without a {@code Host} header just the same, because the + * authority vertx-web builds its absolute URI from is that header alone. Prepending the local socket + * to a target that is already absolute would corrupt it instead: {@code URI} reads the concatenation + * as the authority {@code 127.0.0.1:4566http:} and the path {@code //bucket.s3.localhost:4566/key}. + * Asterisk-form names no host at all and is left alone, as it is with a {@code Host} header. + */ +@Provider +@PreMatching +@Priority(1) // ahead of every host-routing filter, the lowest of which is LambdaUrlRoutingFilter (5) +@ApplicationScoped +public class MissingHostHeaderFilter implements ContainerRequestFilter { + + private static final Logger LOG = Logger.getLogger(MissingHostHeaderFilter.class); + + private final CurrentVertxRequest currentVertxRequest; + + @Inject + public MissingHostHeaderFilter(CurrentVertxRequest currentVertxRequest) { + this.currentVertxRequest = currentVertxRequest; + } + + @Override + public void filter(ContainerRequestContext requestContext) { + RoutingContext routingContext = currentVertxRequest.getCurrent(); + if (routingContext == null) { + return; + } + // An HTTP/2 request has no Host header either, but carries :authority, which Vert.x + // surfaces here. A null authority is the one case with nothing to route by. + HttpServerRequest request = routingContext.request(); + if (request.authority() != null) { + return; + } + String authority = requestAuthority(request); + if (authority == null) { + return; + } + // The scheme is the connection's rather than the target's, which is what vertx-web itself + // uses once a Host header supplies the authority. + URI requestUri = URI.create(request.scheme() + "://" + authority + pathAndQuery(request)); + // The two-argument form: the one-argument one derives the base URI from UriInfo, which is + // the accessor that fails without an authority. + requestContext.setRequestUri(requestUri.resolve("/"), requestUri); + LOG.debugv("Request without an authority: {0} -> {1}", request.uri(), requestUri); + } + + /** + * The authority to route by: the one an absolute-form target states, the local socket for an + * origin-form one. Null when the target names no host and none can stand in for it. + */ + static String requestAuthority(HttpServerRequest request) { + String target = request.uri(); + if (target.startsWith("/")) { + return localAuthority(request.localAddress()); + } + URI absolute; + try { + absolute = new URI(target); + } catch (URISyntaxException malformed) { + LOG.debugv("Request target is neither origin-form nor an absolute URI: {0}", target); + return null; + } + // Asterisk-form and authority-form land here with no authority to read. + return absolute.isAbsolute() ? absolute.getRawAuthority() : null; + } + + /** The origin-form tail, which Vert.x parses out of an absolute-form target as well. */ + private static String pathAndQuery(HttpServerRequest request) { + String query = request.query(); + return query == null ? request.path() : request.path() + "?" + query; + } + + /** {@code host:port}, bracketing an IPv6 literal the way RFC 3986 requires. */ + static String localAuthority(SocketAddress localAddress) { + if (localAddress == null || localAddress.host() == null) { + return null; + } + String host = localAddress.host(); + if (host.indexOf(':') >= 0 && !host.startsWith("[")) { + host = "[" + host + "]"; + } + return localAddress.port() > 0 ? host + ":" + localAddress.port() : host; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilterTest.java new file mode 100644 index 0000000000..e8fe454a53 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderFilterTest.java @@ -0,0 +1,75 @@ +package io.github.hectorvent.floci.core.common; + +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.SocketAddress; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class MissingHostHeaderFilterTest { + + @Test + void originFormTakesTheAuthorityFromTheLocalSocket() { + assertEquals("127.0.0.1:4566", MissingHostHeaderFilter.requestAuthority(request("/_floci/health"))); + } + + @Test + void absoluteFormTakesTheAuthorityFromTheTarget() { + assertEquals("bucket.s3.localhost:4566", + MissingHostHeaderFilter.requestAuthority(request("http://bucket.s3.localhost:4566/key"))); + } + + @Test + void absoluteFormWithoutAPathTakesTheAuthorityFromTheTarget() { + assertEquals("bucket.s3.localhost:4566", + MissingHostHeaderFilter.requestAuthority(request("http://bucket.s3.localhost:4566"))); + } + + @Test + void asteriskFormHasNoAuthority() { + assertNull(MissingHostHeaderFilter.requestAuthority(request("*"))); + } + + @Test + void malformedTargetHasNoAuthority() { + assertNull(MissingHostHeaderFilter.requestAuthority(request("http://bucket.s3.localhost:45 66/key"))); + } + + @Test + void localAuthorityKeepsIpv4Literal() { + assertEquals("127.0.0.1:4566", + MissingHostHeaderFilter.localAuthority(SocketAddress.inetSocketAddress(4566, "127.0.0.1"))); + } + + @Test + void localAuthorityBracketsIpv6Literal() { + assertEquals("[::1]:4566", + MissingHostHeaderFilter.localAuthority(SocketAddress.inetSocketAddress(4566, "::1"))); + } + + @Test + void localAuthorityLeavesBracketedIpv6Alone() { + assertEquals("[::1]:4566", + MissingHostHeaderFilter.localAuthority(SocketAddress.inetSocketAddress(4566, "[::1]"))); + } + + @Test + void localAuthorityWithoutAddressIsNull() { + assertNull(MissingHostHeaderFilter.localAuthority(null)); + } + + @Test + void localAuthorityOfDomainSocketIsNull() { + assertNull(MissingHostHeaderFilter.localAuthority(SocketAddress.domainSocketAddress("/tmp/floci.sock"))); + } + + private static HttpServerRequest request(String target) { + HttpServerRequest request = mock(HttpServerRequest.class); + when(request.uri()).thenReturn(target); + when(request.localAddress()).thenReturn(SocketAddress.inetSocketAddress(4566, "127.0.0.1")); + return request; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderIntegrationTest.java new file mode 100644 index 0000000000..7e1be6b7cb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/MissingHostHeaderIntegrationTest.java @@ -0,0 +1,100 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.charset.StandardCharsets; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.startsWith; + +/** + * A Host-less request cannot be expressed with RestAssured or any SDK client, so these go over a + * raw socket. HTTP/1.0 omitting Host is legal and used to answer 500; HTTP/1.1 omitting it is a + * protocol violation that Vert.x rejects before the router, and still should. An absolute-form + * target states its own authority and must keep routing by it, Host header or not. + */ +@QuarkusTest +class MissingHostHeaderIntegrationTest { + + @Test + void http10WithoutHostHeaderServesHealth() throws Exception { + String response = rawRequest("GET /_floci/health HTTP/1.0\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.0 200 OK")); + assertThat(response, containsString("\"edition\":\"community\"")); + } + + @Test + void http10WithoutHostHeaderServesPathStyleS3() throws Exception { + String response = rawRequest("GET / HTTP/1.0\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.0 200 OK")); + assertThat(response, containsString("ListAllMyBucketsResult")); + } + + @Test + void http10AbsoluteFormWithoutHostHeaderServesHealth() throws Exception { + String response = rawRequest( + "GET http://127.0.0.1:" + RestAssured.port + "/_floci/health HTTP/1.0\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.0 200 OK")); + assertThat(response, containsString("\"edition\":\"community\"")); + } + + @Test + void http10AbsoluteFormWithoutHostHeaderRoutesByTheTargetAuthority() throws Exception { + String bucket = "absolute-form-bucket"; + given().put("/" + bucket).then().statusCode(200); + try { + String response = rawRequest("GET http://" + bucket + ".s3.localhost:" + + RestAssured.port + "/ HTTP/1.0\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.0 200 OK")); + assertThat(response, containsString("" + bucket + "")); + } finally { + given().delete("/" + bucket); + } + } + + @Test + void http11WithoutHostHeaderIsRejected() throws Exception { + String response = rawRequest("GET /_floci/health HTTP/1.1\r\nConnection: close\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.1 400 Bad Request")); + } + + @Test + void http11WithHostHeaderServesHealth() throws Exception { + String response = rawRequest( + "GET /_floci/health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"); + + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("\"edition\":\"community\"")); + } + + private String rawRequest(String request) throws Exception { + try (Socket socket = new Socket("127.0.0.1", RestAssured.port)) { + socket.setSoTimeout(15_000); + OutputStream out = socket.getOutputStream(); + out.write(request.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + + InputStream in = socket.getInputStream(); + ByteArrayOutputStream received = new ByteArrayOutputStream(); + byte[] chunk = new byte[8192]; + int read; + while ((read = in.read(chunk)) != -1) { + received.write(chunk, 0, read); + } + return received.toString(StandardCharsets.UTF_8); + } + } +}