You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/10/16 20:15:07 UTC
(juneau) branch master updated: Bind the bus websocket CSRF boundary to a trusted Forwarded/X-Forwarded host and proto with trustedHops and new boundary reason codes (J0802); and compare HC4.5 and policy redirect hops against the first origin, restoring credentials only on GET/HEAD returns, refusing userinfo in redirect Locations and legacy AbstractHttpClient instances, and stripping Proxy-Authorization on tunnelled routes (J0824)
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new 92eaf14d58 Bind the bus websocket CSRF boundary to a trusted Forwarded/X-Forwarded host and proto with trustedHops and new boundary reason codes (J0802); and compare HC4.5 and policy redirect hops against the first origin, restoring credentials only on GET/HEAD returns, refusing userinfo in redirect Locations and legacy AbstractHttpClient instances, and stripping Proxy-Authorization on tunnelled routes (J0824)
92eaf14d58 is described below
commit 92eaf14d58de1ab4ceffc3ca249f9efc8bd1b3e2
Author: James Bognar <ja...@apache.org>
AuthorDate: Fri Oct 16 16:15:01 2026 -0400
Bind the bus websocket CSRF boundary to a trusted Forwarded/X-Forwarded host and proto with trustedHops and new boundary reason codes (J0802); and compare HC4.5 and policy redirect hops against the first origin, restoring credentials only on GET/HEAD returns, refusing userinfo in redirect Locations and legacy AbstractHttpClient instances, and stripping Proxy-Authorization on tunnelled routes (J0824)
---
.../jetty/CsrfBoundaryForwarded_JettyIT.java | 296 ++++++++++++
.../microservice/jetty/CsrfBoundary_JettyIT.java | 17 +
.../apachehttpclient45/ApacheHc45Transport.java | 44 +-
.../ApacheHc45TransportBuilder.java | 10 +-
.../Hc45RedirectCredentialGuard.java | 103 ++--
...sport_CallerClientRedirectCredentials_Test.java | 183 ++++++-
...ransport_CallerClientRetryCredentials_Test.java | 7 +-
...acheHc45Transport_RedirectCredentials_Test.java | 6 +-
.../ApacheHc45Transport_Policy_Test.java | 86 ++++
.../Hc45RedirectCredentialGuard_Test.java | 166 +++++++
.../rest/client/PolicyEnforcedRedirects.java | 34 +-
.../rest/client/PolicyEnforcedRedirects_Test.java | 74 ++-
.../bus/websocket/BusWebSocketConfigurator.java | 20 +-
.../websocket/BusWebSocketConfigurator_Test.java | 55 +++
.../juneau/rest/server/filter/BoundaryReason.java | 29 +-
.../juneau/rest/server/filter/CsrfBoundary.java | 282 ++++++++++-
.../juneau/rest/server/filter/ForwardedOrigin.java | 301 ++++++++++++
.../server/filter/CsrfBoundaryFilter_Test.java | 22 +-
.../server/filter/CsrfBoundaryForwarded_Test.java | 538 +++++++++++++++++++++
19 files changed, 2163 insertions(+), 110 deletions(-)
diff --git a/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundaryForwarded_JettyIT.java b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundaryForwarded_JettyIT.java
new file mode 100644
index 0000000000..ecddc303f8
--- /dev/null
+++ b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundaryForwarded_JettyIT.java
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.juneau.microservice.jetty;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.net.*;
+import java.net.http.*;
+import java.net.http.HttpResponse.*;
+import java.time.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.marshall.collections.*;
+import org.apache.juneau.rest.server.*;
+import org.apache.juneau.rest.server.bus.*;
+import org.apache.juneau.rest.server.bus.websocket.*;
+import org.apache.juneau.rest.server.filter.*;
+import org.apache.juneau.rest.server.servlet.*;
+import org.eclipse.jetty.ee11.servlet.*;
+import org.eclipse.jetty.ee11.websocket.jakarta.server.config.*;
+import org.eclipse.jetty.server.*;
+import org.junit.jupiter.api.*;
+import org.junit.jupiter.api.condition.*;
+
+import jakarta.servlet.*;
+import jakarta.servlet.http.*;
+
+/**
+ * {@link CsrfBoundary.Builder#trustedForwarding(CsrfBoundary.ForwardedSource) Trusted forwarding} over a real Jetty 12
+ * (ee11) socket, on HTTP writes and on the bus WebSocket handshake.
+ *
+ * <p>
+ * Each test starts a server of its own, because the boundary is the thing that varies. Without the container's
+ * {@link ForwardedRequestCustomizer} the container does no forwarding at all, which is the case the setting exists for;
+ * with it (and {@code originSource(CONTAINER)}) the boundary cross-checks the container's rewrite, and those rows record
+ * what Jetty reports before asserting.
+ *
+ * <p>
+ * Binds a socket, so it is off by default. Run it with {@code -Djuneau.busIt=true}, outside the sandbox.
+ */
+@EnabledIfSystemProperty(named=CsrfBoundary_JettyIT.GATE, matches="true",
+ disabledReason="binds a socket; run with -Dtest='CsrfBoundaryForwarded_JettyIT' -Djuneau.busIt=true")
+class CsrfBoundaryForwarded_JettyIT extends TestBase {
+
+ private static final String PUBLIC = "https://app.example";
+ private static final String JSON = "application/json";
+ private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
+
+ @Rest
+ public static class BusRest extends BasicRestServlet implements BusEventsMixin {
+ private static final long serialVersionUID = 1L;
+ private final transient ServerBus bus;
+ BusRest(ServerBus bus) { this.bus = bus; }
+ @Override public ServerBus serverBus() { return bus; }
+ }
+
+ /** Counts the writes that reached it. */
+ static final class WriteServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+ static final java.util.concurrent.atomic.AtomicInteger WRITES = new java.util.concurrent.atomic.AtomicInteger();
+ @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
+ WRITES.incrementAndGet();
+ res.getWriter().write("written");
+ }
+ }
+
+ /** Reports the container's own view of the request: scheme, server name and server port. */
+ static final class SeenServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+ @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
+ res.getWriter().write(req.getScheme() + "|" + req.getServerName() + "|" + req.getServerPort());
+ }
+ }
+
+ record App(Server server, int port, CsrfBoundary boundary, ServerBus bus) {
+ String origin() { return "http://127.0.0.1:" + port; }
+ }
+
+ private App app;
+
+ @AfterEach void stop() throws Exception {
+ if (app != null) {
+ app.bus().close();
+ app.server().stop();
+ }
+ app = null;
+ }
+
+ private App start(boolean customizer, CsrfBoundary.Builder b) throws Exception {
+ var boundary = b.tokens(CsrfTokens.perProcess()).build();
+ var bus = ServerBus.create(BusPolicy.create().downstream("ops.jobs", true).boundary(boundary).build());
+ var server = new Server();
+ var config = new HttpConfiguration();
+ if (customizer)
+ config.addCustomizer(new ForwardedRequestCustomizer());
+ var connector = new ServerConnector(server, new HttpConnectionFactory(config));
+ connector.setHost("127.0.0.1");
+ connector.setPort(0);
+ server.addConnector(connector);
+ var ctx = new ServletContextHandler();
+ ctx.setContextPath("/");
+ ctx.addFilter(new FilterHolder(new RequestBoundaryFilter(boundary)), "/write", EnumSet.of(DispatcherType.REQUEST));
+ ctx.addServlet(new ServletHolder(new WriteServlet()), "/write");
+ ctx.addServlet(new ServletHolder(new SeenServlet()), "/seen");
+ ctx.addServlet(new ServletHolder(new BusRest(bus)), "/rest/*");
+ JakartaWebSocketServletContainerInitializer.configure(ctx, (sc, container) -> BusWebSockets.register(container, bus));
+ server.setHandler(ctx);
+ server.start();
+ bus.publish("ops.jobs", JsonMap.of("schemaVersion", 1, "running", List.of()));
+ app = new App(server, connector.getLocalPort(), boundary, bus);
+ WriteServlet.WRITES.set(0);
+ return app;
+ }
+
+ private static String token(CsrfBoundary boundary) {
+ var req = (HttpServletRequest) java.lang.reflect.Proxy.newProxyInstance(HttpServletRequest.class.getClassLoader(),
+ new Class<?>[]{HttpServletRequest.class}, (proxy, method, args) -> method.getReturnType() == boolean.class ? (Object) false : null);
+ return boundary.tokenFor(req);
+ }
+
+ private static HttpResponse<String> post(App a, String path, String body, String...headers) throws Exception {
+ var b = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + a.port() + path)).timeout(Duration.ofSeconds(10))
+ .header("Content-Type", JSON).header("Accept", JSON).header(a.boundary().csrfHeader(), token(a.boundary()));
+ for (var i = 0; i < headers.length; i += 2)
+ b.header(headers[i], headers[i + 1]);
+ return HTTP.send(b.POST(HttpRequest.BodyPublishers.ofString(body)).build(), BodyHandlers.ofString());
+ }
+
+ private static String[] forwarded(String origin, String host, String proto) {
+ return new String[] { "Origin", origin, "X-Forwarded-Host", host, "X-Forwarded-Proto", proto };
+ }
+
+ private static final String SESSION = "{\"v\":1,\"bridge\":\"ops\",\"transport\":\"websocket\",\"downstream\":[\"ops.jobs\"],\"upstream\":[]}";
+
+ /** Opens a bus session with the given headers; returns the response. */
+ private static HttpResponse<String> session(App a, String...headers) throws Exception {
+ return post(a, "/rest" + BusEventsMixin.SESSION_PATH, SESSION, headers);
+ }
+
+ private static String wsPath(HttpResponse<String> res) throws Exception {
+ assertEquals(200, res.statusCode(), res::body);
+ return JsonMap.ofString(res.body()).getMap("paths").getString("websocket");
+ }
+
+ /** Collects the first frame and the close code. */
+ static final class Frames implements WebSocket.Listener {
+ final BlockingQueue<String> frames = new LinkedBlockingQueue<>();
+ final CompletableFuture<Integer> closed = new CompletableFuture<>();
+ @Override public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
+ frames.add(data.toString());
+ ws.request(1);
+ return null;
+ }
+ @Override public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
+ closed.complete(statusCode);
+ return null;
+ }
+ }
+
+ /** Connects and reports whether the bus delivered a frame (admitted) or closed 4403 (refused). */
+ private static boolean connects(App a, String path, String...headers) throws Exception {
+ var frames = new Frames();
+ var b = HttpClient.newHttpClient().newWebSocketBuilder();
+ for (var i = 0; i < headers.length; i += 2)
+ b.header(headers[i], headers[i + 1]);
+ var ws = b.buildAsync(URI.create("ws://127.0.0.1:" + a.port() + path), frames).get(10, TimeUnit.SECONDS);
+ var first = frames.frames.poll(5, TimeUnit.SECONDS);
+ if (first != null) {
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "").get(10, TimeUnit.SECONDS);
+ return true;
+ }
+ assertEquals(4403, frames.closed.get(10, TimeUnit.SECONDS));
+ return false;
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // No customizer: the boundary is the forwarding authority
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void b01_forwardedWriteAndHandshakeAdmittedWithoutAnyContainerForwarding() throws Exception {
+ var a = start(false, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ var write = post(a, "/write", "{}", forwarded(PUBLIC, "app.example", "https"));
+ assertEquals(200, write.statusCode(), write::body);
+ var path = wsPath(session(a, forwarded(PUBLIC, "app.example", "https")));
+ assertTrue(connects(a, path, forwarded(PUBLIC, "app.example", "https")));
+ }
+
+ @Test void b02_forwardedHostNotMatchingOriginRefused() throws Exception {
+ var a = start(false, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ var write = post(a, "/write", "{}", forwarded("https://evil.example", "app.example", "https"));
+ assertEquals(403, write.statusCode(), write::body);
+ assertEquals("ORIGIN_MISMATCH", write.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ assertEquals(0, WriteServlet.WRITES.get());
+ var path = wsPath(session(a, forwarded(PUBLIC, "app.example", "https")));
+ assertFalse(connects(a, path, forwarded("https://evil.example", "app.example", "https")));
+ }
+
+ @Test void b03_settingOffRefusesTheSameRequests() throws Exception {
+ var a = start(false, CsrfBoundary.create());
+ var write = post(a, "/write", "{}", forwarded(PUBLIC, "app.example", "https"));
+ assertEquals(403, write.statusCode(), write::body);
+ assertEquals("ORIGIN_MISMATCH", write.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ var path = wsPath(session(a, "Origin", a.origin()));
+ assertFalse(connects(a, path, forwarded(PUBLIC, "app.example", "https")));
+ }
+
+ @Test void b04_missingHeaderRefused() throws Exception {
+ var a = start(false, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ var write = post(a, "/write", "{}", "Origin", a.origin());
+ assertEquals(403, write.statusCode(), write::body);
+ assertEquals("FORWARDED_HOST_MISSING", write.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ // The session POST is judged the same way, so there is no session to hand a handshake: a proto-only request too.
+ var proto = post(a, "/write", "{}", "Origin", a.origin(), "X-Forwarded-Proto", "http");
+ assertEquals("FORWARDED_HOST_MISSING", proto.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ assertEquals(0, WriteServlet.WRITES.get());
+ }
+
+ @Test void b05_forwardedFamilyNotNamedIsNotRead() throws Exception {
+ var a = start(false, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.FORWARDED));
+ var write = post(a, "/write", "{}", "Origin", PUBLIC, "Forwarded", "host=app.example;proto=https");
+ assertEquals(200, write.statusCode(), write::body);
+ var other = post(a, "/write", "{}", forwarded(PUBLIC, "app.example", "https"));
+ assertEquals("FORWARDED_HOST_MISSING", other.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Customizer plus CONTAINER: the boundary cross-checks the container's rewrite
+ //-----------------------------------------------------------------------------------------------------------------
+
+ private static String seen(App a, String...headers) throws Exception {
+ var b = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + a.port() + "/seen")).timeout(Duration.ofSeconds(10));
+ for (var i = 0; i < headers.length; i += 2)
+ b.header(headers[i], headers[i + 1]);
+ return HTTP.send(b.GET().build(), BodyHandlers.ofString()).body();
+ }
+
+ @Test void b06_containerAgreesAndHandshakeIsAdmitted() throws Exception {
+ var a = start(true, CsrfBoundary.create().originSource(CsrfBoundary.OriginSource.CONTAINER)
+ .trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ // Recorded Jetty behavior: the customizer rewrites scheme, server name and port from the forwarded headers.
+ assertEquals("https|app.example|443", seen(a, "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https"));
+ var write = post(a, "/write", "{}", forwarded(PUBLIC, "app.example", "https"));
+ assertEquals(200, write.statusCode(), write::body);
+ var path = wsPath(session(a, forwarded(PUBLIC, "app.example", "https")));
+ assertTrue(connects(a, path, forwarded(PUBLIC, "app.example", "https")));
+ assertFalse(connects(a, path, forwarded("https://evil.example", "app.example", "https")));
+ }
+
+ @Test void b07_containerTakingTheLeftmostEntryIsCaught() throws Exception {
+ var a = start(true, CsrfBoundary.create().originSource(CsrfBoundary.OriginSource.CONTAINER)
+ .trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ // Recorded Jetty behavior: with a list, the customizer takes the leftmost (client-writable) entry.
+ assertEquals("https|left.example|443", seen(a, "X-Forwarded-Host", "left.example, app.example", "X-Forwarded-Proto", "https, https"));
+ var write = post(a, "/write", "{}", forwarded(PUBLIC, "left.example, app.example", "https, https"));
+ assertEquals(403, write.statusCode(), write::body);
+ assertEquals("FORWARDED_CONTAINER_MISMATCH", write.headers().firstValue(RequestBoundaryFilter.REJECTION_HEADER).orElse(null));
+ assertEquals(0, WriteServlet.WRITES.get());
+ }
+
+ /** Lock for the unverified point: the handshake header map keeps repeated lines in wire order, so the rightmost wins. */
+ @Test void b09_handshakeKeepsRepeatedForwardedLinesInWireOrder() throws Exception {
+ var a = start(false, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ var path = wsPath(session(a, "Origin", PUBLIC, "X-Forwarded-Host", "evil.example", "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "http", "X-Forwarded-Proto", "https"));
+ assertTrue(connects(a, path, "Origin", PUBLIC, "X-Forwarded-Host", "evil.example", "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "http", "X-Forwarded-Proto", "https"));
+ // The same lines the other way round name evil.example as the rightmost entry: the Origin no longer matches.
+ assertFalse(connects(a, path, "Origin", PUBLIC, "X-Forwarded-Host", "app.example", "X-Forwarded-Host", "evil.example",
+ "X-Forwarded-Proto", "https", "X-Forwarded-Proto", "http"));
+ }
+
+ @Test void b08_handshakeUnderHostHeaderWithCustomizerRewritesAgree() throws Exception {
+ var a = start(true, CsrfBoundary.create().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ var write = post(a, "/write", "{}", forwarded(PUBLIC, "app.example", "https"));
+ assertEquals(200, write.statusCode(), write::body);
+ var path = wsPath(session(a, forwarded(PUBLIC, "app.example", "https")));
+ assertTrue(connects(a, path, forwarded(PUBLIC, "app.example", "https")));
+ }
+}
diff --git a/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundary_JettyIT.java b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundary_JettyIT.java
index fbddd91190..554e34e26e 100644
--- a/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundary_JettyIT.java
+++ b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/CsrfBoundary_JettyIT.java
@@ -325,6 +325,23 @@ class CsrfBoundary_JettyIT extends TestBase {
assertEquals(1, a.record().writes.get());
}
+ /**
+ * Lock for J0802: with the container's {@link ForwardedRequestCustomizer} and the default {@code HOST_HEADER}, the
+ * customizer, not the boundary, decides. A forwarded host makes the request's own origin, and the boundary reads no
+ * forwarded header itself.
+ */
+ @Test void a08_forwardedHostTrustedByCustomizerUnderHostHeader() throws Exception {
+ var a = start(true, perProcess(), "/*", REQUEST);
+ var tok = token(a);
+ var ok = send(a, "POST", "/write", "X-Forwarded-Host", "evil.example", "X-Forwarded-Proto", "http",
+ "Origin", "http://evil.example", "Content-Type", JSON, LoopbackBoundary.DEFAULT_CSRF_HEADER, tok);
+ assertEquals(200, ok.statusCode(), ok::body);
+ var plain = send(a, "POST", "/write", "Origin", "http://evil.example", "Content-Type", JSON,
+ LoopbackBoundary.DEFAULT_CSRF_HEADER, tok);
+ assertEquals(403, plain.statusCode(), plain::body);
+ assertEquals("ORIGIN_MISMATCH", rejection(plain));
+ }
+
@Test void a03_http2AuthorityStandsInForHost() throws Exception {
var a = start(false, true, perProcess(), "/*", REQUEST);
var tok = token(a);
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport.java
index 02a5cd2527..e1654fb452 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport.java
@@ -24,6 +24,7 @@ import java.util.concurrent.*;
import org.apache.http.*;
import org.apache.http.client.config.*;
import org.apache.http.client.methods.*;
+import org.apache.http.client.protocol.*;
import org.apache.http.config.*;
import org.apache.http.conn.socket.*;
import org.apache.http.conn.ssl.*;
@@ -72,23 +73,18 @@ public final class ApacheHc45Transport implements HttpTransport {
// One further pinned client (own connection pool) per distinct non-empty per-client allow-list, created on first use,
// so a connection opened under one allow-list can never be handed to a request with another.
private final Map<RemoteUrlPolicy.AllowedRanges,CloseableHttpClient> rangedPinnedHttpClients = new ConcurrentHashMap<>();
- private final boolean guardPerRequest;
ApacheHc45Transport(ApacheHc45TransportBuilder builder) {
if (builder.httpClient != null) {
- // A caller-supplied client cannot be given pin-on-connect, so supportsUrlPolicy() reports false for it. It is
- // immutable once built, so the redirect credential guard cannot be added to it as an interceptor; each request
- // is sent with a guarding context instead (see Hc45RedirectCredentialGuard.newGuardingContext()).
+ // A caller-supplied client cannot be given pin-on-connect, so supportsUrlPolicy() reports false for it.
this.httpClient = builder.httpClient;
this.pinnedHttpClient = null;
this.cookieStore = null;
- this.guardPerRequest = true;
} else {
// Two clients, one per connection pool, sharing a cookie store so that cookies behave as on one client.
this.cookieStore = new BasicCookieStore();
this.httpClient = createDefaultHttpClient(cookieStore);
this.pinnedHttpClient = createPinnedHttpClient(cookieStore, PolicyPinningDnsResolver.INSTANCE);
- this.guardPerRequest = false;
}
}
@@ -96,10 +92,22 @@ public final class ApacheHc45Transport implements HttpTransport {
private static CloseableHttpClient createDefaultHttpClient(BasicCookieStore cookieStore) {
return HttpClients.custom()
.setDefaultCookieStore(cookieStore)
- .addInterceptorLast(new Hc45RedirectCredentialGuard())
+ .setRedirectStrategy(new UserInfoRefusingRedirectStrategy())
.build();
}
+ // A redirect Location with user info would make HttpClient replace the client's stored credentials for the target's scope
+ // with the user info's, so it is refused (the policy path refuses it too, in PolicyEnforcedRedirects).
+ private static final class UserInfoRefusingRedirectStrategy extends DefaultRedirectStrategy {
+ @Override /* DefaultRedirectStrategy */
+ public URI getLocationURI(HttpRequest request, HttpResponse response, org.apache.http.protocol.HttpContext context) throws org.apache.http.ProtocolException {
+ var uri = super.getLocationURI(request, response, context);
+ if (uri.getRawUserInfo() != null)
+ throw new org.apache.http.ProtocolException("Redirect Location carries user info, which is refused: " + uri.getHost());
+ return uri;
+ }
+ }
+
// The client for SSRF-guard-active @Remote requests. Its connection manager is its own and resolves every host
// through PolicyPinningDnsResolver, so every connection in its pool was opened through the pin; a guarded request
// can never be handed an idle connection that an unguarded request opened. Redirect handling is disabled so that
@@ -112,7 +120,6 @@ public final class ApacheHc45Transport implements HttpTransport {
return HttpClients.custom()
.setConnectionManager(new PoolingHttpClientConnectionManager(registry, resolver))
.setDefaultCookieStore(cookieStore)
- .addInterceptorLast(new Hc45RedirectCredentialGuard())
.disableRedirectHandling()
.build();
}
@@ -140,14 +147,14 @@ public final class ApacheHc45Transport implements HttpTransport {
if (request.isSsrfGuardActive())
return executeWithPolicy(request);
try {
- return sendOnce(request, httpClient, guardPerRequest);
+ return sendOnce(request, httpClient, Hc45RedirectCredentialGuard.newGuardingContext());
} catch (StaleConnectionException e) {
// A pooled keep-alive connection was torn down by the server before any response was received.
// Replay once on a fresh connection, but only when it is provably safe (idempotent + repeatable body).
if (! request.isSafeToReplay())
throw e.asTransportException();
try {
- return sendOnce(request, httpClient, guardPerRequest);
+ return sendOnce(request, httpClient, Hc45RedirectCredentialGuard.newGuardingContext());
} catch (StaleConnectionException e2) {
throw e2.asTransportException();
}
@@ -161,16 +168,18 @@ public final class ApacheHc45Transport implements HttpTransport {
// Juneau-controlled redirect revalidation for a guarded request; every hop goes through sendOncePinned.
private TransportResponse executeWithPolicy(TransportRequest request) throws TransportException {
- return PolicyEnforcedRedirects.execute(request, this::sendOncePinned);
+ // One guarding context for the whole chain: each hop is a separate execute, and the guard must remember the first origin.
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ return PolicyEnforcedRedirects.execute(request, hop -> sendOncePinned(hop, context));
}
// Performs one pin-on-connect hop on the pinned client. A caller-supplied client has no pinned client, so its hops
// are sent unpinned on that client; RestRequest never routes a guarded request there (supportsUrlPolicy() is false).
// PolicyPinningDnsResolver refuses a host whose every address is denied with an IllegalArgumentException, which
// HttpClient propagates unchanged; it is reported as the documented TransportException.
- private TransportResponse sendOncePinned(TransportRequest request) throws TransportException {
+ private TransportResponse sendOncePinned(TransportRequest request, HttpClientContext context) throws TransportException {
try {
- return sendOnce(request, pinnedClientFor(request), guardPerRequest);
+ return sendOnce(request, pinnedClientFor(request), context);
} catch (StaleConnectionException e) {
throw e.asTransportException();
} catch (IllegalArgumentException e) {
@@ -190,13 +199,14 @@ public final class ApacheHc45Transport implements HttpTransport {
}
// Performs a single HTTP exchange. Throws StaleConnectionException (a retryable signal) when the failure is a
- // pre-response stale-connection failure; throws TransportException for every other failure. guarded sends the request
- // with a context that applies the redirect credential guard, for a client that does not carry it as an interceptor.
- private static TransportResponse sendOnce(TransportRequest request, CloseableHttpClient client, boolean guarded) throws TransportException, StaleConnectionException {
+ // pre-response stale-connection failure; throws TransportException for every other failure. Every request is sent with a
+ // context that applies the redirect credential guard, so transport-built and caller-supplied clients behave the same. A legacy AbstractHttpClient is refused by the builder because
+ // it never sets the request again before it is written, so the wire-stage strip could not run for it.
+ private static TransportResponse sendOnce(TransportRequest request, CloseableHttpClient client, HttpClientContext context) throws TransportException, StaleConnectionException {
var hcRequest = buildHcRequest(request, client);
CloseableHttpResponse hcResponse;
try {
- hcResponse = client.execute(hcRequest, guarded ? Hc45RedirectCredentialGuard.newGuardingContext() : null);
+ hcResponse = client.execute(hcRequest, context);
} catch (IOException e) {
// httpClient.execute() only returns once response headers have been read, so any IOException here
// occurred before any response bytes were received.
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45TransportBuilder.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45TransportBuilder.java
index 9d2756f9fb..ba2abf20ac 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45TransportBuilder.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45TransportBuilder.java
@@ -62,11 +62,19 @@ public final class ApacheHc45TransportBuilder {
* <p>
* The transport takes ownership of the client and will close it when {@link ApacheHc45Transport#close()} is called.
*
+ * <p>
+ * A legacy {@link AbstractHttpClient} subclass (such as {@code DefaultHttpClient}) is refused: it never sets the request
+ * again just before it is written, so the redirect credential guard cannot strip the credentials HttpClient adds itself
+ * (for example the cookie-store {@code Cookie}) on a cross-origin redirect. Build the client with {@code HttpClients}.
+ *
* @param value The client to use. Must not be <jk>null</jk>.
* @return This object.
+ * @throws IllegalArgumentException If the client is an {@link AbstractHttpClient}.
*/
public ApacheHc45TransportBuilder httpClient(CloseableHttpClient value) {
- httpClient = reqnn("value", value);
+ if (reqnn("value", value) instanceof AbstractHttpClient)
+ throw iaex("A legacy AbstractHttpClient (%s) is not supported: it cannot apply the redirect credential guard. Build the client with HttpClients instead.", value.getClass().getName());
+ httpClient = value;
return this;
}
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard.java
index 197c1508b0..60fc392e5e 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/main/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard.java
@@ -26,7 +26,7 @@ import org.apache.http.protocol.*;
import org.apache.juneau.rest.client.*;
/**
- * Request interceptor that removes caller-set credential headers before a request is replayed against a
+ * Request interceptor that removes credential headers before a request is replayed against a
* different origin as the result of a {@code 3xx} redirect.
*
* <p>
@@ -34,10 +34,9 @@ import org.apache.juneau.rest.client.*;
* {@code Authorization} and {@code Cookie} — onto the follow-up request aimed at the {@code Location}
* target. When that target is a different scheme, host, or port (or an {@code https}→{@code http}
* downgrade), forwarding those headers would disclose credentials to an unrelated origin. This interceptor
- * runs on every outgoing request in an exchange: it records the origin of the first request and, on any
- * later request in the same exchange whose origin differs (and on every request after one that did, even if it
- * returns to the first origin), strips the credential headers before the request
- * leaves the client.
+ * runs on every outgoing request in an exchange: it records the origin of the first request and strips the
+ * credential headers from any later request in the same exchange whose origin differs from it. A request that
+ * returns to the first origin is not stripped, so it carries the original origin's credentials again.
*
* <p>
* The origin is compared on HttpClient's own {@link HttpHost} (scheme, host and effective port), with the same
@@ -48,12 +47,15 @@ import org.apache.juneau.rest.client.*;
* so that all transports share it.
*
* <p>
- * A caller-supplied client is immutable once built, so this interceptor cannot be added to it. For such a client the
- * transport passes {@code newGuardingContext()} with each request instead; see {@code GuardingContext}.
+ * This interceptor is not registered on any client. The transport passes {@code newGuardingContext()} with every
+ * request instead, so that transport-built and caller-supplied clients behave identically; see {@code GuardingContext}.
+ * On a hop whose origin is not the first one every credential header is removed, including the cookie-store {@code Cookie} and the
+ * credentials-provider or preemptive {@code Authorization} that HttpClient adds after this interceptor runs.
*/
final class Hc45RedirectCredentialGuard implements HttpRequestInterceptor {
private static final String ATTR_ORIGIN = Hc45RedirectCredentialGuard.class.getName() + ".origin";
+ private static final String ATTR_LEFT = Hc45RedirectCredentialGuard.class.getName() + ".left";
private static final String ATTR_STRIPPED = Hc45RedirectCredentialGuard.class.getName() + ".stripped";
@Override /* HttpRequestInterceptor */
@@ -66,10 +68,18 @@ final class Hc45RedirectCredentialGuard implements HttpRequestInterceptor {
context.setAttribute(ATTR_ORIGIN, target);
return;
}
- // Sticky: HttpClient copies each hop's headers from the caller's original request, so once any hop left the first origin,
- // every later hop (including one that returns to it) must be stripped too.
- if (context.getAttribute(ATTR_STRIPPED) == null && sameOrigin(origin, target))
- return;
+ // Always compared with the first origin, not the previous hop. HttpClient copies each hop's headers from the caller's
+ // original request (this only strips the hop's own copy), so a hop that returns to the first origin is left whole.
+ // A hop that returns to the first origin gets the credentials back only if it is a GET or HEAD: a 307/308 replay of a
+ // POST (or any other method) after leaving the origin would be a credentialed write the caller never asked A to see.
+ if (sameOrigin(origin, target)) {
+ if (context.getAttribute(ATTR_LEFT) == null || safeMethod(request)) {
+ context.removeAttribute(ATTR_STRIPPED);
+ return;
+ }
+ } else {
+ context.setAttribute(ATTR_LEFT, Boolean.TRUE);
+ }
context.setAttribute(ATTR_STRIPPED, Boolean.TRUE);
for (var name : RedirectSecurity.stripOnCrossOrigin())
request.removeHeaders(name);
@@ -85,28 +95,43 @@ final class Hc45RedirectCredentialGuard implements HttpRequestInterceptor {
}
/**
- * Per-request context that applies the guard to a caller-supplied client without changing that client.
+ * Per-request context that applies the guard without changing the client it is used with.
*
* <p>
- * HttpClient's protocol stage records each pass over a hop in the context (its target host, then the request) before it
- * runs the client's own request interceptors, so this context strips the credential headers at that point. The
- * headers on a redirect hop at that point are the ones the redirect executor copied from the original request, which
- * are the caller's. The client's interceptors and authenticator run afterwards, so a {@code Cookie} from the client's
- * {@code CookieStore} and an {@code Authorization} from its {@code CredentialsProvider} are still sent to the new
- * origin.
+ * The transport sends every request with one of these, whether it built the client or the caller supplied it, so both
+ * behave identically. On a hop that is not at the exchange's first origin (exact scheme, host and effective port), <em>every</em>
+ * credential header is removed from the request that goes out, including the ones HttpClient adds itself: a {@code Cookie} from the client's
+ * {@code CookieStore}, and an {@code Authorization} from its {@code CredentialsProvider}, its auth cache (preemptive
+ * auth) or the answer to a {@code 401} challenge. The only exception is {@code Proxy-Authorization}, which is addressed
+ * to the proxy rather than the origin. Headers the client adds that are not credentials, such as
+ * {@code setDefaultHeaders(...)}, are left alone.
+ *
+ * <p>
+ * A request passes through two points that matter, both visible as attributes set on the context. HttpClient's protocol
+ * stage sets the target host and then the request just before it runs the client's own request interceptors; the guard
+ * strips the headers the redirect executor copied from the caller's original request there. The {@code MainClientExec}
+ * then adds its authentication headers, and the connection sets the request one last time immediately before it is
+ * written to the wire; the guard strips again there, if the hop is not at the first origin.
+ *
+ * <p>
+ * The first origin is the one captured at the start of the exchange; each hop is compared with it, never with the previous
+ * hop. A redirect chain that returns to the first origin (A→B→A, A→B→C→A) gets the original origin's credentials back
+ * on that hop, exactly as an unredirected request to it would: the caller's own headers (HttpClient rebuilds each hop from
+ * the original request), the cookie-store {@code Cookie} and the credentials-provider or preemptive {@code Authorization}.
+ * A returning hop gets them back only when its method is {@code GET} or {@code HEAD}: once the exchange has left the first origin, a hop back to it by any other method (a {@code 307}/{@code 308} replay of a {@code POST}) stays stripped; a hop that never left the origin is unaffected. Every hop that is not at the first origin is stripped, so A→B→A→B strips the second B. The comparison is exact
+ * and fails closed: a different port, an {@code http}/{@code https} change, or a different spelling of the host (an
+ * IP literal versus its name, a trailing dot, a punycode name) is a different origin.
*
* <p>
* A hop can be passed more than once: HttpClient's retry executors ({@code RetryExec} after an I/O failure,
* {@code ServiceUnavailableRetryExec} after a 503) restore the headers they captured <em>before</em> the protocol stage
* ran -- the caller's -- and run the protocol stage again on the same request object. So the guard must run on every
- * pass, not once per request object. A pass is recognised by the protocol stage setting the target host immediately
- * before the request; the {@code MainClientExec} sets the request again just before sending (and for each auth
- * challenge round), after the client's interceptors added their headers, and that one must not be stripped. A
- * {@code CONNECT} tunnel request carries no caller headers.
+ * pass, not once per request object. A protocol-stage pass is recognised by the stage setting the target host
+ * immediately before the request. A client that wraps the context it is given in a child context bypasses this guard, and so does a legacy {@code AbstractHttpClient} subclass ({@code DefaultHttpClient}), which never sets the request again before it is written; the builder refuses such a client. Proxy-Authorization is not removed at the wire stage unless the route is tunnelled (inside a tunnel the proxy never sees the request, so one would reach the origin).
*
* <p>
- * Headers the caller's client adds itself, such as {@code setDefaultHeaders(...)}, are client configuration rather than
- * caller-set request headers and are deliberately left alone, like the cookie store and credentials provider.
+ * On a {@code 307}/{@code 308} redirect of a non-{@code GET} request, HttpClient copies the previous hop's headers (as sent) rather than the
+ * original request's, so caller-set headers are not brought back on a return to the first origin; credentials HttpClient adds itself still are. The {@code Host} header also carries over from the previous hop. A {@code CONNECT} tunnel request is never stripped: it carries no caller headers.
*/
private static final class GuardingContext extends HttpClientContext {
@@ -118,21 +143,41 @@ final class Hc45RedirectCredentialGuard implements HttpRequestInterceptor {
super.setAttribute(id, obj);
if (HttpCoreContext.HTTP_TARGET_HOST.equals(id))
protocolPass = true;
- else if (HttpCoreContext.HTTP_REQUEST.equals(id) && protocolPass && obj instanceof HttpRequest request) {
- protocolPass = false;
- guard.process(request, this);
+ else if (HttpCoreContext.HTTP_REQUEST.equals(id) && obj instanceof HttpRequest request) {
+ if (protocolPass) {
+ protocolPass = false;
+ guard.process(request, this);
+ } else if (getAttribute(ATTR_STRIPPED) != null && ! "CONNECT".equalsIgnoreCase(request.getRequestLine().getMethod())) {
+ // Proxy-Authorization is addressed to the proxy, except inside a tunnel, where the proxy never sees this request.
+ var route = getHttpRoute();
+ var keepProxyAuth = route == null || ! route.isTunnelled();
+ for (var name : RedirectSecurity.stripOnCrossOrigin())
+ if (! (keepProxyAuth && "proxy-authorization".equalsIgnoreCase(name)))
+ request.removeHeaders(name);
+ }
}
}
}
+ private static boolean safeMethod(HttpRequest request) {
+ var method = request.getRequestLine().getMethod();
+ return "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method);
+ }
+
// HttpHost always has a scheme name and a host name; the port is -1 when none was given, so it is normalized to the
// scheme default. An https->http downgrade changes the scheme, so it is never same-origin.
private static boolean sameOrigin(HttpHost from, HttpHost to) {
- return eqic(from.getSchemeName(), to.getSchemeName())
- && eqic(from.getHostName(), to.getHostName())
+ return lower(from.getSchemeName()).equals(lower(to.getSchemeName()))
+ && lower(from.getHostName()).equals(lower(to.getHostName()))
&& effectivePort(from) == effectivePort(to);
}
+ // Locale.ROOT lower-casing, not equalsIgnoreCase: that folds U+0131 (dotless i), U+0130 and U+017F onto ASCII letters, so a
+ // non-ASCII host would otherwise compare equal to an ASCII one.
+ private static String lower(String s) {
+ return s.toLowerCase(Locale.ROOT);
+ }
+
private static int effectivePort(HttpHost host) {
var port = host.getPort();
if (port != -1)
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRedirectCredentials_Test.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRedirectCredentials_Test.java
index f4bfcc3ec7..c13a6939f8 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRedirectCredentials_Test.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRedirectCredentials_Test.java
@@ -24,7 +24,9 @@ import java.nio.charset.*;
import java.util.*;
import java.util.concurrent.atomic.*;
+import org.apache.http.*;
import org.apache.http.auth.*;
+import org.apache.http.client.*;
import org.apache.http.impl.client.*;
import org.apache.juneau.rest.client.apachehttpclient45.*;
import org.junit.jupiter.api.*;
@@ -46,9 +48,12 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
private static HttpServer serverA;
private static HttpServer serverB;
+ private static HttpServer serverC;
private static int portA;
private static int portB;
+ private static int portC;
private static final AtomicReference<String> firstHopAuth = new AtomicReference<>();
+ private static final AtomicReference<String> midHopAuth = new AtomicReference<>();
@BeforeAll
static void startServers() throws IOException {
@@ -58,14 +63,25 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
serverB.createContext("/echo-creds", ApacheHc45Transport_CallerClientRedirectCredentials_Test::echoCreds);
serverB.createContext("/challenge", ApacheHc45Transport_CallerClientRedirectCredentials_Test::challenge);
serverB.createContext("/bounce-to-a", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portA + "/echo-creds", null));
+ serverB.createContext("/bounce-to-a-challenge", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portA + "/challenge", null));
+ serverB.createContext("/to-c", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portC + "/to-a", null));
+ serverB.createContext("/to-a-then-b", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portA + "/to-b", null));
serverB.start();
+ serverC = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ portC = serverC.getAddress().getPort();
+ serverC.createContext("/to-a", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portA + "/echo-creds", null));
+ serverC.start();
+
serverA = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
portA = serverA.getAddress().getPort();
serverA.createContext("/echo-creds", ApacheHc45Transport_CallerClientRedirectCredentials_Test::echoCreds);
serverA.createContext("/redirect-cross", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/echo-creds", null));
serverA.createContext("/redirect-same", exchange -> redirect(exchange, 302, "/echo-creds", null));
serverA.createContext("/redirect-cross-set-cookie", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/echo-creds", "store=s-1; Path=/"));
+ serverA.createContext("/challenge", ApacheHc45Transport_CallerClientRedirectCredentials_Test::challenge);
+ serverA.createContext("/redirect-same-set-cookie", exchange -> redirect(exchange, 302, "/echo-creds", "store=s-1; Path=/"));
+ serverA.createContext("/redirect-same-challenge", exchange -> redirect(exchange, 302, "/challenge", null));
serverA.createContext("/redirect-cross-307", exchange -> redirect(exchange, 307, "http://127.0.0.1:" + portB + "/echo-creds", null));
serverA.createContext("/redirect-same-307", exchange -> redirect(exchange, 307, "/echo-creds", null));
serverA.createContext("/redirect-cross-challenge", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/challenge", null));
@@ -73,6 +89,15 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
firstHopAuth.set(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization")));
redirect(exchange, 302, "http://127.0.0.1:" + portB + "/bounce-to-a", null);
});
+ serverA.createContext("/redirect-a-b-a-set-cookie", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/bounce-to-a", "store=s-1; Path=/"));
+ serverA.createContext("/redirect-a-b-a-challenge", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/bounce-to-a-challenge", null));
+ serverA.createContext("/redirect-userinfo", exchange -> redirect(exchange, 302, "http://bob:pw@127.0.0.1:" + portA + "/echo-creds", null));
+ serverA.createContext("/redirect-a-b-c-a", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/to-c", null));
+ serverA.createContext("/redirect-a-b-a-b", exchange -> redirect(exchange, 302, "http://127.0.0.1:" + portB + "/to-a-then-b", null));
+ serverA.createContext("/to-b", exchange -> {
+ midHopAuth.set(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization")));
+ redirect(exchange, 302, "http://127.0.0.1:" + portB + "/echo-creds", null);
+ });
serverA.start();
}
@@ -82,6 +107,8 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
serverA.stop(0);
if (serverB != null)
serverB.stop(0);
+ if (serverC != null)
+ serverC.stop(0);
}
private static String all(HttpExchange exchange, String name) {
@@ -121,7 +148,10 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
}
private static String get(CloseableHttpClient callerClient, String path) throws Exception {
- var transport = ApacheHc45Transport.builder().httpClient(callerClient).build();
+ return get(ApacheHc45Transport.builder().httpClient(callerClient).build(), path);
+ }
+
+ private static String get(ApacheHc45Transport transport, String path) throws Exception {
try (var client = RestClient.builder().transport(transport).rootUrl("http://127.0.0.1:" + portA).build();
var response = client.get(path)
.header("Authorization", "Bearer secret-token")
@@ -145,21 +175,19 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
}
@Test
- void a03_crossOrigin_callerClient_cookieStoreStillApplies() throws Exception {
- // The cookie A sets on its redirect lives in the caller's cookie store; a cookie's domain ignores the port, so the
- // store sends it on to B. Only the caller-set Cookie value is stripped.
- var cookieStore = new BasicCookieStore();
- var callerClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
- assertEquals("auth=none|cookie=store=s-1|key=none|trace=t-1", get(callerClient, "/redirect-cross-set-cookie"));
+ void a03_crossOrigin_callerClient_cookieStoreCookieStripped() throws Exception {
+ // J0824: the cookie A sets lives in the caller's cookie store, which would send it on to B (a cookie's domain ignores
+ // the port). The guard strips every credential header on a cross-origin hop, so the store's Cookie goes too.
+ var callerClient = HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).build();
+ assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(callerClient, "/redirect-cross-set-cookie"));
}
@Test
- void a04_crossOrigin_callerClient_credentialsProviderStillAnswersChallenge() throws Exception {
- var credentials = new BasicCredentialsProvider();
- credentials.setCredentials(new AuthScope("127.0.0.1", portB), new UsernamePasswordCredentials("bob", "pw"));
- var callerClient = HttpClients.custom().setDefaultCredentialsProvider(credentials).build();
- var expected = "Basic " + Base64.getEncoder().encodeToString("bob:pw".getBytes(StandardCharsets.UTF_8));
- assertEquals("auth=" + expected + "|cookie=none|key=none|trace=t-1", get(callerClient, "/redirect-cross-challenge"));
+ void a04_crossOrigin_callerClient_credentialsProviderAuthorizationStripped() throws Exception {
+ // J0824: the credentials provider would answer B's challenge. The answer is an Authorization header, so it is stripped;
+ // B keeps challenging and the caller sees the 401.
+ var callerClient = HttpClients.custom().setDefaultCredentialsProvider(provider(portB)).build();
+ assertEquals("401:challenge", getAnyStatus(callerClient, "/redirect-cross-challenge"));
}
@Test
@@ -173,9 +201,134 @@ class ApacheHc45Transport_CallerClientRedirectCredentials_Test {
}
@Test
- void a07_originBackToFirstOrigin_callerClient_credentialsStayStripped() throws Exception {
+ void a07_originBackToFirstOrigin_callerClient_credentialsRestored() throws Exception {
+ // J0824 follow-up: the hop that returns to the first origin gets the caller's own headers back.
firstHopAuth.set(null);
- assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(HttpClients.createDefault(), "/redirect-a-b-a"));
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123|key=k-1|trace=t-1", get(HttpClients.createDefault(), "/redirect-a-b-a"));
assertEquals("Bearer secret-token", firstHopAuth.get());
}
+
+ private static CredentialsProvider provider(int port) {
+ var credentials = new BasicCredentialsProvider();
+ credentials.setCredentials(new AuthScope("127.0.0.1", port), new UsernamePasswordCredentials("bob", "pw"));
+ return credentials;
+ }
+
+ private static String getAnyStatus(CloseableHttpClient callerClient, String path) throws Exception {
+ var transport = ApacheHc45Transport.builder().httpClient(callerClient).build();
+ try (var client = RestClient.builder().transport(transport).rootUrl("http://127.0.0.1:" + portA).build();
+ var response = client.get(path).header("Authorization", "Bearer secret-token").run()) {
+ return response.getStatusCode() + ":" + response.getBodyAsString();
+ }
+ }
+
+ private static CloseableHttpClient preemptive() {
+ return HttpClients.custom().addInterceptorLast((HttpRequestInterceptor)(request, context) -> request.setHeader("Authorization", "Basic cHJlZW1wdA==")).build();
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // J0824 matrix: caller header, cookie store, credentials provider and preemptive auth, each cross-origin (stripped)
+ // and same-origin (kept), on both caller-supplied and transport-built clients.
+ //------------------------------------------------------------------------------------------------------------------
+
+ @Test
+ void b01_callerClient_sameOrigin_cookieStoreCookieKept() throws Exception {
+ var callerClient = HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).build();
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123,store=s-1|key=k-1|trace=t-1", get(callerClient, "/redirect-same-set-cookie"));
+ }
+
+ @Test
+ void b02_callerClient_sameOrigin_credentialsProviderAnswersChallenge() throws Exception {
+ var callerClient = HttpClients.custom().setDefaultCredentialsProvider(provider(portA)).build();
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123|key=k-1|trace=t-1", get(callerClient, "/redirect-same-challenge"));
+ }
+
+ @Test
+ void b03_callerClient_crossOrigin_preemptiveAuthorizationStripped() throws Exception {
+ assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(preemptive(), "/redirect-cross"));
+ }
+
+ @Test
+ void b04_callerClient_sameOrigin_preemptiveAuthorizationKept() throws Exception {
+ // The preemptive interceptor overwrites the caller's header on every request, including the redirect hop.
+ assertEquals("auth=Basic cHJlZW1wdA==|cookie=session=abc123|key=k-1|trace=t-1", get(preemptive(), "/redirect-same"));
+ }
+
+ @Test
+ void b05_callerClient_crossOrigin_credentialsProviderStrippedEvenWithoutCallerHeaders() throws Exception {
+ var callerClient = HttpClients.custom().setDefaultCredentialsProvider(provider(portB)).build();
+ var transport = ApacheHc45Transport.builder().httpClient(callerClient).build();
+ try (var client = RestClient.builder().transport(transport).rootUrl("http://127.0.0.1:" + portA).build();
+ var response = client.get("/redirect-cross-challenge").run()) {
+ assertEquals(401, response.getStatusCode());
+ }
+ }
+
+ @Test
+ void c01_transportBuilt_crossOrigin_stripsHeaderAndCookieStore() throws Exception {
+ assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(ApacheHc45Transport.create(), "/redirect-cross"));
+ assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(ApacheHc45Transport.create(), "/redirect-cross-set-cookie"));
+ }
+
+ @Test
+ void c02_transportBuilt_sameOrigin_keepsHeadersAndCookieStore() throws Exception {
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123|key=k-1|trace=t-1", get(ApacheHc45Transport.create(), "/redirect-same"));
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123,store=s-1|key=k-1|trace=t-1", get(ApacheHc45Transport.create(), "/redirect-same-set-cookie"));
+ }
+
+ @Test
+ void d01_callerClient_aToBToA_cookieStoreCookieRestoredOnReturn() throws Exception {
+ // The final hop back to A is an ordinary request to A: caller headers and the store cookie are back.
+ var callerClient = HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).build();
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123,store=s-1|key=k-1|trace=t-1", get(callerClient, "/redirect-a-b-a-set-cookie"));
+ }
+
+ @Test
+ void d02_callerClient_aToBToA_credentialsProviderAuthorizationRestoredOnReturn() throws Exception {
+ // No caller Authorization: A's challenge on the return hop is answered by the credentials provider again.
+ var callerClient = HttpClients.custom().setDefaultCredentialsProvider(provider(portA)).build();
+ var transport = ApacheHc45Transport.builder().httpClient(callerClient).build();
+ try (var client = RestClient.builder().transport(transport).rootUrl("http://127.0.0.1:" + portA).build();
+ var response = client.get("/redirect-a-b-a-challenge").run()) {
+ assertEquals(200, response.getStatusCode());
+ assertEquals("auth=Basic Ym9iOnB3|cookie=none|key=none|trace=none", response.getBodyAsString());
+ }
+ }
+
+ @Test
+ void d03_callerClient_aToBToCToA_restoredOnFinalHop() throws Exception {
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123|key=k-1|trace=t-1", get(HttpClients.createDefault(), "/redirect-a-b-c-a"));
+ }
+
+ @Test
+ void d04_callerClient_aToBToAToB_secondBStripped() throws Exception {
+ midHopAuth.set(null);
+ assertEquals("auth=none|cookie=none|key=none|trace=t-1", get(HttpClients.createDefault(), "/redirect-a-b-a-b"));
+ assertEquals("Bearer secret-token", midHopAuth.get(), "the hop back at A carried the credentials");
+ }
+
+ @Test
+ void d05_transportBuilt_aToBToA_restoredOnReturn() throws Exception {
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123|key=k-1|trace=t-1", get(ApacheHc45Transport.create(), "/redirect-a-b-a"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation") // The legacy AbstractHttpClient family is exactly what is refused.
+ void e01_legacyDefaultHttpClient_isRefused() {
+ // Reproduced before the refusal: a legacy client never re-sets the request before the wire, so the store cookie followed a cross-origin redirect.
+ var ex = assertThrows(IllegalArgumentException.class, () -> ApacheHc45Transport.builder().httpClient(new org.apache.http.impl.client.DefaultHttpClient()));
+ assertTrue(ex.getMessage().contains("AbstractHttpClient"), ex.getMessage());
+ }
+
+ @Test
+ void e02_transportBuilt_redirectLocationWithUserInfo_isRefused() throws Exception {
+ var transport = ApacheHc45Transport.create();
+ try (var client = RestClient.builder().transport(transport).rootUrl("http://127.0.0.1:" + portA).build()) {
+ var ex = assertThrows(Exception.class, () -> client.get("/redirect-userinfo").run());
+ var found = false;
+ for (Throwable t = ex; t != null; t = t.getCause())
+ found |= String.valueOf(t.getMessage()).contains("user info");
+ assertTrue(found, ex.toString());
+ }
+ }
}
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRetryCredentials_Test.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRetryCredentials_Test.java
index 6f7b573018..6bffc0d9cf 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRetryCredentials_Test.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_CallerClientRetryCredentials_Test.java
@@ -135,7 +135,7 @@ class ApacheHc45Transport_CallerClientRetryCredentials_Test {
}
@Test
- void a02_originBackToFirstOrigin_retriedAfterDroppedConnection_credentialsStayStripped() throws Exception {
+ void a02_originBackToFirstOrigin_retriedAfterDroppedConnection_credentialsRestoredOnEveryAttempt() throws Exception {
var drops = new ConcurrentLinkedQueue<>(List.of("drop"));
var portA = new int[1];
var portB = new int[1];
@@ -144,9 +144,10 @@ class ApacheHc45Transport_CallerClientRetryCredentials_Test {
portB[0] = b.port();
portA[0] = a.port();
run(a.port(), "/start");
- // A saw: /start (caller's credentials), then /echo twice (dropped, then retried) -- both stripped.
+ // A saw: /start, then /echo twice (dropped, then retried). The hop back at the first origin gets the caller's credentials
+ // back, and the retry must restore them again rather than lose them.
assertEquals(List.of("/start", "/echo", "/echo"), a.log);
- assertEquals(List.of(ALL, STRIPPED, STRIPPED), a.headersSeen);
+ assertEquals(List.of(ALL, ALL, ALL), a.headersSeen);
assertEquals(List.of(STRIPPED), b.headersSeen);
}
}
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_RedirectCredentials_Test.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_RedirectCredentials_Test.java
index 3f638b24b5..926045e383 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_RedirectCredentials_Test.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/ApacheHc45Transport_RedirectCredentials_Test.java
@@ -127,7 +127,7 @@ class ApacheHc45Transport_RedirectCredentials_Test {
}
@Test
- void a03_originBackToFirstOrigin_credentialsStayStripped() throws Exception {
+ void a03_originBackToFirstOrigin_credentialsRestored() throws Exception {
firstHopAuth.set(null);
firstHopCookie.set(null);
firstHopKey.set(null);
@@ -143,8 +143,8 @@ class ApacheHc45Transport_RedirectCredentials_Test {
assertEquals("Bearer secret-token", firstHopAuth.get());
assertEquals("session=abc123", firstHopCookie.get());
assertEquals("k-1", firstHopKey.get());
- assertEquals("auth=none|cookie=none", response.getBodyAsString());
- assertEquals("null", lastKey.get());
+ assertEquals("auth=Bearer secret-token|cookie=session=abc123", response.getBodyAsString());
+ assertEquals("k-1", lastKey.get());
}
}
}
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport_Policy_Test.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport_Policy_Test.java
index 6d9ec650fa..5e0fe74d40 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport_Policy_Test.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/ApacheHc45Transport_Policy_Test.java
@@ -118,6 +118,92 @@ class ApacheHc45Transport_Policy_Test {
assertEquals(List.of("http://192.0.2.1/x", "http://192.0.2.2/next"), uris);
}
+ @Test
+ void a03b_guardedRequest_allHopsShareOneGuardingContext() throws Exception {
+ // J0824: Juneau follows these redirects itself, one execute per hop. The credential guard remembers the first origin in
+ // the context, so every hop must be sent with the same one or a cookie-store Cookie would follow the redirect.
+ var contexts = new ArrayList<HttpContext>();
+ var httpClient = new FakeHttpClient(req -> null) {
+ @Override protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) {
+ contexts.add(context);
+ if (contexts.size() == 1) {
+ var redirect = new FakeResponse(302);
+ redirect.addHeader("Location", "http://192.0.2.2/next");
+ return redirect;
+ }
+ return new FakeResponse(200);
+ }
+ };
+ try (var transport = ApacheHc45Transport.builder().httpClient(httpClient).build()) {
+ try (var resp = transport.execute(guarded("http://192.0.2.1/x"))) {
+ assertEquals(200, resp.getStatusCode());
+ }
+ }
+ assertEquals(2, contexts.size());
+ assertSame(contexts.get(0), contexts.get(1));
+ }
+
+ // J0824: the guarded path must not forward a cookie-store Cookie across origins. Loopback cannot be re-permitted for a guarded
+ // request, so the wire is simulated: for each hop the fake drives the context exactly as HttpClient does (protocol stage,
+ // the client's own interceptors adding a store Cookie, then the wire-send stage) and records the Cookie that would be sent.
+ private static List<String> guardedCookies(String firstUri, String... locations) throws Exception {
+ var sent = new ArrayList<String>();
+ var hops = new int[1];
+ var httpClient = new FakeHttpClient(req -> null) {
+ @Override protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) {
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ request.setHeader("Cookie", "store=s-1");
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ var cookie = request.getFirstHeader("Cookie");
+ sent.add(cookie == null ? "none" : cookie.getValue());
+ if (hops[0] < locations.length) {
+ var redirect = new FakeResponse(302);
+ redirect.addHeader("Location", locations[hops[0]++]);
+ return redirect;
+ }
+ return new FakeResponse(200);
+ }
+ };
+ try (var transport = ApacheHc45Transport.builder().httpClient(httpClient).build()) {
+ try (var resp = transport.execute(guarded(firstUri))) {
+ assertEquals(200, resp.getStatusCode());
+ }
+ }
+ return sent;
+ }
+
+ @Test
+ void a03c_guardedRequest_crossOriginHop_storeCookieNotSent() throws Exception {
+ assertEquals(List.of("store=s-1", "none"), guardedCookies("http://192.0.2.1:8080/x", "http://192.0.2.1:9090/next"));
+ }
+
+ @Test
+ void a03d_guardedRequest_sameOriginHop_storeCookieSent() throws Exception {
+ assertEquals(List.of("store=s-1", "store=s-1"), guardedCookies("http://192.0.2.1/x", "/next"));
+ }
+
+ @Test
+ void a03e_guardedRequest_httpsToHttpSameHost_storeCookieNotSent() throws Exception {
+ assertEquals(List.of("store=s-1", "none"), guardedCookies("https://192.0.2.1/x", "http://192.0.2.1/next"));
+ }
+
+ @Test
+ void a03f_guardedRequest_aToBToA_storeCookieRestoredOnReturn() throws Exception {
+ assertEquals(List.of("store=s-1", "none", "store=s-1"), guardedCookies("http://192.0.2.1/x", "http://192.0.2.2/b", "http://192.0.2.1/back"));
+ }
+
+ @Test
+ void a03g_guardedRequest_aToBToAToB_secondBStripped() throws Exception {
+ assertEquals(List.of("store=s-1", "none", "store=s-1", "none"), guardedCookies("http://192.0.2.1/x", "http://192.0.2.2/b", "http://192.0.2.1/back", "http://192.0.2.2/again"));
+ }
+
+ @Test
+ void a03h_guardedRequest_returnToSameHostOtherPortOrScheme_staysStripped() throws Exception {
+ assertEquals(List.of("store=s-1", "none", "none"), guardedCookies("http://192.0.2.1/x", "http://192.0.2.2/b", "http://192.0.2.1:8080/back"));
+ assertEquals(List.of("store=s-1", "none", "none"), guardedCookies("https://192.0.2.1/x", "https://192.0.2.2/b", "http://192.0.2.1/back"));
+ }
+
@Test
void a04_guardedRequest_redirectToLoopbackIsRejected() throws Exception {
var httpClient = new FakeHttpClient(req -> {
diff --git a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard_Test.java b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard_Test.java
index 610576ac8a..36f7017522 100644
--- a/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard_Test.java
+++ b/juneau-rest/juneau-rest-client-apache-httpclient-45/src/test/java/org/apache/juneau/rest/client/apachehttpclient45/Hc45RedirectCredentialGuard_Test.java
@@ -19,6 +19,7 @@ package org.apache.juneau.rest.client.apachehttpclient45;
import static org.junit.jupiter.api.Assertions.*;
import org.apache.http.*;
+import org.apache.http.client.protocol.*;
import org.apache.http.message.*;
import org.apache.http.protocol.*;
import org.junit.jupiter.api.*;
@@ -114,4 +115,169 @@ class Hc45RedirectCredentialGuard_Test {
guard.process(request, context);
return request;
}
+
+ @Test
+ void f01_guardingContext_httpsToHttpSameHost_wireStageStripsStoreCookie() {
+ // https -> http on the same host is a downgrade, hence a different origin. Drive the context the way HttpClient does.
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, new HttpHost("example.com", 443, "https"), new BasicHttpRequest("GET", "/"), false);
+ var downgraded = new BasicHttpRequest("GET", "/");
+ hopStages(context, new HttpHost("example.com", 80, "http"), downgraded, true);
+ assertNull(downgraded.getFirstHeader("Cookie"));
+ assertNull(downgraded.getFirstHeader("Authorization"));
+ }
+
+ // Protocol stage (target host, request), then the client's own interceptors add a store cookie and auth, then the wire stage.
+ private static void hopStages(HttpClientContext context, HttpHost target, HttpRequest request, boolean expectStripped) {
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ request.addHeader("Cookie", "store=s-1");
+ request.addHeader("Authorization", "Basic x");
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ if (! expectStripped) {
+ assertNotNull(request.getFirstHeader("Cookie"));
+ assertNotNull(request.getFirstHeader("Authorization"));
+ }
+ }
+
+ @Test
+ void g01_aToBToA_wireStageRestoresOnReturn() {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ var a = new HttpHost("example.com", 443, "https");
+ var b = new HttpHost("other.example.com", 443, "https");
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ var viaB = new BasicHttpRequest("GET", "/");
+ hopStages(context, b, viaB, true);
+ assertNull(viaB.getFirstHeader("Cookie"));
+ assertNull(viaB.getFirstHeader("Authorization"));
+ var back = new BasicHttpRequest("GET", "/");
+ hopStages(context, new HttpHost("EXAMPLE.com", -1, "HTTPS"), back, false);
+ assertNotNull(back.getFirstHeader("Cookie"));
+ assertNotNull(back.getFirstHeader("Authorization"));
+ }
+
+ @Test
+ void g02_aToBToAToB_secondBStripped() {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ var a = new HttpHost("a.example.com", 80, "http");
+ var b = new HttpHost("b.example.com", 80, "http");
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ hopStages(context, b, new BasicHttpRequest("GET", "/"), true);
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ var secondB = new BasicHttpRequest("GET", "/");
+ hopStages(context, b, secondB, true);
+ assertNull(secondB.getFirstHeader("Cookie"));
+ assertNull(secondB.getFirstHeader("Authorization"));
+ }
+
+ @Test
+ void g03_aToBToCToA_restoredOnFinalHop() {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ var a = new HttpHost("a.example.com", 80, "http");
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ hopStages(context, new HttpHost("b.example.com", 80, "http"), new BasicHttpRequest("GET", "/"), true);
+ hopStages(context, new HttpHost("c.example.com", 80, "http"), new BasicHttpRequest("GET", "/"), true);
+ var back = new BasicHttpRequest("GET", "/");
+ hopStages(context, a, back, false);
+ assertNotNull(back.getFirstHeader("Cookie"));
+ }
+
+ @Test
+ void g04_returnToLookAlikeOrigin_staysStripped() {
+ // Canonical-origin equality: only scheme (case-insensitive), host (case-insensitive) and effective port may match.
+ var first = new HttpHost("a.example.com", -1, "https");
+ var lookAlikes = new HttpHost[]{
+ new HttpHost("a.example.com", 8443, "https"), // different port
+ new HttpHost("a.example.com", 80, "http"), // downgrade
+ new HttpHost("a.example.com", 443, "http"), // scheme differs, same port
+ new HttpHost("a.example.com.", 443, "https"), // trailing dot
+ new HttpHost("192.0.2.1", 443, "https"), // IP versus name
+ new HttpHost("xn--a-example.com", 443, "https"), // punycode spelling
+ new HttpHost("a.example.com.evil.test", 443, "https"),
+ new HttpHost("evil.test", 443, "https")
+ };
+ for (var target : lookAlikes) {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, first, new BasicHttpRequest("GET", "/"), false);
+ var request = new BasicHttpRequest("GET", "/");
+ hopStages(context, new HttpHost("b.example.com", 443, "https"), new BasicHttpRequest("GET", "/"), true);
+ hopStages(context, target, request, true);
+ assertNull(request.getFirstHeader("Cookie"), target.toString());
+ assertNull(request.getFirstHeader("Authorization"), target.toString());
+ }
+ }
+
+ @Test
+ void g05_sameOrigin_everyHopKept() {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ var a = new HttpHost("a.example.com", 80, "http");
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ hopStages(context, new HttpHost("A.example.com", -1, "http"), new BasicHttpRequest("GET", "/"), false);
+ }
+
+ @Test
+ void g06_nonAsciiLookAlikeHost_isNotSameOrigin() {
+ // equalsIgnoreCase would fold U+0131 (dotless i) and U+017F onto "i" and "s"; the host must be compared as lower-cased ASCII.
+ for (var lookAlike : new String[]{"log\u0131n.sample.com", "login.sample.com".replace("s", "\u017F"), "LOG\u0130N.sample.com"}) {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, new HttpHost(lookAlike.replace("\u017F", "s").replace("\u0131", "i").replace("\u0130", "I"), 443, "https"), new BasicHttpRequest("GET", "/"), false);
+ var request = new BasicHttpRequest("GET", "/");
+ hopStages(context, new HttpHost(lookAlike, 443, "https"), request, true);
+ assertNull(request.getFirstHeader("Cookie"), lookAlike);
+ assertNull(request.getFirstHeader("Authorization"), lookAlike);
+ }
+ }
+
+ @Test
+ void h01_returnToFirstOrigin_onlyGetAndHeadRestored() {
+ var a = new HttpHost("a.example.com", 80, "http");
+ var b = new HttpHost("b.example.com", 80, "http");
+ for (var method : new String[]{"GET", "HEAD", "get"}) {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, a, new BasicHttpRequest("POST", "/"), false);
+ hopStages(context, b, new BasicHttpRequest("POST", "/"), true);
+ var back = new BasicHttpRequest(method, "/");
+ hopStages(context, a, back, false);
+ assertNotNull(back.getFirstHeader("Cookie"), method);
+ }
+ for (var method : new String[]{"POST", "PUT", "DELETE", "PATCH"}) {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, a, new BasicHttpRequest(method, "/"), false);
+ hopStages(context, b, new BasicHttpRequest(method, "/"), true);
+ var back = new BasicHttpRequest(method, "/");
+ hopStages(context, a, back, true);
+ assertNull(back.getFirstHeader("Cookie"), method);
+ assertNull(back.getFirstHeader("Authorization"), method);
+ }
+ }
+
+ @Test
+ void h02_sameOriginPost_neverLeft_keepsCredentials() {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ var a = new HttpHost("a.example.com", 80, "http");
+ hopStages(context, a, new BasicHttpRequest("POST", "/"), false);
+ hopStages(context, a, new BasicHttpRequest("POST", "/"), false);
+ }
+
+ @Test
+ void h03_proxyAuthorization_exemptUnlessRouteTunnelled() {
+ var a = new HttpHost("a.example.com", 443, "https");
+ var proxy = new HttpHost("proxy.example.com", 3128, "http");
+ for (var tunnelled : new boolean[]{false, true}) {
+ var context = Hc45RedirectCredentialGuard.newGuardingContext();
+ hopStages(context, a, new BasicHttpRequest("GET", "/"), false);
+ var b = new HttpHost("b.example.com", 443, "https");
+ context.setAttribute(HttpClientContext.HTTP_ROUTE, new org.apache.http.conn.routing.HttpRoute(b, null, new HttpHost[]{proxy}, true, tunnelled ? org.apache.http.conn.routing.RouteInfo.TunnelType.TUNNELLED : org.apache.http.conn.routing.RouteInfo.TunnelType.PLAIN, org.apache.http.conn.routing.RouteInfo.LayerType.PLAIN));
+ var request = new BasicHttpRequest("GET", "/");
+ request.addHeader("Proxy-Authorization", "Basic cHJveHk=");
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, b);
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ request.addHeader("Proxy-Authorization", "Basic cHJveHk=");
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
+ if (tunnelled)
+ assertNull(request.getFirstHeader("Proxy-Authorization"));
+ else
+ assertNotNull(request.getFirstHeader("Proxy-Authorization"));
+ }
+ }
}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects.java
index 1bcaa34c32..83269204c8 100644
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects.java
+++ b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects.java
@@ -45,9 +45,10 @@ import org.apache.juneau.http.remote.*;
*
* <p>
* Caller-set credential headers ({@link RedirectSecurity#stripOnCrossOrigin()}, matched case-insensitively) are
- * carried to the next hop only when it is the same origin as the current hop and not an {@code https} →
- * {@code http} downgrade (see {@link RedirectSecurity#shouldStripCredentials(URI, URI)}); otherwise they are dropped
- * and stay dropped for the rest of the chain.
+ * carried to a hop only when it is the same origin as the <em>first</em> request in the chain and not an {@code https}
+ * → {@code http} downgrade (see {@link RedirectSecurity#shouldStripCredentials(URI, URI)}); otherwise they are
+ * dropped for that hop. A hop that returns to the first origin gets them back, but only when its method is {@code GET} or {@code HEAD}
+ * (a {@code 307}/{@code 308} replay of a {@code POST} after leaving the first origin stays stripped).
*
* @since 10.0.0
*/
@@ -94,6 +95,7 @@ public final class PolicyEnforcedRedirects {
var allowPrivateUrls = initial.isAllowPrivateUrls();
var allowedRanges = initial.getAllowedAddressRanges();
var current = initial;
+ var left = new boolean[1];
for (var hop = 0; hop < RemoteUrlPolicy.MAX_REDIRECT_HOPS; hop++) {
// Hop 0's URI was already validated (or is the operator-configured client root, which the calling engine
// intentionally does not re-check -- see RemoteUrlPolicy.requireAllowedUrl) before this TransportRequest
@@ -105,7 +107,7 @@ public final class PolicyEnforcedRedirects {
return response;
var location = requireLocation(response);
closeQuietly(response);
- current = nextHop(current, location, response.getStatusCode());
+ current = nextHop(initial, current, location, response.getStatusCode(), left);
}
throw new TransportException("Redirect limit exceeded (" + RemoteUrlPolicy.MAX_REDIRECT_HOPS
+ " hops) while following a policy-covered @Remote redirect chain, starting at: " + initial.getUri());
@@ -113,9 +115,15 @@ public final class PolicyEnforcedRedirects {
// An invalid Location, or a target whose origin cannot be compared (java.net.URI parses some host names, such as an
// underscore name, with a null host), is a failed hop like any other, so it is reported as TransportException.
- private static TransportRequest nextHop(TransportRequest current, String location, int statusCode) throws TransportException {
+ private static TransportRequest nextHop(TransportRequest initial, TransportRequest current, String location, int statusCode, boolean[] left) throws TransportException {
try {
- return forRedirect(current, RemoteUrlPolicy.resolveRedirectLocation(current.getUri(), location), statusCode);
+ var target = RemoteUrlPolicy.resolveRedirectLocation(current.getUri(), location);
+ if (target.getRawUserInfo() != null)
+ throw new TransportException("Redirect Location carries user info, which is refused (it could replace the client's stored credentials): " + location);
+ // Remember that the chain has left the first origin; a later return to it restores credentials only for GET/HEAD.
+ var wasLeft = left[0];
+ left[0] |= RedirectSecurity.shouldStripCredentials(initial.getUri(), current.getUri());
+ return forRedirect(initial, current, target, statusCode, wasLeft || left[0]);
} catch (IllegalArgumentException e) {
throw new TransportException(e.getMessage(), e);
}
@@ -148,7 +156,11 @@ public final class PolicyEnforcedRedirects {
}
}
- private static TransportRequest forRedirect(TransportRequest current, URI target, int statusCode) throws TransportException {
+ private static boolean safeMethod(String method) {
+ return eqic(method, "GET") || eqic(method, "HEAD");
+ }
+
+ private static TransportRequest forRedirect(TransportRequest initial, TransportRequest current, URI target, int statusCode, boolean left) throws TransportException {
var preserveMethod = eqic(current.getMethod(), "GET") || eqic(current.getMethod(), "HEAD");
var rewriteToGet = ! preserveMethod && (statusCode == 301 || statusCode == 302 || statusCode == 303);
@@ -160,9 +172,11 @@ public final class PolicyEnforcedRedirects {
.remoteUrlPolicy(true, false)
.allowedAddressRanges(current.getAllowedAddressRanges())
.timeout(current.getTimeout());
- // Credential headers are forwarded only to the same origin (and never across an https -> http downgrade).
- var stripCredentials = RedirectSecurity.shouldStripCredentials(current.getUri(), target);
- for (var h : current.getHeaders())
+ // Credential headers are forwarded only to the first origin (and never across an https -> http downgrade), so a hop
+ // that returns to it gets the caller's headers back. They are taken from the initial request, not the previous hop's.
+ var stripCredentials = RedirectSecurity.shouldStripCredentials(initial.getUri(), target)
+ || (left && ! safeMethod(rewriteToGet ? "GET" : current.getMethod()));
+ for (var h : initial.getHeaders())
if (! (stripCredentials && RedactedHeaders.isSensitive(h.name(), RedirectSecurity.stripOnCrossOrigin())))
builder.header(h.name(), h.value());
if (! rewriteToGet) {
diff --git a/juneau-rest/juneau-rest-client/src/test/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects_Test.java b/juneau-rest/juneau-rest-client/src/test/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects_Test.java
index ff30183d25..654b952d9d 100644
--- a/juneau-rest/juneau-rest-client/src/test/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects_Test.java
+++ b/juneau-rest/juneau-rest-client/src/test/java/org/apache/juneau/rest/client/PolicyEnforcedRedirects_Test.java
@@ -42,6 +42,7 @@ class PolicyEnforcedRedirects_Test {
private static final class ScriptedHops implements PolicyEnforcedRedirects.HopExecutor {
final List<TransportRequest> hops = new ArrayList<>();
final Deque<String> locations;
+ int status = 302;
ScriptedHops(String...locations) {
this.locations = new ArrayDeque<>(List.of(locations));
@@ -53,7 +54,7 @@ class PolicyEnforcedRedirects_Test {
var location = locations.poll();
if (location == null)
return TransportResponse.builder().statusCode(200).body(new ByteArrayInputStream(new byte[0])).build();
- return TransportResponse.builder().statusCode(302).header("Location", location).build();
+ return TransportResponse.builder().statusCode(status).header("Location", location).build();
}
TransportRequest last() {
@@ -119,13 +120,80 @@ class PolicyEnforcedRedirects_Test {
assertList(headerNames(hops.last()), "Accept");
}
- @Test void a05_crossOriginThenBackToOrigin_credentialsStayDropped() throws Exception {
- // Once a hop has left the original origin, a later hop back to it does not regain the credentials.
+ @Test void a05_crossOriginThenBackToOrigin_credentialsRestored() throws Exception {
+ // A hop that returns to the first origin gets the caller's credential headers back.
var hops = run(request("http://a.example.com/start"), "http://b.example.com/bounce", "http://a.example.com/echo");
assertList(headerNames(hops.hops.get(1)), "Accept", "X-Trace");
+ assertList(headerNames(hops.last()), "Authorization", "Cookie", "Proxy-Authorization", "X-API-Key", "Accept", "X-Trace");
+ }
+
+ @Test void a05b_aToBToCToA_restoredOnFinalHop() throws Exception {
+ var hops = run(request("http://a.example.com/start"), "http://b.example.com/x", "http://c.example.com/y", "http://a.example.com/echo");
+ assertList(headerNames(hops.hops.get(2)), "Accept", "X-Trace");
+ assertList(headerNames(hops.last()), "Authorization", "Cookie", "Proxy-Authorization", "X-API-Key", "Accept", "X-Trace");
+ }
+
+ @Test void a05c_aToBToAToB_strippedAgainOnSecondB() throws Exception {
+ var hops = run(request("http://a.example.com/start"), "http://b.example.com/x", "http://a.example.com/y", "http://b.example.com/echo");
+ assertList(headerNames(hops.hops.get(2)), "Authorization", "Cookie", "Proxy-Authorization", "X-API-Key", "Accept", "X-Trace");
+ assertList(headerNames(hops.last()), "Accept", "X-Trace");
+ }
+
+ @Test void a05d_returnToSameHostDifferentPortOrScheme_staysStripped() throws Exception {
+ var hops = run(request("http://a.example.com/start"), "http://b.example.com/x", "http://a.example.com:8080/echo");
+ assertList(headerNames(hops.last()), "Accept", "X-Trace");
+ hops = run(request("https://a.example.com/start"), "http://b.example.com/x", "http://a.example.com/echo");
assertList(headerNames(hops.last()), "Accept", "X-Trace");
}
+ @Test void a05e_originEquality_caseAndDefaultPortNormalised_butNotIdnOrIpOrTrailingDot() throws Exception {
+ var hops = run(request("https://a.example.com/start"), "http://b.example.com/x", "https://A.EXAMPLE.com:443/echo");
+ assertList(headerNames(hops.last()), "Authorization", "Cookie", "Proxy-Authorization", "X-API-Key", "Accept", "X-Trace");
+ for (var other : new String[]{"https://a.example.com./echo", "https://192.0.2.9/echo", "https://xn--a-example.com/echo", "https://a.example.com:8443/echo"}) {
+ hops = run(request("https://a.example.com/start"), "http://b.example.com/x", other);
+ assertList(headerNames(hops.last()), "Accept", "X-Trace");
+ }
+ }
+
+ private static TransportRequest requestWithMethod(String method, String uri) {
+ return TransportRequest.builder().method(method).uri(uri).remoteUrlPolicy(true, false)
+ .header("Authorization", "Bearer secret-token").header("Accept", "application/json").build();
+ }
+
+ private static ScriptedHops runWithStatus(TransportRequest initial, int status, String...locations) throws Exception {
+ var hops = new ScriptedHops(locations);
+ hops.status = status;
+ PolicyEnforcedRedirects.execute(initial, hops);
+ return hops;
+ }
+
+ @Test void a05g_returnToFirstOrigin_307Post_staysStripped() throws Exception {
+ var hops = runWithStatus(requestWithMethod("POST", "http://a.example.com/start"), 307, "http://b.example.com/x", "http://a.example.com/echo");
+ assertEquals("POST", hops.last().getMethod());
+ assertList(headerNames(hops.last()), "Accept");
+ }
+
+ @Test void a05h_returnToFirstOrigin_302PostBecomesGet_restored() throws Exception {
+ var hops = runWithStatus(requestWithMethod("POST", "http://a.example.com/start"), 302, "http://b.example.com/x", "http://a.example.com/echo");
+ assertEquals("GET", hops.last().getMethod());
+ assertList(headerNames(hops.last()), "Authorization", "Accept");
+ }
+
+ @Test void a05i_returnToFirstOrigin_headRestored() throws Exception {
+ var hops = runWithStatus(requestWithMethod("HEAD", "http://a.example.com/start"), 307, "http://b.example.com/x", "http://a.example.com/echo");
+ assertList(headerNames(hops.last()), "Authorization", "Accept");
+ }
+
+ @Test void a05j_sameOrigin307Post_neverLeft_keepsCredentials() throws Exception {
+ var hops = runWithStatus(requestWithMethod("POST", "http://a.example.com/start"), 307, "http://a.example.com/next");
+ assertList(headerNames(hops.last()), "Authorization", "Accept");
+ }
+
+ @Test void a05f_locationWithUserInfo_isRefused() throws Exception {
+ var ex = assertThrows(TransportException.class, () -> run(request("http://a.example.com/start"), "http://b.example.com/x", "http://user:pw@a.example.com/echo"));
+ assertTrue(ex.getMessage().contains("user info"), ex.getMessage());
+ }
+
@Test void a06_firstHop_sendsAllHeaders() throws Exception {
var hops = run(request("http://a.example.com/start"), "http://b.example.com/echo");
assertList(headerNames(hops.hops.get(0)), "Authorization", "Cookie", "Proxy-Authorization", "X-API-Key", "Accept", "X-Trace");
diff --git a/juneau-rest/juneau-rest-server-bus-websocket/src/main/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator.java b/juneau-rest/juneau-rest-server-bus-websocket/src/main/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator.java
index df553fad80..b60d2a2fc0 100644
--- a/juneau-rest/juneau-rest-server-bus-websocket/src/main/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator.java
+++ b/juneau-rest/juneau-rest-server-bus-websocket/src/main/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator.java
@@ -35,8 +35,8 @@ import jakarta.websocket.server.*;
* can only see the {@code Origin} value, so it refuses a missing value, {@code null}, and anything that is not a
* well-formed http(s) origin; a well-formed cross-site value passes it and is refused by the next step.
* <li>{@link #modifyHandshake}: under a {@link LoopbackBoundary}, Host against the boundary's authority; under a
- * {@link CsrfBoundary}, {@link CsrfBoundary#checkHandshake} with the scheme of the handshake's request URI and
- * every {@code Host}, {@code Origin} and {@code Sec-Fetch-Site} value. Over HTTP/2 (RFC 8441), where the handshake has
+ * {@link CsrfBoundary}, {@link CsrfBoundary#checkHandshake(String, HandshakeHosts, Map)} with the scheme of the handshake's request URI and
+ * its headers (so {@link CsrfBoundary.Builder#trustedForwarding trusted forwarding}, when set, sees the forwarded headers). Over HTTP/2 (RFC 8441), where the handshake has
* no {@code Host}, {@code Sec-WebSocket-Key} or {@code Upgrade}, the request URI's authority stands in for
* {@code Host} ({@link HandshakeHosts}). Otherwise {@code Sec-Fetch-Site} (when
* present) must be {@code same-origin}. Last, the capability and principal. A failure is recorded in the per-connection
@@ -125,8 +125,7 @@ public final class BusWebSocketConfigurator extends ServerEndpointConfig.Configu
var uri = request.getRequestURI();
if (csrf != null) {
var hosts = HandshakeHosts.of(request.getHeaders(), uri);
- var result = csrf.checkHandshake(uri == null ? null : uri.getScheme(), hosts, headers(request, "Origin"),
- headers(request, "Sec-Fetch-Site"));
+ var result = csrf.checkHandshake(uri == null ? null : uri.getScheme(), hosts, request.getHeaders());
if (! result.isAllowed())
return REFUSED;
} else {
@@ -166,19 +165,6 @@ public final class BusWebSocketConfigurator extends ServerEndpointConfig.Configu
return null;
}
- /** Every value of a handshake header, across all spellings of its name, so that a duplicate can be counted. */
- private static List<String> headers(HandshakeRequest request, String name) {
- var l = new ArrayList<String>();
- var headers = request.getHeaders();
- if (headers != null)
- for (var e : headers.entrySet())
- if (name.equalsIgnoreCase(e.getKey()) && e.getValue() != null)
- for (var v : e.getValue())
- if (v != null)
- l.add(v);
- return l;
- }
-
@Override /* Configurator */
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
if (endpointClass != BusWebSocketEndpoint.class)
diff --git a/juneau-rest/juneau-rest-server-bus-websocket/src/test/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator_Test.java b/juneau-rest/juneau-rest-server-bus-websocket/src/test/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator_Test.java
index 9f3418ee8d..d53b524ba9 100644
--- a/juneau-rest/juneau-rest-server-bus-websocket/src/test/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator_Test.java
+++ b/juneau-rest/juneau-rest-server-bus-websocket/src/test/java/org/apache/juneau/rest/server/bus/websocket/BusWebSocketConfigurator_Test.java
@@ -482,6 +482,61 @@ class BusWebSocketConfigurator_Test extends TestBase {
"Sec-WebSocket-Key", "k"))), "no Host at all");
}
+ /** Opens a websocket session through a POST that carries the forwarded headers the trusting boundary needs. */
+ private String openForwarded(Principal principal) throws Exception {
+ var token = csrf.tokenFor(mock(jakarta.servlet.http.HttpServletRequest.class));
+ return BusFixture.open(C, principal, "websocket", DOWN, UP, "Host", "internal:8080", "Origin", "https://" + APP,
+ "X-Forwarded-Host", APP, "X-Forwarded-Proto", "https", "X-Csrf-Token", token);
+ }
+
+ private BusWebSocketConfigurator withForwarding() {
+ return withCsrf(CsrfBoundary.create().tokens(CsrfTokens.perProcess()).trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED));
+ }
+
+ @Test void h01_offIgnoresForwarded() throws Exception {
+ // e13 again, named for the opt-in: the default boundary never reads the forwarded headers.
+ var c = withCsrf();
+ var id = openCsrf(JB);
+ var r = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://" + APP,
+ "X-Forwarded-Host", APP, "X-Forwarded-Proto", "https");
+ assertEquals(4403, refusalCode(handshake(c, r)));
+ }
+
+ @Test void h02_onAdmitsRewrittenHostSameOrigin() throws Exception {
+ var c = withForwarding();
+ var id = openForwarded(JB);
+ var r = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://" + APP,
+ "X-Forwarded-Host", APP, "X-Forwarded-Proto", "https");
+ assertTrue(allowed(handshake(c, r)));
+ }
+
+ @Test void h03_forwardedHostNotMatchingOriginRefused() throws Exception {
+ var c = withForwarding();
+ var id = openForwarded(JB);
+ var r = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://evil.example",
+ "X-Forwarded-Host", APP, "X-Forwarded-Proto", "https");
+ assertEquals(4403, refusalCode(handshake(c, r)));
+ var noHeaders = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://" + APP);
+ assertEquals(4403, refusalCode(handshake(c, noHeaders)));
+ }
+
+ @Test void h04_twoSpellingsRefused() throws Exception {
+ var c = withForwarding();
+ var id = openForwarded(JB);
+ var r = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://" + APP,
+ "X-Forwarded-Host", APP, "x-forwarded-host", APP, "X-Forwarded-Proto", "https");
+ assertEquals(4403, refusalCode(handshake(c, r)));
+ }
+
+ @Test void h05_usesTheHeaderMapOverload() throws Exception {
+ // The list-based checkHandshake forms always refuse a trusting boundary; the configurator must use the map form.
+ var c = withForwarding();
+ var id = openForwarded(JB);
+ var r = requestAt("ws://internal:8080" + path(id), JB, "Host", "internal:8080", "Origin", "https://" + APP,
+ "X-Forwarded-Host", APP, "X-Forwarded-Proto", "https", "Sec-Fetch-Site", "same-origin");
+ assertTrue(allowed(handshake(c, r)));
+ }
+
@Test void e14_untrustworthyRequestUriFailsClosed() throws Exception {
var c = withCsrf();
var id = openCsrf(JB);
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/BoundaryReason.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/BoundaryReason.java
index 0326e024bd..63b0ab0fb0 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/BoundaryReason.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/BoundaryReason.java
@@ -88,5 +88,32 @@ public enum BoundaryReason {
CSRF_TOKEN_MISSING,
/** A state-changing request's CSRF token was not the expected token. Answered with 403 Forbidden. */
- CSRF_TOKEN_MISMATCH
+ CSRF_TOKEN_MISMATCH,
+
+ /**
+ * {@link CsrfBoundary.Builder#trustedForwarding(CsrfBoundary.ForwardedSource) Trusted forwarding} is on and the
+ * request carried no forwarded host (or, for {@code Forwarded}, no usable element). Answered with 403 Forbidden.
+ */
+ FORWARDED_HOST_MISSING,
+
+ /** Trusted forwarding is on and the request carried a forwarded host but no forwarded proto. Answered with 403 Forbidden. */
+ FORWARDED_PROTO_MISSING,
+
+ /** Trusted forwarding is on and the forwarded host, or the {@code Forwarded} header, was malformed. Answered with 403 Forbidden. */
+ FORWARDED_HOST_MALFORMED,
+
+ /** Trusted forwarding is on and the forwarded proto was not {@code http} or {@code https}. Answered with 403 Forbidden. */
+ FORWARDED_PROTO_MALFORMED,
+
+ /** Trusted forwarding is on and the forwarded header held fewer entries than the trusted hop count. Answered with 403 Forbidden. */
+ FORWARDED_HOPS_INSUFFICIENT,
+
+ /** Trusted forwarding is on and the forwarded host and proto held different numbers of entries. Answered with 403 Forbidden. */
+ FORWARDED_HOPS_MISMATCH,
+
+ /**
+ * Trusted forwarding is on and the container's own view of the request disagrees with the forwarded origin.
+ * Answered with 403 Forbidden.
+ */
+ FORWARDED_CONTAINER_MISMATCH
}
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/CsrfBoundary.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/CsrfBoundary.java
index af25194332..482192b060 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/CsrfBoundary.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/CsrfBoundary.java
@@ -20,6 +20,7 @@ import static org.apache.juneau.commons.utils.Shorts.*;
import java.util.*;
import java.util.concurrent.atomic.*;
+import java.util.function.*;
import java.util.logging.*;
import org.apache.juneau.rest.server.*;
@@ -64,6 +65,13 @@ import jakarta.servlet.http.*;
* <tr><td>Own origin</td><td>Unsafe requests</td>
* <td>{@code Host} (on HTTP/2, {@code :authority}) is absent, repeated, or not a host with an optional port</td>
* <td>{@code HOST_MISSING}, {@code HOST_MALFORMED}</td><td>400</td></tr>
+ * <tr><td>Forwarded origin</td><td>Unsafe requests, and safe ones when {@code allowedHosts} is set, when
+ * {@link Builder#trustedForwarding(ForwardedSource)} is on</td>
+ * <td>The forwarded host or proto is missing, malformed, or has fewer or unequal entries than the trusted hop count;
+ * or the container's view disagrees with it</td>
+ * <td>{@code FORWARDED_HOST_MISSING}, {@code FORWARDED_PROTO_MISSING}, {@code FORWARDED_HOST_MALFORMED},
+ * {@code FORWARDED_PROTO_MALFORMED}, {@code FORWARDED_HOPS_INSUFFICIENT}, {@code FORWARDED_HOPS_MISMATCH},
+ * {@code FORWARDED_CONTAINER_MISMATCH}</td><td>403</td></tr>
* <tr><td>{@code Origin} present</td><td>Unsafe requests</td>
* <td>The literal {@code null}; or repeated, unparseable or not this server's own origin; or
* {@code Sec-Fetch-Site} present and not exactly {@code same-origin}</td>
@@ -105,9 +113,10 @@ import jakarta.servlet.http.*;
* <p>
* By default ({@link OriginSource#HOST_HEADER}) the request's own origin is {@link HttpServletRequest#getScheme()} plus
* the {@code Host} header (on HTTP/2, the {@code :authority}; see below). {@code X-Forwarded-*} and {@code Forwarded}
- * are never read by this class. Behind a proxy that terminates
- * TLS, use {@link OriginSource#CONTAINER} and configure the container's own forwarded-header support; the boundary
- * then takes the origin from {@code getScheme()}, {@code getServerName()} and {@code getServerPort()}.
+ * are never read by this class unless {@link Builder#trustedForwarding(ForwardedSource)} is set (see below). Behind a
+ * proxy that terminates TLS, use {@link OriginSource#CONTAINER} and configure the container's own forwarded-header
+ * support; the boundary then takes the origin from {@code getScheme()}, {@code getServerName()} and
+ * {@code getServerPort()}.
* <p>
* <b>Under {@code CONTAINER} the boundary must run after the container's forwarded-header rewrite.</b> Jetty's
* {@code ForwardedRequestCustomizer}, Tomcat's {@code RemoteIpValve} and Spring Boot's
@@ -117,6 +126,31 @@ import jakarta.servlet.http.*;
* {@code HIGHEST_PRECEDENCE} itself. The boundary cannot see its own order; a misordered deployment shows up as
* scheme-mismatch refusals and the warning described below.
*
+ * <h5 class='section'>Trusting a forwarded origin</h5>
+ * <p>
+ * If your container cannot rewrite the request itself, or does not do so for WebSocket upgrades, use
+ * {@link Builder#trustedForwarding(ForwardedSource)}. The request's own origin is then the forwarded host
+ * <b>and</b> proto of the one header family named ({@code X-Forwarded-Host} plus {@code X-Forwarded-Proto}, or
+ * {@code host=} plus {@code proto=} in one {@code Forwarded} element), on HTTP requests and WebSocket handshakes
+ * alike. The other family and {@code X-Forwarded-Port} are never read; put a non-default port in the host value.
+ * <ul>
+ * <li><b>Turn it on only if every request reaches the server through your proxy, and the proxy removes or appends
+ * after any client-supplied copy.</b> A server clients can reach directly lets them choose the origin, and that
+ * defeats {@link Builder#allowedHosts(String...)} for reads.
+ * <li>Set {@link Builder#trustedHops(int)} to exactly the number of proxies that <i>append</i>. A chain of
+ * overwriting proxies stays at 1. <b>Never set it higher:</b> an overstated count trusts a value the client wrote.
+ * <li>A missing, malformed, short or misaligned value is refused ({@code FORWARDED_*}, 403), never guessed at, and
+ * nothing falls back to {@code Host}. A proxy that sets only {@code X-Forwarded-Proto} is not supported.
+ * <li>{@link Builder#allowedHosts(String...)} is checked against the forwarded host, so list the public names.
+ * <li>Under {@link OriginSource#CONTAINER} the container's rewritten origin, port included, must equal the forwarded
+ * one, or the request is refused ({@code FORWARDED_CONTAINER_MISMATCH}); configure both to read the same header
+ * family and hop. Do not enable this where the container consumes the headers (Spring
+ * {@code forward-headers-strategy=framework}): every request is then refused as missing. Under
+ * {@link OriginSource#HOST_HEADER} and on handshakes, a container host that equals an entry left of the selected
+ * one is refused too, because the container trusted a hop the client could have written.
+ * <li>A handshake is judged only through {@link #checkHandshake(String, HandshakeHosts, Map)}.
+ * </ul>
+ *
* <h5 class='section'>HTTP/2 and {@code :authority}</h5>
* <p>
* An HTTP/2 request has no {@code Host} header; its {@code :authority} pseudo-header plays that part, and servlet
@@ -149,7 +183,9 @@ import jakarta.servlet.http.*;
* <li><b>Authentication, intent, session management.</b> The boundary never changes a session id and never sets
* cookie attributes.
* <li><b>Script running inside the page</b> (XSS, a malicious extension) passes every check.
- * <li><b>HTML form POSTs</b>, {@code Referer} checking, and parsing {@code Forwarded}.
+ * <li><b>HTML form POSTs</b> and {@code Referer} checking.
+ * <li><b>Telling a trustworthy proxy from a client</b> (a peer-address allow-list). See
+ * {@link Builder#trustedForwarding(ForwardedSource)}.
* </ul>
*
* <h5 class='section'>What an application must do</h5>
@@ -218,7 +254,10 @@ public class CsrfBoundary implements RequestBoundary {
*/
public enum OriginSource {
- /** The default. {@link HttpServletRequest#getScheme()} and the {@code Host} header. */
+ /**
+ * The default. {@link HttpServletRequest#getScheme()} and the {@code Host} header, or, when
+ * {@link Builder#trustedForwarding(ForwardedSource)} is set, the forwarded origin in their place.
+ */
HOST_HEADER,
/**
@@ -230,6 +269,22 @@ public class CsrfBoundary implements RequestBoundary {
CONTAINER
}
+ /**
+ * The one header family whose forwarded origin the boundary trusts. See
+ * {@link Builder#trustedForwarding(ForwardedSource)}.
+ */
+ public enum ForwardedSource {
+
+ /** The default. No forwarded header is read on any path. */
+ NONE,
+
+ /** {@code X-Forwarded-Host} and {@code X-Forwarded-Proto}. */
+ X_FORWARDED,
+
+ /** {@code host=} and {@code proto=} of the RFC 7239 {@code Forwarded} header. */
+ FORWARDED
+ }
+
private static final Logger LOG = Logger.getLogger(CsrfBoundary.class.getName());
private static final Set<String> SIMPLE_METHODS = Set.of("GET", "HEAD", "POST");
@@ -251,6 +306,8 @@ public class CsrfBoundary implements RequestBoundary {
private final Set<String> allowedHosts;
private final String csrfHeader;
private final boolean createSessions;
+ private final ForwardedSource trustedForwarding;
+ private final int trustedHops;
/**
* Constructor.
@@ -266,6 +323,8 @@ public class CsrfBoundary implements RequestBoundary {
this.allowedHosts = Set.copyOf(builder.allowedHosts);
this.csrfHeader = builder.csrfHeader;
this.createSessions = builder.createSessions;
+ this.trustedForwarding = builder.trustedForwarding;
+ this.trustedHops = builder.trustedHops;
}
/**
@@ -291,7 +350,18 @@ public class CsrfBoundary implements RequestBoundary {
var method = MethodSafety.effectiveMethod(req.getMethod(), req.getQueryString(), req::getHeader);
var hosts = BoundaryChecks.hostValues(req);
- var self = hosts.size() == 1 ? selfOrigin(req, BoundaryChecks.parseHost(hosts.get(0))) : null;
+ Origin self;
+ if (trustedForwarding == ForwardedSource.NONE) {
+ self = hosts.size() == 1 ? selfOrigin(req, BoundaryChecks.parseHost(hosts.get(0))) : null;
+ } else {
+ // Judged only where the own origin is needed, so a direct health probe still passes.
+ if (MethodSafety.isSafe(method) && allowedHosts.isEmpty())
+ return BoundaryResult.ALLOWED;
+ var forwarded = forwardedSelf(req, method, hosts);
+ if (forwarded.refusal() != null)
+ return forwarded.refusal();
+ self = forwarded.origin();
+ }
// The rebinding control runs on every request: a read is as exfiltratable as a write.
if (! allowedHosts.isEmpty()) {
@@ -389,8 +459,15 @@ public class CsrfBoundary implements RequestBoundary {
* </ol>
*
* <p>
+ * With {@link Builder#trustedForwarding(ForwardedSource)} set, the forwarded origin replaces the {@code Host} and
+ * scheme in the steps above, {@code allowedHosts} is checked against the forwarded host, and a missing or malformed
+ * forwarded header is refused with a {@code FORWARDED_*} reason.
+ *
+ * <p>
* The {@code Host} header (or, over HTTP/2, the request URI's authority) is the handshake's own host under either
- * {@link OriginSource}. {@code X-Forwarded-*} and {@code Forwarded} are never read. Behind a proxy that terminates TLS, the scheme is right only if the
+ * {@link OriginSource}. {@code X-Forwarded-*} and {@code Forwarded} are never read unless {@link Builder#trustedForwarding(ForwardedSource)}
+ * is set, which only {@link #checkHandshake(String, HandshakeHosts, Map)} supports. Behind a proxy that terminates
+ * TLS, the scheme is right only if the
* container's own forwarded-header support rewrites the request URI it hands the WebSocket layer; where it does
* not, a {@code wss} page's handshake is refused rather than admitted on a guess.
*
@@ -425,7 +502,57 @@ public class CsrfBoundary implements RequestBoundary {
reqnn("hosts", hosts);
reqnn("origins", origins);
reqnn("fetchSites", fetchSites);
+ return handshake(scheme, hosts, origins, fetchSites, null);
+ }
+ /**
+ * Applies this boundary to a WebSocket handshake, reading every header it needs from the handshake's header map.
+ *
+ * <p>
+ * As {@link #checkHandshake(String, HandshakeHosts, List, List)}, with {@code Origin} and {@code Sec-Fetch-Site}
+ * taken from {@code headers} (every value, across all spellings of the name). This is the form to use when
+ * {@link Builder#trustedForwarding(ForwardedSource)} is set, because only it can see the forwarded headers; the
+ * other forms always refuse such a handshake with {@code FORWARDED_HOST_MISSING}. A forwarded header the map holds
+ * under more than one spelling is refused, because the order of its values across spellings is unknowable.
+ *
+ * @param scheme The scheme of the handshake's request URI. Can be <jk>null</jk>, which is refused.
+ * @param hosts The handshake's {@code Host} values. Must not be <jk>null</jk>.
+ * @param headers The handshake's headers. Can be <jk>null</jk>, which is empty.
+ * @return {@link BoundaryResult#ALLOWED}, or the first rejection. A rejection message never echoes a value the
+ * handshake presented.
+ */
+ public BoundaryResult checkHandshake(String scheme, HandshakeHosts hosts, Map<String,List<String>> headers) {
+ reqnn("hosts", hosts);
+ Function<String,List<String>> lookup = name -> handshakeHeader(headers, name);
+ return handshake(scheme, hosts, handshakeHeader(headers, "Origin"), handshakeHeader(headers, "Sec-Fetch-Site"), lookup);
+ }
+
+ /**
+ * Every value of a handshake header in wire order, or <jk>null</jk> when the map holds the name under more than one
+ * spelling (the order across spellings is lost). Empty when absent.
+ */
+ private static List<String> handshakeHeader(Map<String,List<String>> headers, String name) {
+ var l = new ArrayList<String>();
+ var spellings = 0;
+ if (headers != null) {
+ for (var e : headers.entrySet()) {
+ if (name.equalsIgnoreCase(e.getKey()) && e.getValue() != null) {
+ spellings++;
+ for (var v : e.getValue())
+ if (v != null)
+ l.add(v);
+ }
+ }
+ }
+ if (spellings > 1) {
+ // Origin and Sec-Fetch-Site are counted, not ordered: they stay a plain list. Forwarded headers are refused.
+ return name.equalsIgnoreCase("Origin") || name.equalsIgnoreCase("Sec-Fetch-Site") ? l : null;
+ }
+ return l;
+ }
+
+ private BoundaryResult handshake(String scheme, HandshakeHosts hosts, List<String> origins, List<String> fetchSites,
+ Function<String,List<String>> forwardedHeaders) {
var values = hosts.values();
var host = values.size() == 1 ? BoundaryChecks.parseHost(values.get(0)) : null;
if (host == null) {
@@ -442,7 +569,21 @@ public class CsrfBoundary implements RequestBoundary {
return refuseHandshake(BoundaryReason.ORIGIN_MISMATCH, 403,
"The WebSocket handshake's own scheme could not be determined, so its 'Origin' cannot be checked.", hosts, origins);
- if (! allowedHosts.isEmpty() && ! allowedHosts.contains(host.host()))
+ var self = new Origin(ownScheme, host.host(), host.port() >= 0 ? host.port() : BoundaryChecks.defaultPort(ownScheme));
+ if (trustedForwarding != ForwardedSource.NONE) {
+ // With no header access (the list-based forms) the forwarded host is missing, never guessed.
+ var resolved = forwardedHeaders == null
+ ? new ForwardedOrigin.Resolved(null, List.of(), false, BoundaryReason.FORWARDED_HOST_MISSING)
+ : ForwardedOrigin.resolve(trustedForwarding, trustedHops, forwardedHeaders);
+ if (resolved.reason() != null)
+ return refuseHandshake(resolved.reason(), 403, forwardedMessage(resolved.reason()), hosts, origins);
+ if (containerDisagrees(self, resolved))
+ return refuseHandshake(BoundaryReason.FORWARDED_CONTAINER_MISMATCH, 403,
+ forwardedMessage(BoundaryReason.FORWARDED_CONTAINER_MISMATCH), hosts, origins);
+ self = resolved.origin();
+ }
+
+ if (! allowedHosts.isEmpty() && ! allowedHosts.contains(self.host()))
return refuseHandshake(BoundaryReason.HOST_NOT_ALLOWED, 421,
"Handshake 'Host' is not a host name this server answers to.", hosts, origins);
@@ -451,7 +592,6 @@ public class CsrfBoundary implements RequestBoundary {
if (origins.size() == 1 && "null".equalsIgnoreCase(origins.get(0)))
return refuseHandshake(BoundaryReason.ORIGIN_NULL, 403,
"A WebSocket handshake must not carry an opaque 'null' value in 'Origin'.", hosts, origins);
- var self = new Origin(ownScheme, host.host(), host.port() >= 0 ? host.port() : BoundaryChecks.defaultPort(ownScheme));
var parsed = origins.size() == 1 ? BoundaryChecks.parseOrigin(origins.get(0)) : null;
if (parsed == null || ! parsed.equals(self)) {
if (parsed != null)
@@ -467,6 +607,67 @@ public class CsrfBoundary implements RequestBoundary {
return BoundaryResult.ALLOWED;
}
+ /**
+ * The lines of a forwarded header; empty when absent; <jk>null</jk> when the container will not enumerate them but
+ * holds a value, because one line would then stand for all and could be the client's.
+ */
+ private static List<String> forwardedLines(HttpServletRequest req, String name) {
+ var e = req.getHeaders(name);
+ if (e == null)
+ return req.getHeader(name) == null ? List.of() : null;
+ var l = new ArrayList<String>();
+ while (e.hasMoreElements())
+ l.add(e.nextElement());
+ return l;
+ }
+
+ /**
+ * Whether a container's view {@code c} of the request is one the forwarded origin must not replace.
+ *
+ * <p>
+ * Used where the container's view is the transport (a handshake, or HTTP under {@code HOST_HEADER}): equal views
+ * agree, and an unequal one is replaced, except when its host is one the forwarded header carries to the left of the
+ * selected entry, or when such an entry did not parse (a container may normalize it into a host of its own), which
+ * means the container may have trusted a hop the client could have written.
+ */
+ private static boolean containerDisagrees(Origin c, ForwardedOrigin.Resolved f) {
+ return ! c.host().equals(f.origin().host()) && (f.leftUnparsed() || f.leftHosts().contains(c.host()));
+ }
+
+ /** The fixed text for a forwarded-host refusal. */
+ private static String forwardedMessage(BoundaryReason reason) {
+ return switch (reason) {
+ case FORWARDED_HOST_MISSING -> "A trusted-forwarding boundary requires the forwarded host header; none was usable.";
+ case FORWARDED_PROTO_MISSING -> "A trusted-forwarding boundary requires the forwarded proto alongside the forwarded host.";
+ case FORWARDED_HOST_MALFORMED -> "The forwarded host header is malformed.";
+ case FORWARDED_PROTO_MALFORMED -> "The forwarded proto must be 'http' or 'https'.";
+ case FORWARDED_HOPS_INSUFFICIENT -> "The forwarded header holds fewer entries than the trusted hop count.";
+ case FORWARDED_HOPS_MISMATCH -> "The forwarded host and proto headers hold different numbers of entries.";
+ case FORWARDED_CONTAINER_MISMATCH -> "The container's view of the request disagrees with the forwarded origin.";
+ default -> throw iaex("Not a forwarded-host reason: {0}", reason);
+ };
+ }
+
+ /** The outcome of {@link #forwardedSelf}: the origin to judge against, or the refusal. */
+ private record Self(Origin origin, BoundaryResult refusal) {}
+
+ /** The own origin of an HTTP request when trusted forwarding is on. */
+ private Self forwardedSelf(HttpServletRequest req, String method, List<String> hosts) {
+ var host = hosts.size() == 1 ? BoundaryChecks.parseHost(hosts.get(0)) : null;
+ if (host == null)
+ return new Self(null, hostFailure(req, method, hosts));
+ var resolved = ForwardedOrigin.resolve(trustedForwarding, trustedHops, name -> forwardedLines(req, name));
+ if (resolved.reason() != null)
+ return new Self(null, refuse(req, method, resolved.reason(), 403, forwardedMessage(resolved.reason())));
+ var c = selfOrigin(req, host);
+ // Under CONTAINER the container is declared a forwarding authority, so its view must be exactly the forwarded one.
+ var disagrees = originSource == OriginSource.CONTAINER ? ! resolved.origin().equals(c) : containerDisagrees(c, resolved);
+ if (disagrees)
+ return new Self(null, refuse(req, method, BoundaryReason.FORWARDED_CONTAINER_MISMATCH, 403,
+ forwardedMessage(BoundaryReason.FORWARDED_CONTAINER_MISMATCH)));
+ return new Self(resolved.origin(), null);
+ }
+
/** Logs a refused handshake and builds its result. {@code message} must be a fixed text, as for {@code refuse}. */
private static BoundaryResult refuseHandshake(BoundaryReason reason, int status, String message, HandshakeHosts hosts, List<String> origins) {
LOG.fine(() -> "CSRF boundary refused a WebSocket handshake: reason=" + reason);
@@ -672,6 +873,20 @@ public class CsrfBoundary implements RequestBoundary {
*/
public OriginSource originSource() { return originSource; }
+ /**
+ * The header family whose forwarded origin is trusted.
+ *
+ * @return The source. Never <jk>null</jk>. {@link ForwardedSource#NONE} when forwarding is not trusted.
+ */
+ public ForwardedSource trustedForwarding() { return trustedForwarding; }
+
+ /**
+ * The number of trusted proxy entries; the one this far from the right of the forwarded header is used.
+ *
+ * @return The hop count, 1 to 16.
+ */
+ public int trustedHops() { return trustedHops; }
+
/**
* Whether every admitted unsafe request must carry a single {@code application/json} content type.
*
@@ -703,7 +918,7 @@ public class CsrfBoundary implements RequestBoundary {
public String toString() {
return "CsrfBoundary(tokens=" + tokens + ", nonBrowser=" + nonBrowser + ", originSource=" + originSource
+ ", requireJson=" + requireJson + ", allowedHosts=" + new TreeSet<>(allowedHosts) + ", csrfHeader=" + csrfHeader
- + ", createSessions=" + createSessions + ")";
+ + ", createSessions=" + createSessions + ", trustedForwarding=" + trustedForwarding + ", trustedHops=" + trustedHops + ")";
}
/**
@@ -718,6 +933,8 @@ public class CsrfBoundary implements RequestBoundary {
Set<String> allowedHosts = Set.of();
String csrfHeader = LoopbackBoundary.DEFAULT_CSRF_HEADER;
boolean createSessions = true;
+ ForwardedSource trustedForwarding = ForwardedSource.NONE;
+ int trustedHops = 1;
/**
* Constructor.
@@ -828,12 +1045,57 @@ public class CsrfBoundary implements RequestBoundary {
return this;
}
+ /**
+ * Trusts the forwarded origin one proxy header family carries, for HTTP requests and WebSocket handshakes alike.
+ *
+ * <p>
+ * With a source other than {@link ForwardedSource#NONE}, the request's own origin is the forwarded host
+ * <b>and</b> proto of that one family, and nothing else: there is no fallback to {@code Host} or
+ * {@code getScheme()}, and {@code X-Forwarded-Port} is never read. A request missing either value, or with a
+ * malformed one, is refused with a {@code FORWARDED_*} reason. See {@link #trustedHops(int)} for how an entry
+ * is selected.
+ *
+ * <p>
+ * <b>Turn this on only if every request reaches the server through a proxy that removes or appends after any
+ * client-supplied copy of the header.</b> A server clients can reach directly lets them choose the origin.
+ *
+ * @param value The source. Must not be <jk>null</jk>. Defaults to {@link ForwardedSource#NONE}.
+ * @return This object.
+ */
+ public Builder trustedForwarding(ForwardedSource value) {
+ trustedForwarding = reqnn("value", value);
+ return this;
+ }
+
+ /**
+ * The number of proxies that <i>append</i> to the forwarded header.
+ *
+ * <p>
+ * The entries of the header are counted in wire order across all its lines and commas, and the {@code n}th from
+ * the right is used; entries to its left are ignored. A chain of proxies that overwrite the header stays at 1.
+ * <b>Never set this above the number of proxies that append:</b> an overstated value selects an entry the client
+ * wrote, and that fails open. An understated value selects an inner hop and only causes refusals.
+ *
+ * @param value The hop count, 1 to 16. Defaults to 1.
+ * @return This object.
+ * @throws IllegalArgumentException If {@code value} is outside 1 to 16.
+ */
+ public Builder trustedHops(int value) {
+ if (value < 1 || value > 16)
+ throw iaex("Argument 'value' must be between 1 and 16.");
+ trustedHops = value;
+ return this;
+ }
+
/**
* Builds the boundary.
*
* @return A new {@link CsrfBoundary}.
+ * @throws IllegalArgumentException If {@link #trustedHops(int)} is not 1 while no forwarded source is trusted.
*/
public CsrfBoundary build() {
+ if (trustedHops != 1 && trustedForwarding == ForwardedSource.NONE)
+ throw iaex("trustedHops requires trustedForwarding.");
return new CsrfBoundary(this);
}
}
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/ForwardedOrigin.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/ForwardedOrigin.java
new file mode 100644
index 0000000000..bfe8f692e1
--- /dev/null
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/filter/ForwardedOrigin.java
@@ -0,0 +1,301 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.juneau.rest.server.filter;
+
+import java.util.*;
+import java.util.function.*;
+
+import org.apache.juneau.rest.server.filter.BoundaryChecks.*;
+import org.apache.juneau.rest.server.filter.CsrfBoundary.*;
+
+/**
+ * Reads the forwarded origin a trusted proxy wrote, for {@link CsrfBoundary#trustedForwarding()}.
+ *
+ * <p>
+ * One header family is read ({@code X-Forwarded-Host} plus {@code X-Forwarded-Proto}, or {@code host=} plus
+ * {@code proto=} of {@code Forwarded}); the other is never looked at. The lines of the family are flattened in wire
+ * order into entries, the {@code n}th entry from the right is selected, and everything to its left is ignored. Every
+ * failure is a refusal: nothing here falls back to another value.
+ */
+final class ForwardedOrigin {
+
+ /**
+ * The outcome of {@link #resolve}.
+ *
+ * @param origin The forwarded origin, or <jk>null</jk> when refused.
+ * @param leftHosts The hosts (lower-cased, no port) of the entries strictly left of the selected one that parse.
+ * @param leftUnparsed Whether an entry strictly left of the selected one carried a host that did not parse. A container
+ * may normalize such an entry into a host of its own, so the cross-check treats it as a possible match.
+ * @param reason Why it was refused, or <jk>null</jk> when {@code origin} is set.
+ */
+ record Resolved(Origin origin, List<String> leftHosts, boolean leftUnparsed, BoundaryReason reason) {}
+
+ private ForwardedOrigin() {}
+
+ /**
+ * Resolves the forwarded origin.
+ *
+ * @param source The family to read. Must not be {@link ForwardedSource#NONE}.
+ * @param hops The number of trusted entries; the {@code hops}th from the right is selected.
+ * @param headers Every value of the named header, in wire order, or <jk>null</jk> when the container cannot say in
+ * what order they arrived (a handshake map that holds the name under more than one spelling). An absent header is
+ * an empty list.
+ * @return The outcome. Never <jk>null</jk>.
+ */
+ static Resolved resolve(ForwardedSource source, int hops, Function<String,List<String>> headers) {
+ return source == ForwardedSource.FORWARDED ? resolveForwarded(hops, headers) : resolveXForwarded(hops, headers);
+ }
+
+ private static Resolved refused(BoundaryReason reason) {
+ return new Resolved(null, List.of(), false, reason);
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // X-Forwarded-Host / X-Forwarded-Proto
+ //-----------------------------------------------------------------------------------------------------------------
+
+ private static Resolved resolveXForwarded(int hops, Function<String,List<String>> headers) {
+ var hostLines = headers.apply("X-Forwarded-Host");
+ var protoLines = headers.apply("X-Forwarded-Proto");
+ if (hostLines == null)
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+ if (protoLines == null)
+ return refused(BoundaryReason.FORWARDED_PROTO_MALFORMED);
+ if (hostLines.isEmpty())
+ return refused(BoundaryReason.FORWARDED_HOST_MISSING);
+ if (protoLines.isEmpty())
+ return refused(BoundaryReason.FORWARDED_PROTO_MISSING);
+
+ var hostEntries = flatten(hostLines);
+ var protoEntries = flatten(protoLines);
+ var k = hostEntries.size();
+ if (k != protoEntries.size())
+ return refused(BoundaryReason.FORWARDED_HOPS_MISMATCH);
+ if (k < hops)
+ return refused(BoundaryReason.FORWARDED_HOPS_INSUFFICIENT);
+
+ var selected = k - hops;
+ Origin result = null;
+ for (var i = selected; i < k; i++) {
+ var host = BoundaryChecks.parseHost(hostEntries.get(i));
+ if (host == null)
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+ var proto = proto(protoEntries.get(i));
+ if (proto == null)
+ return refused(BoundaryReason.FORWARDED_PROTO_MALFORMED);
+ if (i == selected)
+ result = origin(proto, host);
+ }
+
+ var left = new ArrayList<String>();
+ var unparsed = false;
+ for (var i = 0; i < selected; i++) {
+ var host = BoundaryChecks.parseHost(hostEntries.get(i));
+ if (host != null)
+ left.add(host.host());
+ else
+ unparsed = true;
+ }
+ return new Resolved(result, left, unparsed, null);
+ }
+
+ /** The lines split on commas, with SP and HTAB trimmed around each comma, in wire order. Empty entries are kept. */
+ private static List<String> flatten(List<String> lines) {
+ var entries = new ArrayList<String>();
+ for (var line : lines) {
+ var value = line == null ? "" : line;
+ var start = 0;
+ while (true) {
+ var comma = value.indexOf(',', start);
+ entries.add(trimOws(value.substring(start, comma < 0 ? value.length() : comma)));
+ if (comma < 0)
+ break;
+ start = comma + 1;
+ }
+ }
+ return entries;
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Forwarded (RFC 7239)
+ //-----------------------------------------------------------------------------------------------------------------
+
+ /** One element of {@code Forwarded}: its parameters by lower-cased name, or a marker for a repeated name. */
+ private record Element(boolean empty, Map<String,String> params, Set<String> repeated) {}
+
+ private static Resolved resolveForwarded(int hops, Function<String,List<String>> headers) {
+ var lines = headers.apply("Forwarded");
+ if (lines == null)
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+ if (lines.isEmpty())
+ return refused(BoundaryReason.FORWARDED_HOST_MISSING);
+
+ // The whole header must tokenize, each line on its own, so a client's open quote cannot swallow a proxy's comma.
+ var elements = new ArrayList<Element>();
+ for (var line : lines)
+ if (! tokenize(line == null ? "" : line, elements))
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+
+ var k = elements.size();
+ if (k < hops)
+ return refused(BoundaryReason.FORWARDED_HOPS_INSUFFICIENT);
+
+ var selected = k - hops;
+ Origin result = null;
+ for (var i = selected; i < k; i++) {
+ var e = elements.get(i);
+ if (e.empty())
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+ if (e.repeated().contains("host") || e.repeated().contains("proto"))
+ return refused(e.repeated().contains("host") ? BoundaryReason.FORWARDED_HOST_MALFORMED : BoundaryReason.FORWARDED_PROTO_MALFORMED);
+ var hostValue = e.params().get("host");
+ if (hostValue == null)
+ return refused(BoundaryReason.FORWARDED_HOST_MISSING);
+ var protoValue = e.params().get("proto");
+ if (protoValue == null)
+ return refused(BoundaryReason.FORWARDED_PROTO_MISSING);
+ var host = BoundaryChecks.parseHost(hostValue);
+ if (host == null)
+ return refused(BoundaryReason.FORWARDED_HOST_MALFORMED);
+ var proto = proto(protoValue);
+ if (proto == null)
+ return refused(BoundaryReason.FORWARDED_PROTO_MALFORMED);
+ if (i == selected)
+ result = origin(proto, host);
+ }
+
+ var left = new ArrayList<String>();
+ var unparsed = false;
+ for (var i = 0; i < selected; i++) {
+ var value = elements.get(i).params().get("host");
+ if (value == null)
+ continue;
+ var host = BoundaryChecks.parseHost(value);
+ if (host != null)
+ left.add(host.host());
+ else
+ unparsed = true;
+ }
+ return new Resolved(result, left, unparsed, null);
+ }
+
+ /**
+ * Tokenizes one line of {@code Forwarded} into elements, appending to {@code out}.
+ *
+ * <p>
+ * Elements are split at commas outside quoted-strings, parameters at semicolons. A parameter is
+ * <c>token OWS "=" OWS (token / quoted-string)</c>. A backslash, a control character or an unterminated quote
+ * makes the line not tokenize.
+ *
+ * @return <jk>false</jk> if the line does not tokenize.
+ */
+ private static boolean tokenize(String s, List<Element> out) {
+ var n = s.length();
+ var i = 0;
+ while (true) {
+ var params = new LinkedHashMap<String,String>();
+ var repeated = new HashSet<String>();
+ var any = false;
+ while (true) {
+ i = skipOws(s, i);
+ if (i < n && s.charAt(i) != ',' && s.charAt(i) != ';') {
+ var nameStart = i;
+ while (i < n && isTchar(s.charAt(i)))
+ i++;
+ if (i == nameStart)
+ return false;
+ var name = s.substring(nameStart, i).toLowerCase(Locale.ROOT);
+ i = skipOws(s, i);
+ if (i >= n || s.charAt(i) != '=')
+ return false;
+ i = skipOws(s, i + 1);
+ String value;
+ if (i < n && s.charAt(i) == '"') {
+ var close = i + 1;
+ while (close < n && s.charAt(close) != '"') {
+ var c = s.charAt(close);
+ if (c == '\\' || (c < 0x20 && c != '\t') || c == 0x7f)
+ return false;
+ close++;
+ }
+ if (close >= n)
+ return false;
+ value = s.substring(i + 1, close);
+ i = close + 1;
+ } else {
+ var valueStart = i;
+ while (i < n && isTchar(s.charAt(i)))
+ i++;
+ if (i == valueStart)
+ return false;
+ value = s.substring(valueStart, i);
+ }
+ any = true;
+ if (params.putIfAbsent(name, value) != null)
+ repeated.add(name);
+ i = skipOws(s, i);
+ }
+ if (i < n && s.charAt(i) == ';') {
+ i++;
+ continue;
+ }
+ break;
+ }
+ if (i < n && s.charAt(i) != ',')
+ return false;
+ out.add(new Element(! any, params, repeated));
+ if (i >= n)
+ return true;
+ i++;
+ }
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Shared
+ //-----------------------------------------------------------------------------------------------------------------
+
+ /** {@code http} or {@code https} in any ASCII case, lower-cased; <jk>null</jk> for anything else. */
+ private static String proto(String value) {
+ var p = value.toLowerCase(Locale.ROOT);
+ return "http".equals(p) || "https".equals(p) ? p : null;
+ }
+
+ private static Origin origin(String proto, Authority host) {
+ return new Origin(proto, host.host(), host.port() >= 0 ? host.port() : BoundaryChecks.defaultPort(proto));
+ }
+
+ private static String trimOws(String s) {
+ var a = 0;
+ var b = s.length();
+ while (a < b && (s.charAt(a) == ' ' || s.charAt(a) == '\t'))
+ a++;
+ while (b > a && (s.charAt(b - 1) == ' ' || s.charAt(b - 1) == '\t'))
+ b--;
+ return s.substring(a, b);
+ }
+
+ private static int skipOws(String s, int i) {
+ while (i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'))
+ i++;
+ return i;
+ }
+
+ /** RFC 7230 tchar. */
+ private static boolean isTchar(char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || "!#$%&'*+-.^_`|~".indexOf(c) >= 0;
+ }
+}
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryFilter_Test.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryFilter_Test.java
index a5680a9911..a46e3dfa9f 100644
--- a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryFilter_Test.java
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryFilter_Test.java
@@ -282,15 +282,35 @@ class CsrfBoundaryFilter_Test extends TestBase {
case CSRF_TOKEN_MISSING -> new Refusal(b, r("POST", "http", HOST, ORIGIN, "Content-Type", JSON), 403);
case CSRF_TOKEN_MISMATCH -> new Refusal(b, r("POST", "http", HOST, ORIGIN, "Content-Type", JSON)
.h(b.csrfHeader(), "0".repeat(128)), 403);
+ case FORWARDED_HOST_MISSING -> forwarded(x -> x, r("POST", "http", HOST, ORIGIN, "Content-Type", JSON));
+ case FORWARDED_PROTO_MISSING -> forwarded(x -> x,
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "app.example"));
+ case FORWARDED_HOST_MALFORMED -> forwarded(x -> x,
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "a@b").h("X-Forwarded-Proto", "http"));
+ case FORWARDED_PROTO_MALFORMED -> forwarded(x -> x,
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "ws"));
+ case FORWARDED_HOPS_INSUFFICIENT -> forwarded(x -> x.trustedHops(2),
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "http"));
+ case FORWARDED_HOPS_MISMATCH -> forwarded(x -> x,
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "a, b").h("X-Forwarded-Proto", "http"));
+ case FORWARDED_CONTAINER_MISMATCH -> forwarded(x -> x.originSource(OriginSource.CONTAINER),
+ r("POST", "http", HOST, ORIGIN, "Content-Type", JSON).h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https"));
default -> throw new IllegalArgumentException("CsrfBoundary does not emit " + reason);
};
}
+ /** A trusting boundary (after {@code tweak}) and the request it refuses; every forwarded refusal is a 403. */
+ private static Refusal forwarded(java.util.function.UnaryOperator<CsrfBoundary.Builder> tweak, R request) {
+ var builder = boundary().trustedForwarding(CsrfBoundary.ForwardedSource.X_FORWARDED);
+ return new Refusal(tweak.apply(builder).build(), request, 403);
+ }
+
@ParameterizedTest
@EnumSource(value=BoundaryReason.class, names={
"HOST_MISSING", "HOST_MALFORMED", "HOST_NOT_ALLOWED", "ORIGIN_MISSING", "ORIGIN_NULL", "ORIGIN_MISMATCH",
"FETCH_SITE_NOT_SAME_ORIGIN", "SIMPLE_REQUEST_WITHOUT_ORIGIN", "CONTENT_TYPE_NOT_JSON", "CSRF_TOKEN_MISSING",
- "CSRF_TOKEN_MISMATCH"
+ "CSRF_TOKEN_MISMATCH", "FORWARDED_HOST_MISSING", "FORWARDED_PROTO_MISSING", "FORWARDED_HOST_MALFORMED",
+ "FORWARDED_PROTO_MALFORMED", "FORWARDED_HOPS_INSUFFICIENT", "FORWARDED_HOPS_MISMATCH", "FORWARDED_CONTAINER_MISMATCH"
})
void a10_rejectionNoStoreAndNoCacheOnAllReasons(BoundaryReason reason) throws Exception {
var x = refusedFor(reason);
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryForwarded_Test.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryForwarded_Test.java
new file mode 100644
index 0000000000..38a460c6c5
--- /dev/null
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/filter/CsrfBoundaryForwarded_Test.java
@@ -0,0 +1,538 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.juneau.rest.server.filter;
+
+import static org.apache.juneau.rest.server.filter.BoundaryReason.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.rest.server.filter.CsrfBoundary.*;
+import org.apache.juneau.rest.server.filter.CsrfBoundary_Test.R;
+import org.junit.jupiter.api.*;
+import org.junit.jupiter.params.*;
+import org.junit.jupiter.params.provider.*;
+
+/**
+ * Tests for {@link CsrfBoundary.Builder#trustedForwarding(ForwardedSource)} on HTTP requests and WebSocket handshakes.
+ *
+ * <p>
+ * Reasons are asserted by direct calls, because the bus configurator collapses every handshake refusal to 4403.
+ *
+ * @since 10.0.0
+ */
+class CsrfBoundaryForwarded_Test extends TestBase {
+
+ private static final String PUBLIC = "https://app.example";
+
+ private static CsrfBoundary.Builder xf() {
+ return CsrfBoundary.create().trustedForwarding(ForwardedSource.X_FORWARDED);
+ }
+
+ private static CsrfBoundary.Builder fwd() {
+ return CsrfBoundary.create().trustedForwarding(ForwardedSource.FORWARDED);
+ }
+
+ /** A same-origin JSON write as seen by a backend behind a proxy that rewrites {@code Host}. */
+ private static R post(CsrfBoundary b, String origin) {
+ return new R().method("POST").scheme("http").h("Host", "backend:8080").h("Origin", origin)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()));
+ }
+
+ private static R viaXf(CsrfBoundary b, String origin, String host, String proto) {
+ return post(b, origin).h("X-Forwarded-Host", host).h("X-Forwarded-Proto", proto);
+ }
+
+ private static void allowed(CsrfBoundary b, R r) {
+ var x = b.check(r.build());
+ assertTrue(x.isAllowed(), () -> "expected allowed, got: " + x);
+ }
+
+ private static void refused(CsrfBoundary b, R r, BoundaryReason reason) {
+ var x = b.check(r.build());
+ assertFalse(x.isAllowed(), () -> "expected " + reason + ", got allowed");
+ assertEquals(reason, x.reason(), x::toString);
+ assertEquals(reason == HOST_NOT_ALLOWED ? 421 : 403, x.status(), x::toString);
+ }
+
+ private static Map<String,List<String>> map(String...nameValue) {
+ var m = new LinkedHashMap<String,List<String>>();
+ for (var i = 0; i < nameValue.length; i += 2)
+ m.computeIfAbsent(nameValue[i], k -> new ArrayList<>()).add(nameValue[i + 1]);
+ return m;
+ }
+
+ private static BoundaryResult hs(CsrfBoundary b, String scheme, String host, String...headers) {
+ return b.checkHandshake(scheme, new HandshakeHosts(host == null ? List.of() : List.of(host), false), map(headers));
+ }
+
+ private static void hsAllowed(CsrfBoundary b, String scheme, String host, String...headers) {
+ var x = hs(b, scheme, host, headers);
+ assertTrue(x.isAllowed(), () -> "expected allowed, got: " + x);
+ }
+
+ private static void hsRefused(CsrfBoundary b, BoundaryReason reason, String scheme, String host, String...headers) {
+ var x = hs(b, scheme, host, headers);
+ assertFalse(x.isAllowed(), () -> "expected " + reason + ", got allowed");
+ assertEquals(reason, x.reason(), x::toString);
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // HTTP, X-Forwarded-*
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void a01_httpForwardedAdmitted() {
+ var b = xf().build();
+ allowed(b, viaXf(b, PUBLIC, "app.example", "https"));
+ }
+
+ @Test void a02_replaceNotUnion() {
+ var b = xf().build();
+ refused(b, viaXf(b, "http://backend:8080", "app.example", "https"), ORIGIN_MISMATCH);
+ refused(b, viaXf(b, "http://app.example", "app.example", "https"), ORIGIN_MISMATCH);
+ }
+
+ @Test void a03_missing() {
+ var b = xf().build();
+ refused(b, post(b, PUBLIC), FORWARDED_HOST_MISSING);
+ refused(b, post(b, PUBLIC).h("X-Forwarded-Proto", "https"), FORWARDED_HOST_MISSING);
+ refused(b, post(b, PUBLIC).h("X-Forwarded-Host", "app.example"), FORWARDED_PROTO_MISSING);
+ refused(b, viaXf(b, PUBLIC, "", "https"), FORWARDED_HOST_MALFORMED);
+ refused(b, viaXf(b, PUBLIC, "app.example", ""), FORWARDED_PROTO_MALFORMED);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "app.example,", "u@app.example", "https://app.example", "app.example/x", "app.example\\x", "app.example?x", "app.example#x",
+ "app.example:0", "app.example:08080", "app.example:+80", "app.example:80a", "app.example:", "app.example:65536",
+ "::1", "[fe80::1%25eth0]", "[::1", "b\u00fccher.example", "app example", "app.example\t x", "[v1.x]"
+ })
+ void a04_malformedHost(String host) {
+ var b = xf().build();
+ refused(b, viaXf(b, PUBLIC, host, host.endsWith(",") ? "https," : "https"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "ws", "wss", "ftp", "\"https\"", "HTTP/1.1", "https x" })
+ void a05_malformedProto(String proto) {
+ var b = xf().build();
+ refused(b, viaXf(b, PUBLIC, "app.example", proto), FORWARDED_PROTO_MALFORMED);
+ }
+
+ @Test void a06_acceptedShapes() {
+ var b = xf().build();
+ allowed(b, viaXf(b, PUBLIC, "APP.Example", "HTTPS"));
+ allowed(b, viaXf(b, "https://[::1]:8443", "[::1]:8443", "https"));
+ allowed(b, viaXf(b, "https://app.example.", "app.example.", "https"));
+ refused(b, viaXf(b, PUBLIC, "app.example.", "https"), ORIGIN_MISMATCH);
+ allowed(b, viaXf(b, "https://xn--bcher-kva.example", "xn--bcher-kva.example", "https"));
+ }
+
+ @Test void a07_hops() {
+ var b = xf().build();
+ // Default n=1 takes the rightmost entry; the client's prefix is ignored.
+ allowed(b, viaXf(b, PUBLIC, "evil.example, app.example", "http, https"));
+ allowed(b, post(b, PUBLIC).h("X-Forwarded-Host", "evil.example").h("X-Forwarded-Host", "app.example")
+ .h("X-Forwarded-Proto", "http, https"));
+ // Alignment: proto is taken at the same index as host.
+ allowed(b, viaXf(b, "https://b", "a, b", "http, https"));
+ refused(b, viaXf(b, PUBLIC, "a, app.example", "https"), FORWARDED_HOPS_MISMATCH);
+
+ var two = xf().trustedHops(2).build();
+ allowed(two, viaXf(two, PUBLIC, "app.example, internal", "https, http"));
+ refused(two, viaXf(two, PUBLIC, "app.example", "https"), FORWARDED_HOPS_INSUFFICIENT);
+ // An overstated n selects the client's entry: the documented fail-open.
+ allowed(two, viaXf(two, "http://evil.example", "evil.example, app.example", "http, https"));
+ // The counted entries are all validated.
+ refused(two, viaXf(two, PUBLIC, "app.example, ", "https, http"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @Test void a08_otherFamilyNeverRead() {
+ var b = xf().build();
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example;proto=https"), FORWARDED_HOST_MISSING);
+ var r = viaXf(b, "https://other.example", "app.example", "https").h("Forwarded", "host=other.example;proto=https");
+ refused(b, r, ORIGIN_MISMATCH);
+ var f = fwd().build();
+ refused(f, post(f, PUBLIC).h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https"), FORWARDED_HOST_MISSING);
+ }
+
+ @Test void a09_portComesOnlyFromTheHostValueOrTheProtoDefault() {
+ var b = xf().build();
+ refused(b, viaXf(b, "https://app.example:8443", "app.example", "https"), ORIGIN_MISMATCH);
+ allowed(b, viaXf(b, "https://app.example:8443", "app.example:8443", "https"));
+ // X-Forwarded-Port is never read.
+ refused(b, viaXf(b, "https://app.example:8443", "app.example", "https").h("X-Forwarded-Port", "8443"), ORIGIN_MISMATCH);
+ }
+
+ @Test void a10_allowedHostsAgainstTheForwardedHost() {
+ var b = xf().allowedHosts("app.example").build();
+ allowed(b, viaXf(b, PUBLIC, "app.example", "https"));
+ var other = xf().allowedHosts("other.example").build();
+ refused(other, viaXf(other, PUBLIC, "app.example", "https"), HOST_NOT_ALLOWED);
+ // A safe GET with no forwarded header: allowed with no list, refused with one.
+ var plain = xf().build();
+ allowed(plain, new R().method("GET").h("Host", "backend:8080"));
+ refused(b, new R().method("GET").h("Host", "backend:8080"), FORWARDED_HOST_MISSING);
+ }
+
+ @Test void a11_hostStillRequired() {
+ var b = xf().build();
+ var x = b.check(new R().method("POST").h("Origin", PUBLIC).h("X-Forwarded-Host", "app.example")
+ .h("X-Forwarded-Proto", "https").build());
+ assertEquals(HOST_MISSING, x.reason());
+ assertEquals(400, x.status());
+ }
+
+ @Test void a12_offByDefaultIgnoresForwarded() {
+ var b = CsrfBoundary.create().build();
+ refused(b, viaXf(b, PUBLIC, "app.example", "https"), ORIGIN_MISMATCH);
+ allowed(b, post(b, "http://backend:8080").h("X-Forwarded-Host", "evil.example"));
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // HTTP, Forwarded
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void b01_forwardedAdmitted() {
+ var b = fwd().build();
+ allowed(b, post(b, PUBLIC).h("Forwarded", "for=1.2.3.4;host=app.example;proto=https"));
+ allowed(b, post(b, PUBLIC).h("Forwarded", "Host=\"app.example\"; PROTO = https"));
+ allowed(b, post(b, "https://[::1]:8443").h("Forwarded", "host=\"[::1]:8443\";proto=https"));
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example:8080;proto=https"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @Test void b02_forwardedMissingAndMalformed() {
+ var b = fwd().build();
+ refused(b, post(b, PUBLIC), FORWARDED_HOST_MISSING);
+ refused(b, post(b, PUBLIC).h("Forwarded", "for=1.2.3.4;proto=https"), FORWARDED_HOST_MISSING);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example"), FORWARDED_PROTO_MISSING);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example;proto=ws"), FORWARDED_PROTO_MALFORMED);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=\"\";proto=https"), FORWARDED_HOST_MALFORMED);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=a;host=app.example;proto=https"), FORWARDED_HOST_MALFORMED);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example;proto=https;proto=http"), FORWARDED_PROTO_MALFORMED);
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=app.example;proto=https,"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "host=\"app.example;proto=https", "host=\"app\\.example\";proto=https", "host;proto=https", "host=;proto=https",
+ "=app.example", "host=app.example proto=https", "host=\"a\"b;proto=https"
+ })
+ void b03_untokenizable(String value) {
+ var b = fwd().build();
+ refused(b, post(b, PUBLIC).h("Forwarded", value), FORWARDED_HOST_MALFORMED);
+ }
+
+ @Test void b04_wholeHeaderMustTokenize() {
+ var b = fwd().build();
+ // A client's line that does not tokenize refuses the request, even though the proxy's last line is fine.
+ refused(b, post(b, PUBLIC).h("Forwarded", "for=\"x").h("Forwarded", "host=app.example;proto=https"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @Test void b05_hopsAcrossLinesAndCommas() {
+ var b = fwd().build();
+ allowed(b, post(b, PUBLIC).h("Forwarded", "host=evil.example;proto=http")
+ .h("Forwarded", "host=app.example;proto=https"));
+ allowed(b, post(b, PUBLIC).h("Forwarded", "host=evil.example;proto=http, host=app.example;proto=https"));
+ allowed(b, post(b, PUBLIC).h("Forwarded", "for=\"a,b\";host=evil.example;proto=http, host=app.example;proto=https"));
+
+ var two = fwd().trustedHops(2).build();
+ allowed(two, post(two, PUBLIC).h("Forwarded", "host=app.example;proto=https, host=internal;proto=http"));
+ refused(two, post(two, PUBLIC).h("Forwarded", "host=app.example;proto=https"), FORWARDED_HOPS_INSUFFICIENT);
+ // An incomplete counted element is never skipped, and no value is borrowed from a neighbour.
+ refused(two, post(two, PUBLIC).h("Forwarded", "host=app.example;proto=https, for=10.0.0.1"), FORWARDED_HOST_MISSING);
+ refused(two, post(two, PUBLIC).h("Forwarded", "for=10.0.0.1, host=app.example;proto=https"), FORWARDED_HOST_MISSING);
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // The container's view
+ //-----------------------------------------------------------------------------------------------------------------
+
+ private static R container(CsrfBoundary b, String origin, String name, int port, String scheme) {
+ return viaXf(b, origin, "app.example", "https").scheme(scheme).container(name, port);
+ }
+
+ @Test void c01_containerMustAgree() {
+ var b = xf().originSource(OriginSource.CONTAINER).build();
+ allowed(b, container(b, PUBLIC, "app.example", 443, "https"));
+ allowed(b, container(b, PUBLIC, "APP.example", 443, "https"));
+ refused(b, container(b, PUBLIC, "evil.example", 443, "https"), FORWARDED_CONTAINER_MISMATCH);
+ // The connector port against the proto default is a mismatch, loud and fail-closed.
+ refused(b, container(b, PUBLIC, "app.example", 8080, "https"), FORWARDED_CONTAINER_MISMATCH);
+ // The container did no forwarding: its view is the transport.
+ refused(b, container(b, PUBLIC, "backend", 8080, "http"), FORWARDED_CONTAINER_MISMATCH);
+ refused(b, container(b, PUBLIC, "app.example", 443, "http"), FORWARDED_CONTAINER_MISMATCH);
+ // An underivable container view is refused.
+ refused(b, container(b, PUBLIC, "app.example:99", 443, "https"), FORWARDED_CONTAINER_MISMATCH);
+ refused(b, container(b, PUBLIC, null, 443, "https"), FORWARDED_CONTAINER_MISMATCH);
+ }
+
+ @Test void c02_containerExplicitPort() {
+ var b = xf().originSource(OriginSource.CONTAINER).build();
+ var r = viaXf(b, "https://app.example:443", "app.example:443", "https").scheme("https").container("app.example", 443);
+ allowed(b, r);
+ var other = viaXf(b, "https://app.example:8443", "app.example:8443", "https").scheme("https").container("app.example", 8443);
+ allowed(b, other);
+ }
+
+ @Test void c03_hostHeaderFingerprintLeftOfSelected() {
+ var b = xf().build();
+ // Host equals the client-writable left entry: the container trusted a hop it must not have.
+ refused(b, new R().method("POST").scheme("http").h("Host", "left.example").h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "left.example, app.example").h("X-Forwarded-Proto", "http, https"),
+ FORWARDED_CONTAINER_MISMATCH);
+ // The transport name is replaced.
+ allowed(b, viaXf(b, PUBLIC, "left.example, app.example", "http, https"));
+ // A match to the right of the selected entry (an inner hop or the transport) is replaced, never refused.
+ var two = xf().trustedHops(2).build();
+ allowed(two, viaXf(two, PUBLIC, "app.example, backend", "https, http"));
+ // Availability-only edge: a client can get its own request refused.
+ refused(b, viaXf(b, PUBLIC, "backend, app.example", "http, https").remove("Host").h("Host", "backend"),
+ FORWARDED_CONTAINER_MISMATCH);
+ // Same host, different port: the TLS-terminating transport, replaced.
+ allowed(b, post(b, PUBLIC).remove("Host").h("Host", "app.example:8080").h("X-Forwarded-Host", "app.example")
+ .h("X-Forwarded-Proto", "https"));
+ }
+
+ @Test void c04_http2SynthesisedHostIsTheContainerView() {
+ var b = xf().build();
+ // HTTP/2: no Host header, the server name stands in; it is the container view and is replaced.
+ var r = new R().method("POST").scheme("http").protocol("HTTP/2.0").container("backend", 8080).h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https");
+ allowed(b, r);
+ var left = new R().method("POST").scheme("http").protocol("HTTP/2.0").container("left.example", 8080).h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "left.example, app.example").h("X-Forwarded-Proto", "http, https");
+ refused(b, left, FORWARDED_CONTAINER_MISMATCH);
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Handshakes
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void d01_handshakeAdmitted() {
+ var b = xf().build();
+ hsAllowed(b, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https");
+ hsAllowed(b, "ws", "backend:8080", "origin", PUBLIC, "x-forwarded-host", "app.example", "X-FORWARDED-PROTO", "https",
+ "Sec-Fetch-Site", "same-origin");
+ hsRefused(b, ORIGIN_MISMATCH, "ws", "backend:8080", "Origin", "http://backend:8080", "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ hsRefused(b, FETCH_SITE_NOT_SAME_ORIGIN, "ws", "backend:8080", "Origin", PUBLIC, "Sec-Fetch-Site", "same-site",
+ "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https");
+ }
+
+ @Test void d02_handshakeMissingAndMalformed() {
+ var b = xf().build();
+ hsRefused(b, FORWARDED_HOST_MISSING, "ws", "backend:8080", "Origin", PUBLIC);
+ hsRefused(b, FORWARDED_HOST_MISSING, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Proto", "https");
+ hsRefused(b, FORWARDED_PROTO_MISSING, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example");
+ hsRefused(b, FORWARDED_PROTO_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "wss");
+ hsRefused(b, FORWARDED_HOST_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "a@app.example",
+ "X-Forwarded-Proto", "https");
+ hsRefused(b, HOST_MISSING, "ws", null, "Origin", PUBLIC, "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https");
+ }
+
+ @Test void d03_handshakeTwoSpellingsRefused() {
+ var b = xf().build();
+ hsRefused(b, FORWARDED_HOST_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "x-forwarded-host", "app.example", "X-Forwarded-Proto", "https");
+ hsRefused(b, FORWARDED_PROTO_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https", "x-forwarded-proto", "https");
+ // Origin is counted, not ordered: two spellings are two values, and a second value is a mismatch.
+ hsRefused(b, ORIGIN_MISMATCH, "ws", "backend:8080", "Origin", PUBLIC, "origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ }
+
+ @Test void d04_listFormsAlwaysRefuseWhenTrusted() {
+ var b = xf().build();
+ var x = b.checkHandshake("ws", List.of("backend:8080"), List.of(PUBLIC), List.of());
+ assertEquals(FORWARDED_HOST_MISSING, x.reason());
+ var plain = CsrfBoundary.create().build();
+ assertTrue(plain.checkHandshake("ws", List.of("app.example"), List.of("http://app.example"), List.of()).isAllowed());
+ }
+
+ @Test void d05_handshakeSchemeAndUnknownTransport() {
+ var b = xf().build();
+ hsAllowed(b, "wss", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https");
+ // An unknown URI scheme is refused even with a well-formed forwarded origin.
+ hsRefused(b, ORIGIN_MISMATCH, "ftp", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ }
+
+ @Test void d06_handshakeFingerprintAndHops() {
+ var b = xf().build();
+ hsRefused(b, FORWARDED_CONTAINER_MISMATCH, "ws", "left.example", "Origin", PUBLIC, "X-Forwarded-Host", "left.example, app.example",
+ "X-Forwarded-Proto", "http, https");
+ hsAllowed(b, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "left.example, app.example",
+ "X-Forwarded-Proto", "http, https");
+ // A real Jetty-customizer view: Host and scheme already rewritten, so they agree.
+ hsAllowed(b, "wss", "app.example", "Origin", PUBLIC, "X-Forwarded-Host", "app.example", "X-Forwarded-Proto", "https");
+ }
+
+ @Test void d07_handshakeForwardedFamilyAndAllowedHosts() {
+ var b = fwd().allowedHosts("app.example").build();
+ hsAllowed(b, "ws", "backend:8080", "Origin", PUBLIC, "Forwarded", "host=app.example;proto=https");
+ hsRefused(b, FORWARDED_HOST_MISSING, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ var other = fwd().allowedHosts("other.example").build();
+ hsRefused(other, HOST_NOT_ALLOWED, "ws", "backend:8080", "Origin", PUBLIC, "Forwarded", "host=app.example;proto=https");
+ }
+
+ @Test void d08_handshakeOffIgnoresForwarded() {
+ var b = CsrfBoundary.create().build();
+ hsRefused(b, ORIGIN_MISMATCH, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ hsAllowed(b, "ws", "backend:8080", "Origin", "http://backend:8080");
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Review follow-ups
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void f01_unenumerableHeadersAreMalformedNeverTheFirstLine() {
+ var b = xf().build();
+ var req = viaXf(b, "http://evil.example", "evil.example", "http").build();
+ when(req.getHeaders("X-Forwarded-Host")).thenReturn(null);
+ var x = b.check(req);
+ assertFalse(x.isAllowed(), x::toString);
+ assertEquals(FORWARDED_HOST_MALFORMED, x.reason());
+ var req2 = viaXf(b, "http://evil.example", "evil.example", "http").build();
+ when(req2.getHeaders("X-Forwarded-Proto")).thenReturn(null);
+ assertEquals(FORWARDED_PROTO_MALFORMED, b.check(req2).reason());
+ var f = fwd().build();
+ var req3 = post(f, PUBLIC).h("Forwarded", "host=evil.example;proto=http").build();
+ when(req3.getHeaders("Forwarded")).thenReturn(null);
+ assertEquals(FORWARDED_HOST_MALFORMED, f.check(req3).reason());
+ // Absent stays absent.
+ refused(b, post(b, PUBLIC), FORWARDED_HOST_MISSING);
+ }
+
+ @Test void f02_hostsAndProtosOfDifferentCountsMismatchBeforeTheHopCount() {
+ var two = xf().trustedHops(2).build();
+ refused(two, viaXf(two, PUBLIC, "a, b", "https"), FORWARDED_HOPS_MISMATCH);
+ refused(two, viaXf(two, PUBLIC, "a", "https, http"), FORWARDED_HOPS_MISMATCH);
+ refused(two, viaXf(two, PUBLIC, "a", "https"), FORWARDED_HOPS_INSUFFICIENT);
+ refused(two, viaXf(two, PUBLIC, "a, b, c", "https, http"), FORWARDED_HOPS_MISMATCH);
+ }
+
+ @Test void f03_unparseableLeftEntryIsPossiblyTheContainersHost() {
+ var b = xf().build();
+ // The container could normalize the quoted left entry into the Host it presents; refuse rather than guess.
+ var r = new R().method("POST").scheme("http").h("Host", "left.example").h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "\"left.example\", app.example").h("X-Forwarded-Proto", "http, https");
+ refused(b, r, FORWARDED_CONTAINER_MISMATCH);
+ // Availability only: the client's own unparseable entry also refuses a request whose transport host is rewritten.
+ refused(b, viaXf(b, PUBLIC, "\"left.example\", app.example", "http, https"), FORWARDED_CONTAINER_MISMATCH);
+ var f = fwd().build();
+ var r2 = new R().method("POST").scheme("http").h("Host", "evil.example").h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(f.csrfHeader(), f.tokenFor(new R().build()))
+ .h("Forwarded", "host=\"user@evil.example\";proto=http, host=app.example;proto=https");
+ refused(f, r2, FORWARDED_CONTAINER_MISMATCH);
+ hsRefused(b, FORWARDED_CONTAINER_MISMATCH, "ws", "left.example", "Origin", PUBLIC, "X-Forwarded-Host", "\"left.example\", app.example",
+ "X-Forwarded-Proto", "http, https");
+ }
+
+ @Test void f04_forwardedEdgeShapes() {
+ var two = fwd().trustedHops(2).build();
+ refused(two, post(two, PUBLIC).h("Forwarded", "host=app.example;proto=https,,host=internal;proto=http"), FORWARDED_HOST_MALFORMED);
+ refused(two, post(two, PUBLIC).h("Forwarded", "host=app.example;proto=https").h("Forwarded", "")
+ .h("Forwarded", "host=internal;proto=http"), FORWARDED_HOST_MALFORMED);
+ var b = fwd().build();
+ allowed(b, post(b, PUBLIC).h("Forwarded", "host=app.example;proto=\"https\""));
+ allowed(b, post(b, PUBLIC).h("Forwarded", "host=\"app.example:443\";proto=https"));
+ refused(b, post(b, PUBLIC).h("Forwarded", "host=\"app.example:444\";proto=https"), ORIGIN_MISMATCH);
+ allowed(b, post(b, PUBLIC).h("Forwarded", "host=app.example;;proto=https"));
+ }
+
+ @Test void f05_xForwardedEdgeShapes() {
+ var b = xf().build();
+ allowed(b, post(b, PUBLIC).h("X-Forwarded-Host", "x").h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "http").h("X-Forwarded-Proto", "https"));
+ refused(b, viaXf(b, PUBLIC, "app.example", "ht\ttp"), FORWARDED_PROTO_MALFORMED);
+ var two = xf().trustedHops(2).build();
+ refused(two, viaXf(two, PUBLIC, "app.example,,internal", "https, https, http"), FORWARDED_HOST_MALFORMED);
+ refused(two, viaXf(two, PUBLIC, "app.example, internal", "https, ws"), FORWARDED_PROTO_MALFORMED);
+ }
+
+ @Test void f09_mixedCaseAndQuotedTab() {
+ var b = xf().build();
+ var r = post(b, PUBLIC).h("X-Forwarded-Host", "evil.example").h("x-forwarded-host", "app.example")
+ .h("X-Forwarded-Proto", "http").h("x-FORWARDED-proto", "https");
+ allowed(b, r);
+ var f = fwd().build();
+ refused(f, post(f, PUBLIC).h("Forwarded", "host=\"app.\texample\";proto=https"), FORWARDED_HOST_MALFORMED);
+ }
+
+ @Test void f06_safeMethodsAndAllowedHosts() {
+ var open = xf().build();
+ // No allowedHosts: a safe request is not judged, forwarded headers or not, even malformed ones.
+ allowed(open, new R().method("GET").h("Host", "backend:8080"));
+ allowed(open, new R().method("GET").h("Host", "backend:8080").h("X-Forwarded-Host", "\"").h("X-Forwarded-Proto", "ws"));
+ var listed = xf().allowedHosts("app.example").build();
+ refused(listed, new R().method("GET").h("Host", "backend:8080"), FORWARDED_HOST_MISSING);
+ allowed(listed, new R().method("GET").h("Host", "backend:8080").h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https"));
+ }
+
+ @Test void f07_handshakeEdgeShapes() {
+ var two = xf().trustedHops(2).build();
+ hsAllowed(two, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example, internal", "X-Forwarded-Proto", "https, http");
+ hsRefused(two, FORWARDED_HOPS_INSUFFICIENT, "ws", "backend:8080", "Origin", PUBLIC, "X-Forwarded-Host", "app.example",
+ "X-Forwarded-Proto", "https");
+ var f = fwd().build();
+ hsRefused(f, FORWARDED_HOST_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "Forwarded", "host=\"app.example;proto=https");
+ hsRefused(f, FORWARDED_HOST_MALFORMED, "ws", "backend:8080", "Origin", PUBLIC, "Forwarded", "host=app.example;proto=https",
+ "forwarded", "host=app.example;proto=https");
+ hsRefused(f, FORWARDED_HOST_MISSING, "ws", "backend:8080", "Origin", PUBLIC);
+ var b = xf().build();
+ var empty = b.checkHandshake("ws", new HandshakeHosts(List.of("backend:8080"), false), new LinkedHashMap<String,List<String>>());
+ assertEquals(FORWARDED_HOST_MISSING, empty.reason());
+ }
+
+ @Test void f08_containerSourceOverHttp2() {
+ var b = xf().originSource(OriginSource.CONTAINER).build();
+ var r = new R().method("POST").scheme("https").protocol("HTTP/2.0").container("app.example", 443).h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https");
+ allowed(b, r);
+ var off = new R().method("POST").scheme("http").protocol("HTTP/2.0").container("backend", 8080).h("Origin", PUBLIC)
+ .h("Content-Type", "application/json").h(b.csrfHeader(), b.tokenFor(new R().build()))
+ .h("X-Forwarded-Host", "app.example").h("X-Forwarded-Proto", "https");
+ refused(b, off, FORWARDED_CONTAINER_MISMATCH);
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // Builder
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void e01_builder() {
+ assertThrows(IllegalArgumentException.class, () -> CsrfBoundary.create().trustedHops(0));
+ assertThrows(IllegalArgumentException.class, () -> CsrfBoundary.create().trustedHops(17));
+ assertThrows(IllegalArgumentException.class, () -> CsrfBoundary.create().trustedHops(2).build());
+ assertThrows(IllegalArgumentException.class, () -> CsrfBoundary.create().trustedForwarding(null));
+ var b = xf().trustedHops(16).build();
+ assertEquals(ForwardedSource.X_FORWARDED, b.trustedForwarding());
+ assertEquals(16, b.trustedHops());
+ assertTrue(b.toString().contains("trustedForwarding=X_FORWARDED") && b.toString().contains("trustedHops=16"), b.toString());
+ assertEquals(ForwardedSource.NONE, CsrfBoundary.create().build().trustedForwarding());
+ assertEquals(1, CsrfBoundary.create().build().trustedHops());
+ }
+}