relay(NetSocket client, Buffer clientHello, RelayTarget target, RelayKind kind,
diff --git a/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/SniFrontListener.java b/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/SniFrontListener.java
index 03c25f1bb..48a302feb 100644
--- a/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/SniFrontListener.java
+++ b/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/SniFrontListener.java
@@ -224,24 +224,36 @@ public final class SniFrontListener {
public static final Duration SATURATION_WARN_INTERVAL = Duration.ofSeconds(60);
/**
- * Why the front closed a connection at once: at accept, without reading from it, or at the route
- * decision of a passthrough match, without dialling its backend.
+ * Why the front closed a connection at once, and where: each reason carries its token and the stage
+ * it refuses at, and {@link ApiSheriffLogMessages.WARN#FRONT_CONNECTION_REFUSED} logs both as
+ * parameters, so the record never restates the set of reasons. {@link #CAP} and
+ * {@link #SOURCE_SHARE} refuse at accept, without reading from the connection; {@link #DIAL_BUDGET}
+ * refuses at the route decision of a passthrough match, before its backend is dialled.
*/
public enum Refusal {
- /** The undecided-connection cap was full. */
- CAP("cap"),
+ /** The undecided-connection cap was full; the bound logged is the cap. */
+ CAP("cap", "at accept, without reading from the connection"),
- /** The connection's source already held its full share of the cap. */
- SOURCE_SHARE("source_share"),
+ /**
+ * The connection's source already held its full share of the cap; the bound logged is that
+ * share.
+ */
+ SOURCE_SHARE("source_share", "at accept, without reading from the connection"),
- /** The connection's passthrough target already had its full dial budget in flight. */
- DIAL_BUDGET("dial_budget");
+ /**
+ * The connection's passthrough target already had its full dial budget in flight; the bound
+ * logged is that budget — the dialling connections of one target, which count against the cap,
+ * so one backend that does not answer the dial holds at most its eighth of the cap.
+ */
+ DIAL_BUDGET("dial_budget", "at its route decision, before its backend is dialled");
private final String token;
+ private final String stage;
- Refusal(String token) {
+ Refusal(String token, String stage) {
this.token = token;
+ this.stage = stage;
}
/**
@@ -250,6 +262,13 @@ public enum Refusal {
public String token() {
return token;
}
+
+ /**
+ * @return the fixed phrase naming where the front refuses for this reason, logged after the token
+ */
+ public String stage() {
+ return stage;
+ }
}
/** The Vert.x timer id meaning "no deadline timer was armed". */
@@ -547,8 +566,8 @@ private void refuse(NetSocket socket, Refusal refusal) {
case DIAL_BUDGET -> maxDialsPerTarget;
});
if (warnDue(refusal)) {
- LOGGER.warn(ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED, refusal.token(), bound,
- Long.toString(warnInterval.toSeconds()));
+ LOGGER.warn(ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED, refusal.token(), refusal.stage(),
+ bound, Long.toString(warnInterval.toSeconds()));
} else {
LOGGER.debug("Front connection refused (%s): the bound of %s connections for this reason is full",
refusal.token(), bound);
@@ -710,16 +729,22 @@ private void onData(Buffer chunk) {
* passthrough match first claims one dial slot of its target; when the target's budget is full the
* connection is refused instead — its slots of the cap and of its source's share are returned at
* once and it is never dialled. The terminated hand-off claims no dial slot.
+ *
+ * The SNI is normalized once ({@link SniFrontListener#normalizeSni}) and that key both selects the target and is
+ * the label the relay audits a passthrough match under — the {@code passthrough_sni} host as
+ * configured, lower-cased — never the raw ClientHello value, whose letter case and trailing dot
+ * are the client's choice.
*/
private void route(@Nullable String serverName, Buffer replay) {
- RelayTarget target = serverName == null ? null : passthroughTargets.get(normalizeSni(serverName));
- if (serverName != null && target != null) {
+ String sniKey = serverName == null ? null : normalizeSni(serverName);
+ RelayTarget target = sniKey == null ? null : passthroughTargets.get(sniKey);
+ if (sniKey != null && target != null) {
if (!claimDial(target)) {
releaseSlot();
refuse(socket, Refusal.DIAL_BUDGET);
return;
}
- dial(() -> relay.relay(socket, replay, target, RelayKind.PASSTHROUGH, serverName), target);
+ dial(() -> relay.relay(socket, replay, target, RelayKind.PASSTHROUGH, sniKey), target);
return;
}
if (serverName == null) {
diff --git a/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/TlsEdgeProducer.java b/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/TlsEdgeProducer.java
index f48df4cb8..39c2006ea 100644
--- a/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/TlsEdgeProducer.java
+++ b/api-sheriff/src/main/java/de/cuioss/sheriff/gateway/tls/TlsEdgeProducer.java
@@ -151,7 +151,7 @@ public class TlsEdgeProducer {
* ({@code quarkus.http.idle-timeout}), which the relay idle timeout must
* not undercut
* @param publicPort the public TLS port the front listener binds when passthrough is active
- * @param internalHttpsPort the internal loopback port the terminated Quarkus HTTPS listener owns
+ * @param internalHttpsPort the internal port the terminated Quarkus HTTPS listener owns
*/
@Inject
@SuppressWarnings("java:S107") // CDI constructor injection: each parameter is one injected collaborator or key
diff --git a/api-sheriff/src/main/resources/application.properties b/api-sheriff/src/main/resources/application.properties
index f08e93168..c756cce93 100644
--- a/api-sheriff/src/main/resources/application.properties
+++ b/api-sheriff/src/main/resources/application.properties
@@ -10,7 +10,7 @@ quarkus.application.name=api-sheriff
# gateway.yaml. ADR-0025 states the boundary rule — gateway.yaml names TLS *policy* in neutral terms,
# while ports and trust material stay deployment-supplied. The ADR-0017 SNI passthrough topology
# depends on exactly this: a deployment that enables tls.passthrough_sni overrides
-# QUARKUS_HTTP_SSL_PORT to move the terminated listener to the internal loopback port (8444), which a
+# QUARKUS_HTTP_SSL_PORT to move the terminated listener to the internal port (8444), which a
# gateway.yaml-owned port could not express.
quarkus.http.port=8080
quarkus.http.ssl-port=8443
@@ -142,12 +142,16 @@ quarkus.http.limits.max-body-size=64M
# Connection cap — how many connections the Quarkus-terminated side holds open at once.
# Without this key Quarkus applies no cap at all. A connection beyond the cap is closed without being
-# served, while the connections already open are served on. It bounds open connections whatever they
-# carry; edge_hardening.admission_cap bounds the requests in flight on them. The cap is ONE counter
-# shared by the plain-HTTP redirect listener and the HTTPS listener of the Quarkus-terminated side, so
-# a connection to the redirect listener counts toward it too. The SNI front listener of
-# passthrough_sni and the management interface are not counted. It is set here, not in gateway.yaml,
-# and is not configurable there.
+# served, while the connections already open are served on. It counts a connection once the
+# connection is established: on the HTTPS listener only after its TLS handshake has completed, so a
+# connection still in its handshake holds no slot. A counted connection holds its slot until it closes,
+# whether or not it carries a request; edge_hardening.admission_cap bounds the requests in flight on
+# them. The cap is ONE counter shared by the plain-HTTP redirect listener and the HTTPS listener of the
+# Quarkus-terminated side, so a connection to the redirect listener counts toward it too. It has no
+# per-source share: one source can hold the whole counter, and routing through the SNI front of
+# passthrough_sni does not bound it, because the front's per-source share counts only the connections
+# it has not yet handed over. The SNI front listener itself and the management interface are not
+# counted. It is set here, not in gateway.yaml, and is not configurable there.
#
# Derivation. Dockerfile.native declares no file-descriptor limit, so the process runs under
# whatever limit the container runtime grants, and the image cannot derive a value from it. The cap
@@ -226,20 +230,30 @@ quarkus.management.enabled=true
# default.
#
# Rule: each applied bound is held at the main listener's value, and a default that is already tighter
-# is kept rather than raised. Only the header block differs from its default (20K), so only it is set —
-# to the main listener's 16 KiB. The request line (4096) and the chunk (8 KiB) keep their defaults,
-# which are tighter than the main listener's 8 KiB and 16 KiB. The body keeps its 10 MiB default, which
-# is tighter than the main listener's 64M above. The form limits (256 fields, 2048 bytes per attribute,
-# 1024 undecoded bytes) keep the defaults the main listener keeps too. They do act here: the management
-# body handler decodes a URL-encoded POST body on every management route, health probes included.
+# is kept rather than raised. The header block differs from its default (20K), so it is set — to the
+# main listener's 16 KiB. The request line (4096) and the chunk (8 KiB) keep their defaults, which are
+# tighter than the main listener's 8 KiB and 16 KiB. The form limits (256 fields, 2048 bytes per
+# attribute, 1024 undecoded bytes) keep the defaults the main listener keeps too. They do act here: the
+# management body handler decodes a URL-encoded POST body on every management route, health probes
+# included.
+#
+# The body bound is set below its default on its own terms, not the main listener's: no management
+# route reads a request body, so the 10 MiB default would only let a client make the body handler
+# buffer 10 MiB per request for nothing. It is set to 32 KiB — the smallest power
+# of two that stays above every body another applied bound must see in order to act on its own terms:
+# the form decoder's 2 KiB attribute and 1 KiB buffered bytes, and the 8 KiB chunk bound, which is
+# observed with a 16 KiB chunk. The body bound therefore never pre-empts their 400s with a 413 of its
+# own. It is fixed, not configurable: gateway.yaml carries no key for it.
#
# ManagementListenerTransportTest pins, on a live management listener, each of those bounds and the
-# 8 KiB HTTP/2 header list the listener announces: the header block (431 past 16 KiB, the one bound
-# set here), the request line (414 past the 4 KiB default), each form limit (400 one unit past it), and
-# the body (413 past 10 MiB), each against a control at or under the bound that is served. The chunk
-# bound refuses nothing — the codec delivers a larger chunk in pieces of at most 8 KiB, which no client
-# can observe — so the test asserts what is observable: a chunk twice that size is served.
+# 8 KiB HTTP/2 header list the listener announces: the header block (431 past 16 KiB), the request line
+# (414 past the 4 KiB default), each form limit (400 one unit past it), and the body (413 past 32 KiB),
+# each against a control at or under the bound that is served. The header block and the body are the
+# two bounds set here. The chunk bound refuses nothing — the codec delivers a larger chunk in pieces of
+# at most 8 KiB, which no client can observe — so the test asserts what is observable: a chunk twice
+# that size is served.
quarkus.management.limits.max-header-size=16K
+quarkus.management.limits.max-body-size=32K
# The key-less TLS bucket the plain-HTTP management opt-out selects.
#
@@ -280,7 +294,7 @@ quarkus.tls.plain-management.reload-period=24H
# is empty the front is never created and the terminated Quarkus HTTPS listener (quarkus.http.ssl-port
# above) keeps the public port — the default single-listener topology is unchanged (zero overhead).
# A deployment that enables tls.passthrough_sni gives the public TLS port to the front listener and
-# moves the terminated Quarkus HTTPS listener to the internal loopback port by additionally setting
+# moves the terminated Quarkus HTTPS listener to the internal port by additionally setting
# quarkus.http.ssl-port=${sheriff.tls.internal-https-port}
# so the front owns sheriff.tls.public-port and opaquely L4-relays a matched SNI to the resolved
# backend, handing every other connection to the internal terminated listener.
diff --git a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/SingleSourceTlsContractTest.java b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/SingleSourceTlsContractTest.java
index 56cc9ffe3..4a622c46c 100644
--- a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/SingleSourceTlsContractTest.java
+++ b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/SingleSourceTlsContractTest.java
@@ -98,7 +98,7 @@ class SingleSourceTlsContractTest {
*/
private static final Set SANCTIONED_EXCEPTIONS = Set.of(
// Deployment-bound port. Promoting it would break the ADR-0017 SNI split, where a
- // deployment moves the terminated listener to the internal loopback port through
+ // deployment moves the terminated listener to the internal port through
// QUARKUS_HTTP_SSL_PORT — a topology a gateway.yaml-owned port could not express.
"quarkus.http.ssl-port",
// Deployment-bound exposure knob of the same class: a port/exposure decision the
diff --git a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/validation/rule/EdgeRulesTest.java b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/validation/rule/EdgeRulesTest.java
index 5e7c1bf86..f20982234 100644
--- a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/validation/rule/EdgeRulesTest.java
+++ b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/config/validation/rule/EdgeRulesTest.java
@@ -57,8 +57,9 @@
* Tests for the edge rules the {@link ConfigValidator} runs through {@link EdgeRules}: the D5
* boot-time hardening of {@code forwarded.trusted_proxies} (real-CIDR parsing with full-space
* rejection and the broad-prefix boot WARN, ADR-0044), the boot WARN for an acting
- * {@code enumeration_detection} action behind trusted proxies, and the {@code tls.passthrough_sni} host
- * collision and alias-resolvability rules.
+ * {@code enumeration_detection} action behind trusted proxies, the {@code tls.passthrough_sni} host
+ * collision and alias-resolvability rules, and the boot WARN for a passthrough topology meeting an
+ * acting detection action or a loopback trusted proxy.
*
* Every case drives the full default validator, so a rule dropped from its registration fails here as
* surely as a rule whose body is removed.
@@ -71,6 +72,9 @@ class EdgeRulesTest {
private static final String DETECTION_BEHIND_TRUSTED_PROXIES_ID =
ConfigLogMessages.WARN.DETECTION_ACTION_BEHIND_TRUSTED_PROXIES.resolveIdentifierString();
+ private static final String PASSTHROUGH_SOURCE_COLLAPSE_ID =
+ ConfigLogMessages.WARN.PASSTHROUGH_SOURCE_COLLAPSE.resolveIdentifierString();
+
private final ConfigValidator validator = new ConfigValidator();
// --- fixture helpers -------------------------------------------------
@@ -273,6 +277,92 @@ void shouldWarnOnActingDetectionBehindTrustedProxies(String label,
}
}
+ /**
+ * The boot WARN that a passthrough topology meets a configuration acting on the loopback relay
+ * leg as if it were a client. It fires once for {@code block} and once for {@code delay} under a
+ * non-empty {@code passthrough_sni}, and once for a {@code trusted_proxies} range holding a
+ * loopback address — overlapping {@code 127.0.0.0/8}, or containing {@code ::1}. Its matched
+ * controls stay silent: passthrough alone, each combination without passthrough, {@code observe}
+ * or disabled detection under passthrough, and a non-loopback proxy list under passthrough.
+ */
+ static Stream passthroughSourceCollapseControls() {
+ EnumerationDetectionConfig block = detection(true, EnumerationDetectionConfig.Action.BLOCK);
+ List nonLoopback = List.of("192.0.2.0/24", "2001:db8::/48");
+ return Stream.of(
+ Arguments.of("passthrough with block", true, block, null, "enumeration_detection.action is block"),
+ Arguments.of("passthrough with delay", true,
+ detection(true, EnumerationDetectionConfig.Action.DELAY), null,
+ "enumeration_detection.action is delay"),
+ Arguments.of("passthrough with an IPv4 range overlapping 127.0.0.0/8", true, null,
+ List.of("192.0.2.0/24", "127.0.0.1/32"), "forwarded.trusted_proxies holds a loopback range"),
+ Arguments.of("passthrough with an IPv6 range containing ::1", true, null, List.of("::1/128"),
+ "forwarded.trusted_proxies holds a loopback range"),
+ Arguments.of("passthrough alone", true, null, null, null),
+ Arguments.of("block without passthrough", false, block, null, null),
+ Arguments.of("a loopback proxy without passthrough", false, null, List.of("127.0.0.0/8"), null),
+ Arguments.of("passthrough with observe", true,
+ detection(true, EnumerationDetectionConfig.Action.OBSERVE), null, null),
+ Arguments.of("passthrough with detection disabled and block", true,
+ detection(false, EnumerationDetectionConfig.Action.BLOCK), null, null),
+ Arguments.of("passthrough with a non-loopback proxy list", true, null, nonLoopback, null));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("passthroughSourceCollapseControls")
+ @DisplayName("Should warn only when passthrough_sni meets an acting detection action or a loopback trusted proxy")
+ void shouldWarnOnPassthroughSourceCollapse(String label, boolean passthrough,
+ @Nullable EnumerationDetectionConfig detection, @Nullable List trustedProxies,
+ @Nullable String expectedToken) {
+ GatewayConfig.GatewayConfigBuilder builder = validGateway().enumerationDetection(detection);
+ if (passthrough) {
+ builder.tls(TlsConfig.builder().passthroughSni(Map.of("secure.example.com", "SECURE")).build());
+ }
+ if (trustedProxies != null) {
+ builder.forwarded(ForwardedConfig.builder().trustedProxies(trustedProxies).build());
+ }
+ EndpointConfig endpoint = endpoint("orders", "ORDERS", List.of(), routeConfig("r", HttpMethod.GET));
+
+ List errors = validator.validate(builder.build(), List.of(endpoint),
+ topologyWith("ORDERS", "SECURE"));
+
+ assertTrue(errors.isEmpty(), () -> "the combination boots, got: " + errors);
+ List warnings = TestLoggerFactory.getTestHandler()
+ .resolveLogMessagesContaining(TestLogLevel.WARN, PASSTHROUGH_SOURCE_COLLAPSE_ID).stream()
+ .map(LogRecord::getMessage).toList();
+ if (expectedToken != null) {
+ assertEquals(1, warnings.size(), () -> label + " must warn once, got: " + warnings);
+ assertTrue(warnings.getFirst().contains(expectedToken),
+ () -> "the warning names the combination by its fixed token: " + warnings);
+ assertTrue(warnings.stream().noneMatch(message -> message.contains("127.0.0.")
+ || message.contains("::1/") || message.contains("192.0.2.")),
+ () -> "the warning never names a configured range: " + warnings);
+ } else {
+ assertTrue(warnings.isEmpty(), () -> label + " must stay silent, got: " + warnings);
+ }
+ }
+
+ @Test
+ @DisplayName("Should warn once per combination when passthrough_sni meets both an acting action and a loopback proxy")
+ void shouldWarnOncePerPassthroughSourceCollapseCombination() {
+ GatewayConfig gateway = validGateway()
+ .enumerationDetection(detection(true, EnumerationDetectionConfig.Action.BLOCK))
+ .tls(TlsConfig.builder().passthroughSni(Map.of("secure.example.com", "SECURE")).build())
+ .forwarded(ForwardedConfig.builder().trustedProxies(List.of("127.0.0.0/8")).build())
+ .build();
+ EndpointConfig endpoint = endpoint("orders", "ORDERS", List.of(), routeConfig("r", HttpMethod.GET));
+
+ List errors = validator.validate(gateway, List.of(endpoint), topologyWith("ORDERS", "SECURE"));
+
+ assertTrue(errors.isEmpty(), () -> "the combination boots, got: " + errors);
+ List warnings = TestLoggerFactory.getTestHandler()
+ .resolveLogMessagesContaining(TestLogLevel.WARN, PASSTHROUGH_SOURCE_COLLAPSE_ID).stream()
+ .map(LogRecord::getMessage).toList();
+ assertEquals(2, warnings.size(), () -> "one warning per combination, got: " + warnings);
+ assertTrue(warnings.stream().anyMatch(message -> message.contains("enumeration_detection.action is block"))
+ && warnings.stream().anyMatch(message -> message.contains("holds a loopback range")),
+ () -> "each combination is named by its own token: " + warnings);
+ }
+
@Test
@DisplayName("Should reject a route whose match.host collides case-insensitively with a passthrough_sni host")
void shouldRejectRouteHostCollidingWithPassthroughSni() {
diff --git a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ManagementListenerTransportTest.java b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ManagementListenerTransportTest.java
index 051ff4b60..6b428b504 100644
--- a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ManagementListenerTransportTest.java
+++ b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ManagementListenerTransportTest.java
@@ -45,6 +45,8 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* The transport bounds that act on the management interface, observed on a live management listener.
@@ -55,13 +57,19 @@
* listener options ({@code HttpServerOptionsUtils.applyCommonOptionsForManagementInterface}) — the
* header block, the request line, the chunk and three form limits — and the body size, which the body
* handler Quarkus installs on every management route enforces. The shipped
- * {@code application.properties} sets the header block to the main listener's 16 KiB and keeps every
- * other bound at its default. Quarkus applies no HTTP/2 setting to the management listener at all.
+ * {@code application.properties} sets the header block to the main listener's 16 KiB and the body to
+ * 32 KiB, and keeps every other bound at its default. Quarkus applies no HTTP/2 setting to the
+ * management listener at all.
*
* Every bound but the chunk is shown by a request past it, which is refused, and a matched request
* under or at it, which the liveness probe serves; for HTTP/2 the announced setting is read instead.
- * The header-block case is the one the shipped key changes: under the 20 KiB Quarkus default it would
- * serve the request that is refused here. The request-line case pins a transport default the shipped
+ * The header-block and body cases are the two the shipped keys change: under the 20 KiB header and
+ * 10 MiB body Quarkus defaults each would serve the request that is refused here. Each listed default
+ * SmallRye Health route ({@code health}, {@code health/live}, {@code health/ready},
+ * {@code health/started}, {@code health/group}, {@code health/well}) and the {@code metrics} route
+ * still answers a body-less {@code GET} at the body bound, and the form
+ * and chunk cases below stay green under it, which is what shows the body bound pre-empts none of
+ * them. The request-line case pins a transport default the shipped
* file relies on. The HTTP/2 case reads the header-list size the listener announces to a
* prior-knowledge client: the transport's 8 KiB, not the main listener's 16 KiB.
*
@@ -76,7 +84,7 @@
* its {@code =}; the refused form is such a name, while a name followed by its {@code =} is decoded at
* once and never held. The body size is refused with a {@code 413} on the declared
* {@code Content-Length} alone, before any body byte is read, and the control carries a body of exactly
- * the 10 MiB Quarkus default.
+ * the shipped 32 KiB.
*
* The chunk bound refuses nothing, and that is what is asserted: a chunk twice its 8 KiB is served. The
* codec delivers a larger chunk to the server in pieces of at most that size; the pieces are reassembled
@@ -116,8 +124,8 @@ class ManagementListenerTransportTest {
/** The chunk bound of the management listener: the transport default, kept by the shipped file. */
private static final int CHUNK_BOUND = 8 * 1024;
- /** The body bound of the management routes: the Quarkus default of 10240 KiB, kept by the shipped file. */
- private static final int BODY_BOUND = 10 * 1024 * 1024;
+ /** The body bound of the management routes: the 32 KiB the shipped file sets, below the 10 MiB Quarkus default. */
+ private static final int BODY_BOUND = 32 * 1024;
/** How far past, or short of, a bound the refused and the served request lie. */
private static final int MARGIN = 512;
@@ -240,15 +248,32 @@ void servesAChunkPastTheChunkBound() throws Exception {
}
@Test
- @DisplayName("refuses a declared body past the 10 MiB default with 413, and serves a body of exactly 10 MiB")
- void boundsTheBodyAtTheQuarkusDefault() throws Exception {
+ @DisplayName("refuses a declared body past the shipped 32 KiB with 413, and serves a body of exactly 32 KiB")
+ void boundsTheBodyAtTheShippedBound() throws Exception {
int refused = statusOf(requestDeclaringBodyOf(BODY_BOUND + 1));
int served = statusOf(requestWithBodyOf(BODY_BOUND));
assertAll("the management router's body size",
() -> assertEquals(PAYLOAD_TOO_LARGE, refused,
- "a declared body past 10 MiB is refused before a body byte is read"),
- () -> assertEquals(OK, served, "control: a body of exactly 10 MiB is served"));
+ "a declared body one byte past 32 KiB is refused before a body byte is read"),
+ () -> assertEquals(OK, served, "control: a body of exactly 32 KiB is served"));
+ }
+
+ @ParameterizedTest(name = "GET {0}")
+ @ValueSource(strings = {"health", "health/live", "health/ready", "health/started", "health/group",
+ "health/well", "metrics"})
+ @DisplayName("answers a body-less GET on each listed default SmallRye Health and metrics route with 200 under the body bound")
+ void servesEveryProbeRouteABodylessGet(String route) throws Exception {
+ assertEquals(OK, statusOf(bodylessGetOf(route)),
+ "the probe route " + route + " is served: no probe needs a body the bound could refuse");
+ }
+
+ /**
+ * @param route the probe route, relative to the management root path
+ * @return a body-less GET of that route
+ */
+ private String bodylessGetOf(String route) {
+ return "GET " + managementPath(route) + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
}
/**
@@ -329,8 +354,16 @@ private String requestWithLineOf(int lineBytes) {
/** @return the liveness probe beneath the management root path */
private String livenessPath() {
+ return managementPath(LIVENESS_PATH);
+ }
+
+ /**
+ * @param route a route relative to the management root path
+ * @return that route beneath the management root path
+ */
+ private String managementPath(String route) {
String root = managementUrl.getPath();
- return (root.endsWith("/") ? root : root + "/") + LIVENESS_PATH;
+ return (root.endsWith("/") ? root : root + "/") + route;
}
/**
diff --git a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ShippedApplicationPropertiesTest.java b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ShippedApplicationPropertiesTest.java
index 60d91411c..3d7b5e8b3 100644
--- a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ShippedApplicationPropertiesTest.java
+++ b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/quarkus/ShippedApplicationPropertiesTest.java
@@ -76,8 +76,8 @@
* Deleting the key turns this class red; {@code MainListenerConnectionCapTest} proves the key acts on
* the listener.
*
- * For the management interface it guards the header-block key the shipped file sets and the idle-reap
- * key it leaves unset, {@code quarkus.management.idle-timeout}, so that listener keeps the Quarkus
+ * For the management interface it guards the header-block and body keys the shipped file sets and the
+ * idle-reap key it leaves unset, {@code quarkus.management.idle-timeout}, so that listener keeps the Quarkus
* default idle reap.
*
* @author API Sheriff Team
@@ -100,6 +100,8 @@ class ShippedApplicationPropertiesTest {
private static final String MANAGEMENT_MAX_HEADER_SIZE = "quarkus.management.limits.max-header-size";
+ private static final String MANAGEMENT_MAX_BODY_SIZE = "quarkus.management.limits.max-body-size";
+
private static final String MANAGEMENT_IDLE_TIMEOUT = "quarkus.management.idle-timeout";
/** The shipped connection cap as a multiple of the default admission cap (the documented headroom). */
@@ -211,6 +213,26 @@ void packagedFileDeclaresTheManagementHeaderBlockBound() throws Exception {
+ "or the management listener keeps the 20 KiB Quarkus default above the main listener's bound");
}
+ /**
+ * The management interface's body bound. No management route reads a request body, so without
+ * {@code quarkus.management.limits.max-body-size} the body handler on every management route would
+ * buffer up to the 10 MiB Quarkus default for nothing. It is held at 32 KiB, the smallest power of two
+ * above every body the form and chunk bounds must see to answer on their own terms;
+ * {@code ManagementListenerTransportTest} proves the key acts on the listener.
+ */
+ @Test
+ @DisplayName("The packaged file bounds the management interface's request body at 32 KiB")
+ void packagedFileDeclaresTheManagementBodyBound() throws Exception {
+ Properties shipped = new Properties();
+ try (Reader reader = Files.newBufferedReader(PACKAGED_APPLICATION_PROPERTIES, StandardCharsets.UTF_8)) {
+ shipped.load(reader);
+ }
+
+ assertEquals("32K", shipped.getProperty(MANAGEMENT_MAX_BODY_SIZE),
+ () -> MANAGEMENT_MAX_BODY_SIZE + " must stay declared at 32K in the shipped application.properties, "
+ + "or every management route buffers a request body up to the 10 MiB Quarkus default");
+ }
+
/**
* The management interface's idle reap. {@code quarkus.management.idle-timeout} is not part of the
* {@code quarkus.management.limits.*} family the shipped file bounds the management listener through,
diff --git a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/tls/SniFrontListenerTest.java b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/tls/SniFrontListenerTest.java
index cccc6ea3d..d7c240516 100644
--- a/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/tls/SniFrontListenerTest.java
+++ b/api-sheriff/src/test/java/de/cuioss/sheriff/gateway/tls/SniFrontListenerTest.java
@@ -141,6 +141,75 @@ void mappedSniRelaysToPassthroughBackend() throws Exception {
Awaits.teardown(front.stop(), "the SNI front listener to stop");
}
+ /**
+ * The relay's INFO audit record names the key the passthrough route matched, never the raw
+ * ClientHello value: a server name padded with whitespace — CR and LF included — still selects
+ * the configured host, and the record carries that host without the padding, so a client cannot
+ * write a line break of its own into the audit log.
+ */
+ @ParameterizedTest(name = "padded server name #{index}")
+ @ValueSource(strings = {" " + MAPPED_SNI + "\r\n", "\r\n" + MAPPED_SNI + "\r\n", "\t" + MAPPED_SNI + " \n"})
+ @DisplayName("audits a padded server name under the configured host it matched, without the padding")
+ void auditsAPaddedServerNameUnderTheMatchedKey(String paddedServerName) throws Exception {
+ byte[] hello = ClientHelloFixture.withSni(paddedServerName);
+ Backend passthrough = startBackend(hello.length);
+ Backend terminated = startBackend(hello.length);
+ SniFrontListener front = startFront(Map.of(MAPPED_SNI, passthrough.target()), terminated.target());
+
+ sendToFront(front, hello);
+
+ Buffer received = Awaits.connect(passthrough.firstBytes(),
+ "the passthrough backend to receive the relayed bytes");
+ List audited = awaitRelayAudit();
+ assertAll("the padded server name is routed and audited under the matched key",
+ () -> assertEquals(Buffer.buffer(hello), received,
+ "the padded server name still selects the passthrough backend"),
+ () -> assertEquals(1, audited.size(), "one passthrough relay was audited"),
+ () -> assertEquals(relayAudit(MAPPED_SNI, passthrough.target()), audited.getFirst().getMessage(),
+ "the audit record carries the configured host, not the client's padded value"));
+ Awaits.teardown(front.stop(), "the SNI front listener to stop");
+ }
+
+ /** Matched control: an exact configured host is audited exactly as it was sent. */
+ @Test
+ @DisplayName("audits an exact configured host unchanged")
+ void auditsAnExactServerNameUnchanged() throws Exception {
+ byte[] hello = ClientHelloFixture.withSni(MAPPED_SNI);
+ Backend passthrough = startBackend(hello.length);
+ Backend terminated = startBackend(hello.length);
+ SniFrontListener front = startFront(Map.of(MAPPED_SNI, passthrough.target()), terminated.target());
+
+ sendToFront(front, hello);
+
+ Awaits.connect(passthrough.firstBytes(), "the passthrough backend to receive the relayed bytes");
+ List audited = awaitRelayAudit();
+ assertAll("the exact host is audited unchanged",
+ () -> assertEquals(1, audited.size(), "one passthrough relay was audited"),
+ () -> assertEquals(relayAudit(MAPPED_SNI, passthrough.target()), audited.getFirst().getMessage(),
+ "the audit record carries the host exactly as configured and sent"));
+ Awaits.teardown(front.stop(), "the SNI front listener to stop");
+ }
+
+ /**
+ * Waits until the relay has written its INFO audit record — the relay logs it once the session
+ * started, which a backend that already read the ClientHello can observe before the line is
+ * written — and returns every such record.
+ */
+ private static List awaitRelayAudit() throws Exception {
+ Awaits.until(() -> !relayAuditLines().isEmpty(), "the relay to write its INFO audit record",
+ Awaits.CONNECT_CEILING_SECONDS);
+ return relayAuditLines();
+ }
+
+ private static List relayAuditLines() {
+ return TestLoggerFactory.getTestHandler().resolveLogMessagesContaining(TestLogLevel.INFO,
+ "Passthrough relay established for SNI");
+ }
+
+ private static String relayAudit(String sniKey, RelayTarget target) {
+ return ApiSheriffLogMessages.INFO.PASSTHROUGH_RELAY_ESTABLISHED.format(sniKey, target.toString());
+ }
+
@Test
@DisplayName("routes a non-matching SNI to the terminated-strict path")
void nonMatchingSniRelaysToTerminatedBackend() throws Exception {
@@ -396,6 +465,11 @@ void warnsOncePerWindowPerReason() throws Exception {
() -> assertEquals(1, warnings.size(), "only the first refusal of the window is a WARN"),
() -> assertTrue(warnings.getFirst().getMessage().contains("(cap)"),
"the WARN names the reason token: " + warnings.getFirst().getMessage()),
+ () -> assertTrue(warnings.getFirst().getMessage().contains(
+ "(cap) at accept, without reading from the connection:"),
+ "the WARN places a cap refusal at accept: " + warnings.getFirst().getMessage()),
+ () -> assertFalse(warnings.getFirst().getMessage().contains("route decision"),
+ "a cap refusal's WARN names no other stage: " + warnings.getFirst().getMessage()),
() -> assertFalse(warnings.getFirst().getMessage().contains(HOST),
"the WARN never names the peer address: " + warnings.getFirst().getMessage()),
() -> assertEquals(2, debugLines("Front connection refused (cap)").size(),
@@ -469,8 +543,16 @@ void recordsEveryRefusalWithItsReason() throws Exception {
() -> assertEquals(2, warnings.size(), "each reason opens its own warn window"),
() -> assertTrue(warnings.get(0).getMessage().contains("(source_share)"),
"the share refusal names its reason: " + warnings.get(0).getMessage()),
+ () -> assertTrue(warnings.get(0).getMessage().contains(
+ "(source_share) at accept, without reading from the connection:"),
+ "the share refusal is placed at accept: " + warnings.get(0).getMessage()),
+ () -> assertFalse(warnings.get(0).getMessage().contains("route decision"),
+ "the share refusal names no other stage: " + warnings.get(0).getMessage()),
() -> assertTrue(warnings.get(1).getMessage().contains("(cap)"),
- "the cap refusal names its reason: " + warnings.get(1).getMessage()));
+ "the cap refusal names its reason: " + warnings.get(1).getMessage()),
+ () -> assertTrue(warnings.get(1).getMessage().contains(
+ "(cap) at accept, without reading from the connection:"),
+ "the cap refusal is placed at accept: " + warnings.get(1).getMessage()));
Awaits.teardown(front.stop(), "the SNI front listener to stop");
}
@@ -546,6 +628,27 @@ void aSaturatedSourceIsRefusedForItsShareWhileTheCapIsFull() throws Exception {
Awaits.teardown(front.stop(), "the SNI front listener to stop");
}
+ /**
+ * The record takes the reason and its stage from the refusal being logged, so the template itself
+ * names neither: formatted with neutral arguments, it carries no reason token and no stage of any
+ * {@link Refusal}. A reason added to the enum is covered without touching this case.
+ */
+ @Test
+ @DisplayName("the refusal WARN template names no reason and no stage of its own")
+ void theTemplateEnumeratesNoReason() {
+ String formatted = ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED.format("reason", "stage", "1", "60");
+
+ assertAll("every reason and stage reaches the line through a parameter",
+ () -> assertTrue(formatted.contains("(reason) stage: a bound of 1 connections is full"),
+ "the token and the stage are the first two parameters: " + formatted),
+ () -> assertTrue(Arrays.stream(Refusal.values()).noneMatch(r -> formatted.contains(r.token())),
+ "the template names no reason token: " + formatted),
+ () -> assertTrue(Arrays.stream(Refusal.values()).noneMatch(r -> formatted.contains(r.stage())),
+ "the template names no stage: " + formatted),
+ () -> assertTrue(Arrays.stream(Refusal.values()).noneMatch(r -> r.stage().isBlank()),
+ "every reason carries a stage to log"));
+ }
+
@Test
@DisplayName("closes a refused connection even when recording the refusal throws")
void closesTheRefusedConnectionWhenTheRecorderThrows() throws Exception {
@@ -569,21 +672,6 @@ void closesTheRefusedConnectionWhenTheRecorderThrows() throws Exception {
() -> assertFalse(held.closedNanos().isDone(), "the connection holding the cap stays open"));
Awaits.teardown(front.stop(), "the SNI front listener to stop");
}
-
- private static List refusalWarnings() {
- return TestLoggerFactory.getTestHandler().resolveLogMessagesContaining(TestLogLevel.WARN,
- ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED.resolveIdentifierString());
- }
-
- /**
- * A source key that assigns the accepted connections, in accept order, to the given sources,
- * and every connection beyond them to the last one. One front server handles its connections
- * on one event loop, so accept order is the order this test connects in.
- */
- private static Function sourcesInOrder(String... sources) {
- AtomicInteger accepted = new AtomicInteger();
- return socket -> sources[Math.min(accepted.getAndIncrement(), sources.length - 1)];
- }
}
/**
@@ -938,7 +1026,7 @@ void aDarkTargetLeavesTheCapToTerminatedHandshakes() throws Exception {
Offer secondHandshake = offer(front, terminatedHello);
awaitRefusals(2);
- List warnings = RefusalsAtAccept.refusalWarnings();
+ List warnings = refusalWarnings();
assertAll("the dark target took its budget of the cap and no more",
() -> assertEquals(List.of(true, true, false, false), admitted(darkDials),
"the target's first two dials are admitted, the two beyond its budget refused"),
@@ -954,6 +1042,13 @@ void aDarkTargetLeavesTheCapToTerminatedHandshakes() throws Exception {
() -> assertTrue(warnings.getFirst().getMessage().contains("bound of " + BUDGET + " "),
"the WARN names the budget as the bound that was full: "
+ warnings.getFirst().getMessage()),
+ () -> assertTrue(warnings.getFirst().getMessage().contains(
+ "(dial_budget) at its route decision, before its backend is dialled:"),
+ "the WARN places a dial_budget refusal at the route decision: "
+ + warnings.getFirst().getMessage()),
+ () -> assertFalse(warnings.getFirst().getMessage().contains("at accept"),
+ "the WARN does not place a dial_budget refusal at accept: "
+ + warnings.getFirst().getMessage()),
() -> assertFalse(darkDials.getFirst().leg().closedNanos().isDone(),
"an admitted dial is still pending, its connection open"));
Awaits.teardown(front.stop(), "the SNI front listener to stop");
@@ -1129,7 +1224,7 @@ private SniFrontListener startDarkLoadFront(RelayTarget darkTarget, RelayTarget
Arrays.fill(sources, 0, CAP, DARK_SOURCE);
sources[CAP] = HANDSHAKE_SOURCE;
return startFront(relay, Map.of(MAPPED_SNI, darkTarget), terminatedTarget, DEADLINE, CAP, dialBudget,
- RefusalsAtAccept.sourcesInOrder(sources));
+ sourcesInOrder(sources));
}
/** A front of {@link #CAP} whose one passthrough target has a dial budget of one. */
@@ -1663,7 +1758,7 @@ void emptiesAfterADialFailure() throws Exception {
void emptiesAfterADialBudgetRefusal() throws Exception {
Backend passthrough = startBackend(hello.length);
SniFrontListener front = startHeldDialFront(vertx.createNetClient(), passthrough.target(), 4, 1,
- RefusalsAtAccept.sourcesInOrder("holder", "refused"));
+ sourcesInOrder("holder", "refused"));
routeWithAHeldDial(front);
int whileHeld = front.sourcesHoldingSlots();
@@ -1687,7 +1782,7 @@ void emptiesAfterADialBudgetRefusal() throws Exception {
void emptiesAfterACapRefusal() throws Exception {
Backend terminated = startBackend(1);
SniFrontListener front = startFront(Map.of(), terminated.target(), LONG_DEADLINE, 1, 1, LONG_IDLE,
- LONG_IDLE, System::nanoTime, RefusalsAtAccept.sourcesInOrder("holder", "refused"));
+ LONG_IDLE, System::nanoTime, sourcesInOrder("holder", "refused"));
ClientLeg holder = connectClient(front);
int whileHeld = awaitSourcesHolding(front, 1);
@@ -1767,6 +1862,26 @@ private static List debugLines(String text) {
return TestLoggerFactory.getTestHandler().resolveLogMessagesContaining(TestLogLevel.DEBUG, text);
}
+ /**
+ * Every {@code WARN} {@link ApiSheriffLogMessages.WARN#FRONT_CONNECTION_REFUSED} record logged so far,
+ * whatever its reason: a {@code cap} or {@code source_share} refusal at accept, or a
+ * {@code dial_budget} refusal at the route decision.
+ */
+ private static List refusalWarnings() {
+ return TestLoggerFactory.getTestHandler().resolveLogMessagesContaining(TestLogLevel.WARN,
+ ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED.resolveIdentifierString());
+ }
+
+ /**
+ * A source key that assigns the accepted connections, in accept order, to the given sources,
+ * and every connection beyond them to the last one. One front server handles its connections
+ * on one event loop, so accept order is the order a case connects in.
+ */
+ private static Function sourcesInOrder(String... sources) {
+ AtomicInteger accepted = new AtomicInteger();
+ return socket -> sources[Math.min(accepted.getAndIncrement(), sources.length - 1)];
+ }
+
private SniFrontListener startFront(Map targets, RelayTarget terminatedTarget)
throws Exception {
return startFront(targets, terminatedTarget, SniFrontListener.CLIENT_HELLO_DEADLINE,
diff --git a/deployment/compose-sample/docker/sheriff-config-auth-fronted/endpoints/idp.yaml b/deployment/compose-sample/docker/sheriff-config-auth-fronted/endpoints/idp.yaml
index d2e9ba913..6c052cbdc 100644
--- a/deployment/compose-sample/docker/sheriff-config-auth-fronted/endpoints/idp.yaml
+++ b/deployment/compose-sample/docker/sheriff-config-auth-fronted/endpoints/idp.yaml
@@ -20,7 +20,13 @@
# travel the back channel (oidc.back_channel_origin in gateway.yaml) and the JWKS URL names the
# internal keycloak:8443 address, so neither needs a front-side route, and the sample's browser
# client performs no OIDC or RFC 8414 discovery of its own. That holds by construction: no rule has
-# to recognise a dangerous path, because a path nobody listed has no way in.
+# to recognise a dangerous path, because a path outside the four listed prefixes has no way in.
+#
+# Each route is a segment-prefix route, so the allowlist is four namespaces, not four addresses: every
+# sub-path of a listed prefix passes to Keycloak — /auth/realms/sample/login-actions/,
+# /auth/resources/ — and what Keycloak serves under such a sub-path is reachable through the
+# gateway. A path that is neither a listed prefix nor below one, segment by segment, is answered the
+# unrouted 404 (/auth/realms/sample/login-actionsX is not below /auth/realms/sample/login-actions).
#
# Every request is canonicalised BEFORE route selection. A dot-segment, an encoded separator, a
# doubled slash or a backslash — /auth/realms/sample/login-actions/../../../admin/,
diff --git a/doc/LogMessages.adoc b/doc/LogMessages.adoc
index 0c8dc8cd3..053a26358 100644
--- a/doc/LogMessages.adoc
+++ b/doc/LogMessages.adoc
@@ -105,12 +105,13 @@ diagnostics use the logger directly and are not catalogued.
|ApiSheriff-143 |EDGE |Source '%s' on host '%s' reached the threat classification threshold — ECS alert: %s |Logged once per episode when a source's weighted rejection score reaches the `threat_classification` threshold; observation only. The values are source (as ApiSheriff-141 -- IPv4, IPv6 `/64` or `/48`, `unknown` or `unresolved-via-` followed by a trusted proxy's canonical address -- so an IPv6 source the threat ledger began tracking above its high-water mark appears as its `/48`), folded host (as ApiSheriff-141) and an ECS ALERT document (link:architecture/observability-and-errors.adoc#_threat_alert_document[the threat ALERT document]). Forward it to the SIEM, tune the threshold or weights if honest clients alert, and use `enumeration_detection` `delay` or `block` to act on a source.
|ApiSheriff-144 |EDGE |Threat classification is tracking its maximum of %s sources — a further source was left untracked and cannot raise an alert; further overflows stay at DEBUG and are counted on sheriff_threat_untracked_total |Logged once per process when the threat ledger is full (65,536 sources) and a new source cannot be scored. Further overflows are counted on `sheriff_threat_untracked_total`; a sustained rate means a distributed scan or sources that are not per client.
|ApiSheriff-145 |BFF |Pending-authorization store is full of live login records — new logins are refused with 503 until records are consumed or expire; further refusals in this episode stay at DEBUG |Logged once per saturation episode when the pending-authorization store holds its capacity of live records and a login, step-up or widening start is refused `503` with `Retry-After: 30` (`PENDING_AUTHORIZATION_SATURATED`) instead of evicting another user's live login. Carries no request data; the latch releases only once the store has drained below half its capacity, so freeing one place and refilling it does not log it again. The refusal rate is `sheriff_errors_total{event="PENDING_AUTHORIZATION_SATURATED"}`; a sustained rate means a login flood from many sources.
-|ApiSheriff-146 |EDGE |Front connection refused at accept (%s): the bound of %s undecided connections is full — further refusals for this reason within %s seconds stay at DEBUG and are counted on sheriff_front_connections_refused_total |Logged when the accept-time SNI front (active with `tls.passthrough_sni`) closes a connection at once, with one of three reason tokens. At accept, unread: `cap` (1024 connections waiting for their ClientHello or for their backend dial to settle) or `source_share` (one source — an IPv4 address, or the /64 prefix of an IPv6 address — holds its 256). At the route decision of a passthrough match, without dialing its backend: `dial_budget` (128 connections are already dialing that passthrough target; the bound logged is that 128). The template reads "at accept" for all three. At most once per 60 s per reason, repeats at DEBUG; every refusal is counted on `sheriff_front_connections_refused_total{reason}`. Never names the peer address or a received byte. Sustained `cap` means a slow-handshake flood or passthrough backends that do not answer the dial (each such connection holds its slot for any host-name lookup of the backend plus the 10 s connect timeout); `dial_budget` means 128 connections to one passthrough backend were in progress at once, usually because that backend does not answer the dial; `source_share` from all clients means an L4 load balancer hides client addresses — see link:user/tls-edge.adoc[TLS Edge].
+|ApiSheriff-146 |EDGE |Front connection refused (%s) %s: a bound of %s connections is full — further refusals for this reason within %s seconds stay at DEBUG and are counted on sheriff_front_connections_refused_total |Logged when the accept-time SNI front (active with `tls.passthrough_sni`) closes a connection at once. The values are the reason token, the stage that reason refuses at, the bound that was full and the window in seconds; the stage comes with the reason, so the line names where the refusal happened for whichever reason is logged. `cap` (1024 connections waiting for their ClientHello or for their backend dial to settle) and `source_share` (one source — an IPv4 address, or the /64 prefix of an IPv6 address — holds its 256) are logged with the stage `at accept, without reading from the connection`. `dial_budget` (128 connections are already dialing that passthrough target; the bound logged is that 128) is logged with the stage `at its route decision, before its backend is dialled`. At most once per 60 s per reason, repeats at DEBUG; every refusal is counted on `sheriff_front_connections_refused_total{reason}`. Never names the peer address or a received byte. Sustained `cap` means a slow-handshake flood or passthrough backends that do not answer the dial (each such connection holds its slot for any host-name lookup of the backend plus the 10 s connect timeout); `dial_budget` means 128 connections to one passthrough backend were in progress at once, usually because that backend does not answer the dial; `source_share` from all clients means an L4 load balancer hides client addresses — see link:user/tls-edge.adoc[TLS Edge].
|[[apisheriff-147]]ApiSheriff-147 |BFF |Logout could not revoke the session's refresh token at the identity provider — the gateway session is ended and the refresh token stays valid at the provider until it expires; further failures stay at DEBUG |Logged once per runtime when RP-initiated logout cannot revoke the session's refresh token (RFC 7009): a transport failure, a non-success answer from the `revocation_endpoint`, or provider metadata that could not be obtained. The logout completes as usual; the refresh token stays valid at the IdP until it expires. Carries no value and no exception; the DEBUG line beside it names only the exception types of the failure's cause chain, never the exception or its message, since that may hold the refresh token; repeats at DEBUG. A session without a refresh token, or an IdP without a `revocation_endpoint`, sends nothing and is not logged here. Check that the IdP's revocation endpoint is reachable under the `egress_tls.oidc_*` posture and `oidc.back_channel_origin`.
|[[apisheriff-148]]ApiSheriff-148 |CONFIG |edge_hardening.admission_cap is %s, which is above half the connection cap of %s open connections (quarkus.http.limits.max-connections) — on HTTP/1.1 every request holds a connection and the cap also counts connections carrying no admitted request, so the cap can close connections unserved, without a 503, before admission refuses a request. Keep edge_hardening.admission_cap at or below %s, or raise quarkus.http.limits.max-connections in the deployment together with the container's nofile limit |Logged once at startup when the configured `edge_hardening.admission_cap` is above half the connection cap of the Quarkus-terminated listener (shipped as 4096, twice the default admission cap, set in `application.properties`, not in `gateway.yaml`). A warning, not a boot refusal: a deployment that raises the connection cap, or serves mostly HTTP/2, may want the larger value; the configured number is never capped silently. The arguments are the admission cap, the connection cap, and half the connection cap as the value to stay at or below. See link:user/edge-security.adoc#_edge_hardening_defaults[Edge hardening defaults].
|[[apisheriff-149]]ApiSheriff-149 |CONFIG |enumeration_detection.action is %s while forwarded.trusted_proxies is non-empty — a request a trusted proxy forwards without a Forwarded or X-Forwarded-For header, or with only blank ones, is keyed on the shared source 'unknown', which detection counts and reports but never blocks, delays or refuses, so such requests escape the configured action. Make sure every trusted proxy sends its clients' addresses in X-Forwarded-For |Logged by the configuration validation rule that judges `forwarded.trusted_proxies`, when `enumeration_detection` is enabled with action `block` or `delay` and `forwarded.trusted_proxies` is non-empty; it is therefore emitted each time the configuration is validated, at startup and in a `--validate-config` run. A trusted proxy's request that carries no `Forwarded` or `X-Forwarded-For` header, or only blank ones, is keyed on `unknown`, which is counted, trips and is reported (ApiSheriff-141) but is never answered `429`, delayed or refused. A request whose header carries a non-blank value from which no client resolves is keyed on that proxy's own unresolved source (`unresolved-via-` followed by the proxy's canonical address) and acted on like any source. A warning, not a boot refusal; the argument is the action, never an address. Confirm every trusted proxy sends a usable `X-Forwarded-For`.
|[[apisheriff-150]]ApiSheriff-150 |CONFIG |oidc.session.mode is server and oidc.logout.backchannel_path is declared — a back-channel logout ends sessions only in the in-memory session store of the replica that receives it, and that replica answers 200 even when it ended none. Behind several replicas, a session held by another replica stays alive after the identity provider ended it, and nothing reports it. No gateway.yaml key declares the replica count, so this is reported on every such boot: where back-channel revocation must reach every session, run a single replica |Logged by the configuration validation rule that judges the `oidc` session settings, when `oidc.session.mode` is `server` and `oidc.logout.backchannel_path` is declared; it is therefore emitted each time the configuration is validated, at startup and in a `--validate-config` run. The server-mode session store is per process, so a back-channel logout ends the matching sessions on the replica that receives the logout token only. The gateway cannot see how many replicas run, so the record is emitted on every such validation, single replica included; it is silent in cookie mode, which serves no back-channel path, and when no `backchannel_path` is declared. Never a refusal. The template carries no parameter: no path, issuer, session or subject. See link:user/bff-session.adoc#multi-replica[Running more than one replica].
|[[apisheriff-151]]ApiSheriff-151 |EDGE |Reporting circuit breaker for upstream '%s' entering %s failed — the breaker state changed, its transition record or metric may be missing |Logged, with the exception, when the state-change consumer of an upstream circuit breaker throws while a transition is reported. The breaker has already entered the state; the call that caused the transition keeps its own answer or failure, and a call admitted as a half-open trial still runs, so only the report is lost — the transition's own record (ApiSheriff-103 / ApiSheriff-104) and, on an open, its count. The arguments are the breaker name (`scheme://host:port:h2=:retry=`) and the state entered. Not expected in operation: the installed consumer only counts and logs.
+|[[apisheriff-152]]ApiSheriff-152 |CONFIG |tls.passthrough_sni is non-empty while %s — behind the SNI front every terminated connection reaches the edge from the loopback relay leg, so source detection and the trusted-proxy judgement see every terminated client as that one loopback peer: an acting detection action blocks or delays all of them at once, and a loopback trusted proxy trusts every client's own forwarded headers. For the combination named here, set enumeration_detection.action to observe, or remove the loopback range from forwarded.trusted_proxies |Logged by the configuration validation rule that judges the passthrough topology, once for each present combination, when `tls.passthrough_sni` is non-empty and either `enumeration_detection` is enabled with action `block` or `delay` (argument `enumeration_detection.action is block` / `... is delay`) or a `forwarded.trusted_proxies` range holds a loopback address -- overlapping `127.0.0.0/8`, or containing `::1` (argument `forwarded.trusted_proxies holds a loopback range`); it is therefore emitted each time the configuration is validated, at startup and in a `--validate-config` run. Behind the SNI front every terminated connection reaches the edge from the loopback relay leg, so, while no loopback address is a trusted proxy, every terminated client shares one source: one client's rejections trip it and the block or delay it earns acts on all of them, and a loopback trusted proxy makes every client's own `Forwarded` / `X-Forwarded-For` trusted. A warning, not a boot refusal; the argument is a fixed token, never a range or an address. Keep `enumeration_detection.action` at `observe` and keep loopback out of `forwarded.trusted_proxies` in a passthrough topology. See link:configuration/security-and-edge-hardening.adoc[Security and Edge Hardening].
|===
== ERROR Level (200-299)
diff --git a/doc/adr/0003-forwarded-headers.adoc b/doc/adr/0003-forwarded-headers.adoc
index 5cb91eb22..5c31f0dab 100644
--- a/doc/adr/0003-forwarded-headers.adoc
+++ b/doc/adr/0003-forwarded-headers.adoc
@@ -93,8 +93,14 @@ declares a proxy's managed family (see <<_a_family_accept_setting>>), so no requ
*The per-source keys of an unresolved chain.* A trusted proxy's request whose `X-Forwarded-For` or
`Forwarded` carries a value from which no client resolves -- a disagreeing pair, a malformed chain, a
value sanitization drops, a client named by something other than an address -- is keyed by per-source detection and by the BFF pending-login quota on that
-proxy's own source, `unresolved-via-` followed by the proxy's canonical address. Detection acts on it
-like on any source, because a client can always produce such a header. Only a request carrying no such
+proxy's own source, `unresolved-via-` followed by the proxy's canonical address. The canonical address
+of an IPv4 proxy is its address, so each IPv4 trusted proxy has a source of its own; that of an IPv6
+proxy is its /64 prefix, so every IPv6 trusted proxy in one /64 shares one such source. Every request
+whose chain resolves no client and that arrives through a proxy with that canonical address shares
+the source, whichever client sent it. Detection tracks and acts on the pair of that source and the
+request's folded host, like on any source, because a client can always produce such a header: a
+block or a delay the pair earns acts on every request keyed on both that unresolved source and that
+folded host. Only a request carrying no such
value at all, or only blank ones, is keyed on the shared `unknown` source, which detection counts but never acts on.
*The judged value.* The resolver joins every instance of a header with `", "` and sanitizes the joined
@@ -156,7 +162,7 @@ RFC 7239 section 6.3 suggests obfuscated identifiers to avoid leaking internal t
=== Accepted costs
-* A trusted proxy that does not manage `X-Forwarded-*` is unsupported, and no setting covers that deployment. Passing a client's `X-Forwarded-For` through unchanged hands the spoofed chain the win. Appending only to `Forwarded` makes a client-sent `X-Forwarded-For` contest the chain: no client resolves, and every such request through that proxy shares the proxy's unresolved source.
+* A trusted proxy that does not manage `X-Forwarded-*` is unsupported, and no setting covers that deployment. Passing a client's `X-Forwarded-For` through unchanged hands the spoofed chain the win. Appending only to `Forwarded` makes a client-sent `X-Forwarded-For` contest the chain: no client resolves, and every such request shares the proxy's unresolved source -- its own for an IPv4 proxy, the one of its /64 for an IPv6 proxy, shared with every trusted proxy in that /64.
== Links
diff --git a/doc/adr/0043-Compress-then-encrypt_in_the_sealed_session_cookie_and_the_CRIME_BREACH_discriminator.adoc b/doc/adr/0043-Compress-then-encrypt_in_the_sealed_session_cookie_and_the_CRIME_BREACH_discriminator.adoc
index dfa0d545f..c65244bba 100644
--- a/doc/adr/0043-Compress-then-encrypt_in_the_sealed_session_cookie_and_the_CRIME_BREACH_discriminator.adoc
+++ b/doc/adr/0043-Compress-then-encrypt_in_the_sealed_session_cookie_and_the_CRIME_BREACH_discriminator.adoc
@@ -9,7 +9,7 @@
// Progressive-disclosure metadata block (see manage-adr SKILL.md → "ADR Template
// Structure"). Read by `manage-adr.py scan` so a caller can assess an ADR's
// relevance without reading the full file. List fields are comma-separated.
-// summary: The cookie-based BFF deflates its session payload before it seals it, because the two conditions that make compress-then-encrypt dangerous — repeated samples of one secret and attacker-chosen plaintext adjacent to it — do not hold for this construction (cross-site re-seals carry fresh tokens, and the only attacker influence is which declared scope names enter), and both are named here so a future change that reintroduces either knows it has reversed the decision.
+// summary: The cookie-based BFF deflates its session payload before it seals it, because the two conditions that make compress-then-encrypt dangerous — repeated samples of one secret and attacker-chosen plaintext adjacent to it — do not hold for this construction (cross-site re-seals carry a freshly issued access token, a repeated ID token sits next to no attacker-varied byte, and the only attacker influence is which scope names the identity provider returns), and both are named here so a future change that reintroduces either knows it has reversed the decision.
// tags: compression, side-channels, cookie-session, sealed-wire-format, bff, crime, breach
// affects: api-sheriff
// supersedes:
@@ -71,20 +71,25 @@ the material, and the merge of a widening.
A compression oracle needs many seals of the same secret, each next to bytes the attacker varies, and an observer of
their lengths. The seals a cross-site request drives meet none of these conditions:
-* *Every re-seal carries freshly issued tokens.* A refresh and a widening both store the token response the identity
- provider just issued, so no two seals compress the same access token.
-* *The stable secret cannot be probed.* The session nonce stays the same across re-seals, but no attacker-varied byte
- sits next to it in the compression context. The only attacker influence on the plaintext is which scope names enter
- it (half two).
-* *Samples are bounded by monotone scope growth.* A widening only adds scope names, and only names the operator
- declared on a route and the identity provider grants. A name once in the session stays there, so the distinct
- plaintexts an attacker can cause are bounded by the declared scope set, not by the number of requests it sends.
+* *Every re-seal carries a freshly issued access token.* A refresh and a widening both store the access token of the
+ token response the identity provider just issued, so each seal compresses an access token no earlier seal carried.
+* *The stable secrets cannot be probed.* The session nonce stays the same across re-seals, and so can the ID token: a
+ refresh response that carries no ID token keeps the previous one (`TokenRefreshCoordinator.rotate`), so two seals can
+ compress the same ID token. No attacker-varied byte sits next to either in the compression context. The only attacker
+ influence on the plaintext is which scope names enter it (half two).
+* *Samples are bounded by the scope names the identity provider returns.* A refresh replaces the active scope set with
+ the scope its token response names, or with the scopes the gateway asked for when the response names none, so the set
+ can shrink as well as grow; a widening adds the names the identity provider grants. The names come from the identity
+ provider's answer or the gateway's own request, never from the attacker's, so the distinct plaintexts an attacker can
+ cause are bounded by the scope names the identity provider returns for the session, not by the number of requests it
+ sends.
* *Reading a length needs an on-path observer of the cookie size.* The cross-site page that drives the re-seal cannot
read the `Set-Cookie` header of the gateway's origin.
=== Half two: chosen-plaintext influence
-*Can an attacker vary the plaintext next to the secret? Only by choosing which declared scope names enter it.* The
+*Can an attacker vary the plaintext next to the secret? Only by steering which scope names the identity provider returns
+enter it.* The
identity provider issues or the gateway mints each of the eleven components. None is echoed from the request that
produced it.
@@ -142,12 +147,13 @@ produced it.
| `grantedScopes`
| The identity provider, or the gateway's own request when the token names no scope
| Only in which names it holds, as for `activeScopes`. The set holds the scopes the identity provider is known to grant
- the session, and a widening only adds to it
+ the session: a widening adds to it, and a scope-driven refresh whose response leaves out a requested scope removes
+ that scope from it
(link:0057-Session_routes_obtain_their_declared_scopes_by_refreshing_inside_the_grant_and_widening_the_live_session_outside_it.adoc[ADR-0057]).
|===
No request supplies a byte of any field, so a probe string has no place to go. The most a request selects is which
-operator-declared, identity-provider-granted scope names a widening adds. That choice is drawn from a fixed, finite
+scope names the identity provider returns to a refresh or a widening it drives. That choice is drawn from a finite
vocabulary the attacker does not write, so attacker-varied bytes sharing a compression context with the secret are
absent structurally, not by a validation a later change could relax.
@@ -219,8 +225,8 @@ or relocate the payload. Only compression addresses the size without giving up a
* *The compressed length is visible.* Anyone who can see the cookie can observe the sealed size: the browser, an intermediary
that logs header sizes, and the client. After compression that size depends on the payload's content. A markedly smaller seal
carries less material, most legibly no refresh token. The signal is not actionable. It distinguishes classes of session, not
- a bit of a secret. The series of re-seals a cross-site request can drive is bounded by scope growth and carries fresh tokens
- each time, and observing it needs a position on the path. A client that can read the cookie's length already holds the
+ a bit of a secret. The series of re-seals a cross-site request can drive is bounded by the scope names the identity provider
+ returns and carries a freshly issued access token each time, and observing it needs a position on the path. A client that can read the cookie's length already holds the
cookie. This record keeps the residual, and it is no path to token material.
* *The wire format has no migration path.* An explicit version gate refuses a value sealed under an earlier format before it
constructs a cipher. Earlier cookie sessions end at the change, and the browser re-authenticates.
@@ -234,14 +240,15 @@ Either of these restores an enabling condition and makes compress-then-encrypt u
. *A payload component an attacker can influence.* A field populated from the request puts chosen plaintext into the compression
context next to three credentials. Examples are a returned URL, a client-supplied correlation id, a header echo, an IdP claim
- a downstream party can set, or a scope name that is not drawn from the operator's declared set. The deflate step must go in the
- same change.
+ a downstream party can set, or a scope name that neither the identity provider returned nor the gateway requested. The deflate
+ step must go in the same change.
. *A re-seal that keeps the same secret.* A path that produces a fresh seal without fresh token material hands the attacker
repeated samples of one secret. Examples are a "refresh my cookie" endpoint, a re-seal on every request, or a re-seal a client
parameter triggers. The other half may still hold, which is the case a reader most likely waves through.
Both reduce to one question: can a party who does not hold this session obtain repeated seals of the same secret, or choose bytes
-inside one beyond selecting declared scope names? While the answer stays no on both, the decision stands.
+inside one beyond selecting which scope names the identity provider returns? While the answer stays no on both, the decision
+stands.
=== Other risks
diff --git a/doc/adr/0076-One_per-source_detection_substrate_counts_pre-trust_rejections_and_answers_a_tripped_source.adoc b/doc/adr/0076-One_per-source_detection_substrate_counts_pre-trust_rejections_and_answers_a_tripped_source.adoc
index 646e19e78..9dfebf2a7 100644
--- a/doc/adr/0076-One_per-source_detection_substrate_counts_pre-trust_rejections_and_answers_a_tripped_source.adoc
+++ b/doc/adr/0076-One_per-source_detection_substrate_counts_pre-trust_rejections_and_answers_a_tripped_source.adoc
@@ -234,8 +234,13 @@ the one derivation the source key and the BFF's pending-login quota key share, t
combined headers once and tells a chain that resolves no client apart from no chain at all. A request
whose `Forwarded` or `X-Forwarded-For` carries a non-blank value yet resolves no client is keyed on
that proxy's own source, `unresolved-via-` followed by the proxy's canonical address, which is acted
-on like any source; only a request that
-carries neither header, or only blank ones, is `unknown`.
+on like any source. The canonical address of an IPv4 proxy is its address, so each IPv4 trusted
+proxy has a source of its own; that of an IPv6 proxy is its `/64`, so every IPv6 trusted proxy in one
+`/64` shares one such source. Every request whose chain resolves no client and that arrives through a
+proxy with that canonical address shares the source, whichever client sent it. Like every source it
+is tracked together with the request's folded host, so a block or a delay the pair earns acts on
+every request keyed on both that unresolved source and that folded host.
+Only a request that carries neither header, or only blank ones, is `unknown`.
[[amendment-unknown]]
*The `unknown` source is counted, never acted on.* `unknown` is one key for
@@ -385,7 +390,9 @@ admission.
with a non-blank value that resolves no client -- a malformed chain, one over a cap, the two
families disagreeing, or a client named by something other than an address -- is
keyed on that proxy's own unresolved source, `unresolved-via-` followed by the proxy's canonical
- address, which `block` and `delay` act on (<>).
+ address -- its own for an IPv4 proxy, shared by every IPv6 trusted proxy in one `/64` -- and
+ `block` and `delay` act on the requests sharing both that source and the folded host
+ (<>).
** Above the high-water mark a new IPv6 source is one key per `/48`, so the clients of one `/48`
share that key from then on (<>).
** A restart clears every bucket and every block. `Retry-After` describes the block on this node
diff --git a/doc/adr/0078-Per-source_threat_classification_raises_one_ECS_alert_per_episode_from_its_own_ledger.adoc b/doc/adr/0078-Per-source_threat_classification_raises_one_ECS_alert_per_episode_from_its_own_ledger.adoc
index a7702cef7..e61877c62 100644
--- a/doc/adr/0078-Per-source_threat_classification_raises_one_ECS_alert_per_episode_from_its_own_ledger.adoc
+++ b/doc/adr/0078-Per-source_threat_classification_raises_one_ECS_alert_per_episode_from_its_own_ledger.adoc
@@ -150,8 +150,8 @@ threat ALERT document]. The fixed values are these:
*The `source.ip` trap.* ECS types `source.ip` as an IP address. The key of an IPv6 source is its
`/64` prefix, a request through a trusted proxy that carries no client-address header, or only blank
-ones, is `unknown`, and a forwarded chain that resolves no client is its proxy's
-`unresolved-via-`. None of these is a valid
+ones, is `unknown`, and a forwarded chain that resolves no client is its proxy's unresolved source,
+`unresolved-via-` followed by the proxy's canonical address. None of these is a valid
`ip` value, and a SIEM would reject the document or drop the field. `source.address` therefore always carries the key text,
and `source.ip` appears only when that text is a whole IPv4 address. `url.domain` appears only for a
declared host, never for `*`.
diff --git a/doc/architecture/tls-and-inbound-security.adoc b/doc/architecture/tls-and-inbound-security.adoc
index d8bf13da0..df6770d7d 100644
--- a/doc/architecture/tls-and-inbound-security.adoc
+++ b/doc/architecture/tls-and-inbound-security.adoc
@@ -175,9 +175,9 @@ listener and the main domain-socket listener. The management interface is built
customizer, so none of them reaches it. It is bounded through the `quarkus.management.limits.*` family
in the shipped `application.properties` instead, as far as Quarkus applies that family there: its
HTTP/1.x header block at the main listener's 16 KiB, its request line (4 KiB) and chunk (8 KiB) at their
-transport defaults, which are tighter than the main listener's, and its three form limits (256 fields,
-2048 bytes per attribute, 1024 undecoded bytes) and body (10 MiB, enforced by the body handler on every
-management route) at their Quarkus defaults. Quarkus applies no HTTP/2 setting to
+transport defaults, which are tighter than the main listener's, its three form limits (256 fields,
+2048 bytes per attribute, 1024 undecoded bytes) at their Quarkus defaults, and its body at the shipped
+32 KiB, still enforced by the body handler on every management route. Quarkus applies no HTTP/2 setting to
the management listener, so it announces the transport's 8 KiB header list, keeps the transport's
stream and reset defaults and gets no connection-window sizing. Its idle reap is not part of that
family: the shipped `application.properties` sets no `quarkus.management.idle-timeout`, so the
@@ -201,7 +201,10 @@ test asserts that a chunk twice its size is served.
[[_connection_cap]]
*Connection cap.* The Quarkus-terminated side bounds its open connections with one counter,
`quarkus.http.limits.max-connections`, shared by the plain-HTTP redirect listener and the HTTPS
-listener (the SNI front listener and the management interface are not counted). The cap is set at
+listener (the SNI front listener and the management interface are not counted). It counts a
+connection on the HTTPS listener only once its TLS handshake has completed, and it has no per-source
+share: one source can hold the whole counter, and routing through the SNI front does not bound it,
+because the front's per-source share counts only the connections it has not yet handed over. The cap is set at
twice the default admission cap, so on HTTP/1.1, where a request needs a connection of its own,
admission has room to answer its `503` while a connection slot remains; idle keep-alive connections
can still fill the cap, and a connection beyond it is closed unserved. An `edge_hardening.admission_cap` above
diff --git a/doc/configuration/security-and-edge-hardening.adoc b/doc/configuration/security-and-edge-hardening.adoc
index fe4b10335..2f4752231 100644
--- a/doc/configuration/security-and-edge-hardening.adoc
+++ b/doc/configuration/security-and-edge-hardening.adoc
@@ -259,14 +259,17 @@ link:../user/edge-security.adoc#_edge_hardening_defaults[Edge hardening defaults
*The connection cap is one shared counter.* `quarkus.http.limits.max-connections` is one counter
shared by the plain-HTTP redirect listener and the HTTPS listener of the Quarkus-terminated side; the
-SNI front listener of `passthrough_sni` and the management interface are not counted. A connection
-the cap has counted holds its slot until it closes, whether or not it ever carries a request.
+SNI front listener of `passthrough_sni` and the management interface are not counted. It counts a
+connection on the HTTPS listener only once its TLS handshake has completed, and a connection the cap
+has counted holds its slot until it closes, whether or not it ever carries a request.
*A front proxy with its own request-head timeout is a deployment requirement.* No key here, and none
in the shipped `application.properties`, sets a deadline on the arrival of a request head. Until a
head is complete, the only bounds on its connection are the idle-connection reap, which any byte
restarts, and the connection cap above; `admission_cap` counts requests, so it does not see such a
-connection. Put a front proxy or load balancer in front of the gateway that times out the request
+connection. The connection cap has no per-source share, so one source can hold the whole counter,
+and routing through the SNI front of `passthrough_sni` does not bound it: the front's per-source share
+counts only the connections it has not yet handed over. Put a front proxy or load balancer in front of the gateway that times out the request
head itself (see
link:../user/edge-security.adoc#_request_head_deadline[Edge security -- A front proxy times out the request head]).
@@ -388,6 +391,24 @@ the configuration validation rule that judges `forwarded.trusted_proxies`, so it
configuration is validated: at startup, and in a `--validate-config` run as well. It names the action
only. Make sure every trusted proxy sends its clients' addresses in `X-Forwarded-For`.
+[[_enumeration_detection_passthrough]]
+*Behind the SNI front every terminated client is the loopback relay leg.* Under a non-empty
+`tls.passthrough_sni`, every terminated connection reaches the edge from the front's loopback relay
+leg, so source detection and the trusted-proxy judgement see every terminated client as that one
+loopback peer. While no `forwarded.trusted_proxies` range holds a loopback address, all of them are
+therefore one source: with `action` `block` or `delay`, one client's rejections trip it, and the block
+or delay it earns acts on every terminated client at once. A `forwarded.trusted_proxies` range that
+holds a loopback address -- overlapping `127.0.0.0/8`, or containing `::1` -- makes that leg a trusted
+proxy, so the gateway trusts every terminated client's own `Forwarded` and `X-Forwarded-For` headers.
+Each terminated request is then keyed by the *Address* rules above as a trusted proxy's request: on
+the address its own client-address header names, on the loopback leg's `unresolved-via-` source when a
+non-blank header resolves no client, and on `unknown` -- counted, never acted on -- when it sends none
+or only blank ones. The gateway logs WARN
+link:../LogMessages.adoc#apisheriff-152[`ApiSheriff-152`] once for each of the two combinations it
+finds, emitted by the same configuration validation as `ApiSheriff-149`; it names the combination by a
+fixed token, never a range or an address. In a passthrough topology keep `action` at `observe` and keep
+loopback out of `forwarded.trusted_proxies`.
+
*Shared addresses.* Behind a load balancer not listed in `forwarded.trusted_proxies`, every client is
one source: one scanning client trips it, and under `block` every client is answered `429`; under
`delay` all their rejections slow down and, once the held-answer share is used up, every further
diff --git a/doc/configuration/tls-and-egress.adoc b/doc/configuration/tls-and-egress.adoc
index ef896827d..9c19f190b 100644
--- a/doc/configuration/tls-and-egress.adoc
+++ b/doc/configuration/tls-and-egress.adoc
@@ -212,7 +212,7 @@ named explicitly.
`QUARKUS_HTTP_SSL_PORT`. Promoting it would break the
link:../adr/0017-Accept-time_SNI_split_at_a_dedicated_front_listener_passthrough_relays_opaquely_at_L4_everything_else_terminates_internally.adoc[ADR-0017]
SNI split, where a deployment that enables `tls.passthrough_sni` moves the terminated listener to
- the internal loopback port through exactly this variable -- a topology a `gateway.yaml`-owned port
+ the internal port through exactly this variable -- a topology a `gateway.yaml`-owned port
could not express.
| `quarkus.http.insecure-requests`
diff --git a/doc/development/boot-validation-rules.adoc b/doc/development/boot-validation-rules.adoc
index 47e443e15..2ce62c243 100644
--- a/doc/development/boot-validation-rules.adoc
+++ b/doc/development/boot-validation-rules.adoc
@@ -107,8 +107,10 @@ rule that `DEFAULT_RULES` does not register through that row's class.
| extracted
| `EdgeRules`
-| `validateForwardedTrust`, `validatePassthroughHostCollision`, `validatePassthroughAliasResolvable`
-| `forwarded.trusted_proxies`, `tls.passthrough_sni`
+| `validateForwardedTrust`, `validatePassthroughHostCollision`, `validatePassthroughAliasResolvable`,
+ `validatePassthroughSourceCollapse`
+| `forwarded.trusted_proxies`, `tls.passthrough_sni`, `enumeration_detection` (the passthrough
+ source-collapse rule is a boot WARN only, never a refusal)
| extracted
| `HeaderRules`
diff --git a/doc/development/tls-edge.adoc b/doc/development/tls-edge.adoc
index 7ba96eb64..24abf0abd 100644
--- a/doc/development/tls-edge.adoc
+++ b/doc/development/tls-edge.adoc
@@ -311,9 +311,12 @@ share -- or at its route decision beyond its passthrough target's dial budget is
* *logged* as `WARN ApiSheriff-146` (`ApiSheriffLogMessages.WARN.FRONT_CONNECTION_REFUSED`), at most once
per `SniFrontListener.SATURATION_WARN_INTERVAL` (60 s, measured on the monotonic `System.nanoTime()`
clock) per reason, with the reason token (`cap` / `source_share` / `dial_budget` -- the same spelling
- as the metric label), the bound that was full and the
- window. Every further refusal of that reason inside the window is logged at `DEBUG`. Neither line
- ever names the peer address or a received byte.
+ as the metric label), the stage that reason refuses at, the bound that was full and the window. The
+ stage is a field of `SniFrontListener.Refusal` beside its token -- `at accept, without reading from
+ the connection` for `cap` and `source_share`, `at its route decision, before its backend is dialled`
+ for `dial_budget` -- and reaches the record as a parameter, so the template lists no reason of its own
+ and a reason added to the enum is logged with its own stage. Every further refusal of that reason
+ inside the window is logged at `DEBUG`. Neither line ever names the peer address or a received byte.
The package-private constructor of `SniFrontListener` takes the share, the warn window, the clock, the
source key and the recorder explicitly. A test drives a second warn window by advancing its own clock
@@ -362,10 +365,21 @@ There are two ports, wired by `TlsEdgeProducer`:
| Internal HTTPS port
| `sheriff.tls.internal-https-port` (`8444`)
-| The terminated Quarkus HTTPS listener, bound to `localhost` only. Every non-passthrough connection
- is relayed here for termination.
+| The terminated Quarkus HTTPS listener. Every non-passthrough connection is relayed here for
+ termination. The listener binds `quarkus.http.host`, which the image sets to `0.0.0.0`
+ (`Dockerfile.native` starts the executable with `-Dquarkus.http.host=0.0.0.0`), so it listens on
+ every interface of the container, not on loopback alone.
|===
+*The internal HTTPS port is reachable wherever the deployment lets traffic reach it.* The front
+relays to `localhost:8444`, but nothing confines the listener to that address. Any peer on the
+container's network -- another container on the same Compose or pod network, or a client of a host
+port the deployment publishes for `8444` -- can connect to it directly and bypass the front: the SNI
+split, the front's ClientHello deadline and its per-source share do not apply to such a connection,
+and the relay registers no client for it, so the pending-login quota keys it on its own TCP peer.
+Publish only the public TLS port, keep `8444` unpublished, and restrict the container network to the
+peers that must reach the gateway.
+
The internal handoff is a *loopback relay*, not an in-process call: terminated connections are
spliced from the front listener to `localhost:8444`, where the ordinary Quarkus HTTPS listener does
the TLS termination and L7 processing it would do anyway. This keeps the terminated pipeline
diff --git a/doc/security-threat-model.adoc b/doc/security-threat-model.adoc
index 5304bb0a7..f837c84ea 100644
--- a/doc/security-threat-model.adoc
+++ b/doc/security-threat-model.adoc
@@ -1337,7 +1337,8 @@ inbound idle timeout that closes a connection carrying no bytes (any byte the co
starts it again, so it does not end a connection that keeps trickling), a connection cap
(`quarkus.http.limits.max-connections`) that bounds how many connections the Quarkus-terminated
side holds open at once (one counter shared by the plain-HTTP redirect listener and the HTTPS
-listener; the SNI front listener of `passthrough_sni` and the management interface are not
+listener, counting a connection on the HTTPS listener only once its TLS handshake has completed;
+the SNI front listener of `passthrough_sni` and the management interface are not
counted; set at twice the default admission cap, so on HTTP/1.1 admission can answer while a
connection slot remains -- idle keep-alive connections can still fill the cap), a max-in-flight admission cap, `max_body_bytes` as a
*streaming* counter (never buffer the body -- link:adr/0006-body-streaming-vs-httpresult.adoc[ADR-0006]),
@@ -1349,7 +1350,10 @@ still cap body bytes. Explicit YAML `StreamReadConstraints` are applied at confi
HTTP/1.1 request line and header block, or an HTTP/2 header block with its `CONTINUATION` frames.
Until a head is complete, the idle timeout, which any byte restarts, and the connection cap are the
only bounds on its connection, and a connection the cap has counted holds its slot until it closes,
-whether or not a request head ever completes on it. A front proxy that enforces its own request-head
+whether or not a request head ever completes on it. The cap has no per-source share, so one source
+that completes its handshakes and sends no request head can hold the whole counter; routing through
+the SNI front does not bound that, because the front's per-source share counts only the connections it
+has not yet handed over (<>). A front proxy that enforces its own request-head
timeout is therefore a deployment requirement
(link:user/edge-security.adoc#_request_head_deadline[Edge security -- A front proxy times out the request head]).
@@ -1980,8 +1984,8 @@ for good (CWE-400). The front bounds each with a fixed value that no configurati
backend. A backend is the host and port a passthrough alias resolves to, not an SNI hostname: every
hostname that resolves to it shares its budget, and its host name is compared without regard to
letter case, so two aliases that spell one backend's name differently cannot hold a budget each. The
- terminated hand-off target is exempt: its dial goes to the gateway's own loopback listener and settles
- at once.
+ terminated hand-off target is exempt: its dial goes to the gateway's own internal listener through
+ `localhost` and settles at once.
* *A visible refusal.* Every connection closed at accept, beyond the cap or beyond its source's share,
and every connection closed at its route decision beyond its backend's dial budget, is counted on
`sheriff_front_connections_refused_total{reason}` (`cap` / `source_share` / `dial_budget`) and logged
@@ -2124,7 +2128,8 @@ customizes: the main HTTP, main HTTPS and main domain-socket listeners. The mana
built without the customizer, so none of these bounds reaches it: Quarkus applies no HTTP/2 setting to
it, and it announces the transport's 8 KiB header list and keeps the transport's stream and reset
defaults. Its HTTP/1.x header block is held at the main listeners' 16 KiB through
-`quarkus.management.limits.max-header-size`, and its request line and chunk keep transport defaults
+`quarkus.management.limits.max-header-size`, its request body at the shipped 32 KiB through
+`quarkus.management.limits.max-body-size`, and its request line and chunk keep transport defaults
tighter than the main listeners' (`ManagementListenerTransportTest`). The last two follow from the
never-forward set and from dispatch:
@@ -2999,17 +3004,21 @@ browser* with a short-lived `HttpOnly` `__Host-` binding cookie (a record retrie
matching binding cookie, not just a valid `state`). PKCE does not replace login-CSRF
protection -- keep both.
-*Status (mode-split -- the single-use guarantee differs):*
-
-* *Server mode:* COVERED. The record is server-side; the gateway *discards it on first
- callback* (true single-use) and the binding cookie ties it to the browser.
-* *Cookie mode:* PARTIAL (accepted risk). The record travels only in the sealed short-lived
- `__Host-` login cookie -- there is no server store to mark it consumed -- so within the
- cookie's short TTL a captured login cookie *could* be replayed. Mitigation and accepted risk:
- the TTL is minutes, the cookie is `HttpOnly`+`Secure`+`__Host-` (not JS-readable, HTTPS-only,
- origin-locked), the browser binding still holds, and the exposure window is the login round
- trip only. This is an explicit risk acceptance of the stateless variant -- choose server mode
- if strict single-use of the login step is required.
+*Status:* COVERED, in both session modes. The single-use guarantee is the same in each, because the
+login step is not stateless in either:
+
+* *Server mode and cookie mode alike:* the pending-authorization record -- `state`, `nonce`, PKCE
+ verifier and return URL -- is held server-side in the one in-memory pending-authorization store
+ of the gateway process (`InMemoryPendingAuthorizationStore`, built for both modes), and the
+ short-lived `HttpOnly` `__Host-` binding cookie carries only the record's unguessable id. The
+ callback consumes the record as it reads it (`PendingAuthorizationStore.consume`), so the record
+ is single-use: a replayed callback, or the same binding cookie presented again, resolves nothing.
+* *What the session mode changes is after the callback, not before it.* Cookie mode seals the
+ *session* the callback creates into the session cookie and keeps no server-side session; server
+ mode stores it. Neither seals the pending-authorization record into a cookie. Because the record
+ lives in one process, the callback has to reach the instance that started the login in both modes
+ (see link:variants/03-bff-cookie.adoc#_stateless_after_login_not_during_it[Variant 3 -- Stateless
+ after login, not during it]).
*The return URL is bound to the gateway origin, and only the query is carried along.* A
session-route navigation records its return URL as the canonical request path plus the raw
@@ -3383,7 +3392,7 @@ configured list names only other origins; the unsafe-method check of session rou
the configured list alone. Because the proof is checked before the session is looked up, the answer
without it is the same whether or not a session exists. *Accepted cost:* a logout link on a trusted
origin other than the gateway's own sends no `Origin` on a top-level navigation, and a typed or
-bookmarked logout URL carries `Sec-Fetch-Site: none`; both land on the confirmation page, which the
+bookmarked logout URL carries `Sec-Fetch-Site: none` and no `Origin`; both land on the confirmation page, which the
user confirms with one click.
*A proven RP-initiated logout ends the gateway session whatever the identity provider offers.* The logout
@@ -4319,7 +4328,7 @@ by these rules, in this order:
source (`PendingQuotaKeys`): for a peer listed in `forwarded.trusted_proxies`, the client address
its forwarding headers resolve to -- when a `Forwarded` or `X-Forwarded-For` value is present yet
the two chains together resolve none, that proxy's own unresolved source
- (`unresolved-via-`), never one chain read on its own, the one derivation the
+ (`unresolved-via-` followed by the proxy's canonical address), never one chain read on its own, the one derivation the
detection source key shares (`ForwardedClientResolution`) -- and `unknown` when the request carries
neither header, or only blank ones; for any other peer, the
TCP peer address, whose forwarding headers are never read. Behind the gateway's own SNI front
@@ -4911,14 +4920,14 @@ outstanding hardening work (next section).
| <> | Per-route `cookies` policy, default `none`; one gateway-cookie definition dropped in both directions under every policy; `allow: all` refused at the gateway scope; upstream `Set-Cookie` relayed by policy with `Domain` removed on the HTTP relay, gRPC headers and gRPC trailers; a same-origin check on every non-WebSocket cookie-forwarding route for unsafe requests carrying a forwarded cookie, `allowed_origins` mandatory on a cookie-forwarding WebSocket route | Gateway (`GatewayCookies`, `ForwardPolicyStage`, `UpstreamSetCookieFilter`, `ResponseStage`, `CsrfDefence`, `RouteTableBuilder`, `GatewayEdgeRoute`) + configuration validator (`CookieRules`, `ForwardingRules`) -- ADR-0037 | COVERED (cross-upstream exposure under `allow: all`, a `Path`-scoped upstream cookie and an upstream that opts out of the check accepted)
| <> | Every rejection raised after route selection and before the trust boundary, and every unexpected internal failure there, rendered as the unrouted `404` -- status, body, `Content-Type` and header set identical, never trailers-only on gRPC; every unrouted `404` released on the floor's step grid, the release computed on the event loop when the answer is armed, on a Vert.x timer; held answers on a derived held-answer sub-budget, `503` on the floor's release time when it is full, one tripped source held to its share; the floor measured against twelve caller-drivable pre-trust paths, each answered as the unrouted `404` -- the bearer-token paths, the declared-length fast-reject, a route-scoped filter violation, a cookie-forwarding same-origin refusal and a `protocol: grpc` route among them -- and its overruns metered; the true event still metered; one switch `security_defaults.uniform_not_found`, on by default | Gateway (`UniformNotFound`, `ErrorResponseWriter`, `RejectionReporter`, `ResponseDelay`, `EdgeAdmission`, `PipelineRequest`, `AuthenticationStage`) -- ADR-0073 | COVERED (session and anonymous routes still disclose themselves through their own answers, the floor measured on the integration stack rather than on every deployment, and the held-answer `503` under a `404` flood, accepted)
| <> | Exact-match redirect URI | Engine (logout) + AS (auth) + gateway reserved-path registration | COVERED
-| <> | Browser-bound `state`; single-use; same-origin return URL whose path passes the shared <> review, with the raw query kept and a boot-checked `default_return_url` | Engine `FlowContext` + gateway pending-authorization record (binding cookie, `PendingAuthorizationRecord.sameOrigin` over `LocationPathReview`) | COVERED (server) / PARTIAL-accepted (cookie: TTL replay window)
+| <> | Browser-bound `state`; single-use in both session modes (the record held in the server-side pending-authorization store, consumed on its first callback); same-origin return URL whose path passes the shared <> review, with the raw query kept and a boot-checked `default_return_url` | Engine `FlowContext` + gateway pending-authorization record (binding cookie, `InMemoryPendingAuthorizationStore`, `PendingAuthorizationRecord.sameOrigin` over `LocationPathReview`) | COVERED
| <> | PKCE `S256`; verifier binding; single-use code | Engine `PkceChallenge` (S256-only) | COVERED
| <> | `nonce` validated + single-use | Engine `IdTokenValidationBridge` + gateway pending-authorization record | COVERED
| <> | Single-IdP; `iss` verification | Design + engine `IssValidator` | ELIMINATED
| <> | Alg pinning; aud/iss/exp; psychic-sig guard | Validation lib (fail-closed, in-library) + ADR-0001 | COVERED
| <> | Ignore `jku`/`x5u`; egress-guarded bounded JWKS fetch (the `jwks.url` host exempted, derived or declared -- see <>); readiness `DOWN` per issuer without a key set; bounded fast retry | Validation lib (`EgressPolicy`) + gateway (`TokenValidatorProducer` egress allowance, `RetryingJwksLoader`, `GatewayReadinessCheck`) | COVERED
| <> | RT reuse detection by IdP strict rotation; per-kind refresh-failure dispositions; per-session single-flight | IdP (strict rotation, shipped in the integration and compose-sample realms) + engine `RefreshFlow.classify` + gateway `TokenRefreshCoordinator` -- ADR-0046 | COVERED (server: replay unreachable, IdP revocation via refresh) / COVERED (cookie: replay rejected by the IdP; duplicate-refresh residual accepted)
-| <> | Logout: exact post-logout URI + state (engine); back-channel token checks including `typ`, `exp`, `jti` and single use (gateway); RP-initiated logout acts only on a top-level document navigation from a trusted origin (no `Sec-Purpose`, `Sec-Fetch-Mode` `navigate` and `Sec-Fetch-Dest` `document` when present, and a trusted `Origin`, else `Sec-Fetch-Site` `same-origin`) judged by the session CSRF defence before any session lookup, otherwise a `no-store`, framing-forbidden confirmation page whose form `POST`s back; the gateway session ended before the provider redirect is built, and without it where none can be built; RP-initiated logout revokes the session's refresh token (RFC 7009) after the local destruction, a failure latched as `ApiSheriff-147`; in server mode a termination is not undone by an in-flight refresh or widening write | Engine (RP-initiated, `RevocationClient`) + gateway (back-channel receiver, `LogoutTokenValidator`, `LogoutTokenReplayGuard`, `LogoutEndpoint`, `CsrfDefence.provesTrustedDocumentNavigation`, `RpInitiatedLogout`, `BffRuntimeProducer.revokeOnLogout`, `SessionBinding` updating write over the conditional `SessionStore` write) -- ADR-0018, ADR-0080 | COVERED (server; not revoked: the access token, anything on the back-channel path, and any token at a provider without a `revocation_endpoint`; a logout link on another trusted origin lands on the confirmation page, accepted) / PARTIAL-accepted (cookie: a response in flight can outlast the logout)
+| <> | Logout: exact post-logout URI + state (engine); back-channel token checks including `typ`, `exp`, `jti` and single use (gateway); RP-initiated logout acts only on a top-level document navigation from a trusted origin (no speculative-load marker, which is a `Sec-Purpose` of any value or, with `Sec-Purpose` absent, a `prefetch` value, in any case, of the legacy `Purpose` or `X-Moz` header; `Sec-Fetch-Mode` `navigate` and `Sec-Fetch-Dest` `document` when present; and a trusted `Origin`, else `Sec-Fetch-Site` `same-origin`) judged by the session CSRF defence before any session lookup, otherwise a `no-store`, framing-forbidden confirmation page whose form `POST`s back; the gateway session ended before the provider redirect is built, and without it where none can be built; RP-initiated logout revokes the session's refresh token (RFC 7009) after the local destruction, a failure latched as `ApiSheriff-147`; in server mode a termination is not undone by an in-flight refresh or widening write | Engine (RP-initiated, `RevocationClient`) + gateway (back-channel receiver, `LogoutTokenValidator`, `LogoutTokenReplayGuard`, `LogoutEndpoint`, `CsrfDefence.provesTrustedDocumentNavigation`, `RpInitiatedLogout`, `BffRuntimeProducer.revokeOnLogout`, `SessionBinding` updating write over the conditional `SessionStore` write) -- ADR-0018, ADR-0080 | COVERED (server; not revoked: the access token, anything on the back-channel path, and any token at a provider without a `revocation_endpoint`; a logout link on another trusted origin lands on the confirmation page, accepted) / PARTIAL-accepted (cookie: a response in flight can outlast the logout)
| <> | Tokens never in browser; `__Host-` cookie, with a non-`__Host-` `session.cookie_name` refused at boot; fixation; `token_relay: false` keeps the token from the origin, `Authorization` re-admission refused at boot | Engine `TokenStore` SPI + gateway session cookie + configuration validator | COVERED
| <> | CSRF on cookie-authed API (Origin/Sec-Fetch-Site) | Gateway (fixed behaviour, no knob) | COVERED
| <> | AES-GCM random nonce; key-id AAD; rotation; size budget | Gateway `TokenStore` implementation (`SealedSessionCookieCodec`) | COVERED
diff --git a/doc/user/edge-security.adoc b/doc/user/edge-security.adoc
index b06990f96..299161262 100644
--- a/doc/user/edge-security.adoc
+++ b/doc/user/edge-security.adoc
@@ -594,12 +594,16 @@ deployment that never writes it keeps the behaviour shown here.
[`quarkus.http.limits.max-connections`]
| 4096
| How many connections the Quarkus-terminated side holds open at once. A connection beyond the cap
- is closed without being served, while the connections already open are served on. It bounds open
- connections whatever they carry; the admission cap below bounds the requests in flight on them.
- The cap is one counter shared by the plain-HTTP redirect listener and the HTTPS listener of the
- Quarkus-terminated side, so a connection to the redirect listener counts toward it too. The SNI
- front listener of `passthrough_sni` and the management interface are not counted. The value is set
- in the shipped `application.properties`, not in `gateway.yaml`, and is not configurable there.
+ is closed without being served, while the connections already open are served on. It counts a
+ connection once the connection is established -- on the HTTPS listener only after its TLS handshake
+ has completed, so a connection still in its handshake holds no slot -- and a counted connection holds
+ its slot until it closes, whether or not it carries a request; the admission cap below bounds the
+ requests in flight on them. The cap is one counter shared by the plain-HTTP redirect listener and
+ the HTTPS listener of the Quarkus-terminated side, so a connection to the redirect listener counts
+ toward it too. It has no per-source share: one source can hold the whole counter, and routing
+ through the SNI front of `passthrough_sni` does not bound it (see <<_request_head_deadline>>). The
+ SNI front listener itself and the management interface are not counted. The value is set in the
+ shipped `application.properties`, not in `gateway.yaml`, and is not configurable there.
*Derivation.* `Dockerfile.native` declares no file-descriptor limit, so the process runs under
whatever limit the container runtime grants, and the image cannot derive a value from it. The cap
@@ -823,13 +827,17 @@ above act on such a connection:
* the *idle-connection reap*, which any byte restarts, so a client that sends something within every
60 s keeps its connection open;
* the *connection cap*, one counter shared by the plain-HTTP redirect listener and the HTTPS listener
- of the Quarkus-terminated side. A connection the cap has counted holds its slot until it closes,
- whether or not a request head ever completes on it, and a connection beyond the cap is closed
- without being served.
-
-Under `tls.passthrough_sni` the SNI front listener ends a connection whose TLS ClientHello is not
-complete within 10 s (link:tls-edge.adoc[TLS edge]); it sets no deadline on the request head that
-follows the handshake.
+ of the Quarkus-terminated side. It counts a connection on the HTTPS listener only once its TLS
+ handshake has completed. A connection the cap has counted holds its slot until it closes, whether or
+ not a request head ever completes on it, and a connection beyond the cap is closed without being
+ served.
+
+The connection cap has no per-source share: one source that completes its handshakes and then sends
+no request head can hold the whole counter, and every other client's connection is then closed
+unserved. Under `tls.passthrough_sni` the SNI front listener ends a connection whose TLS ClientHello is
+not complete within 10 s (link:tls-edge.adoc[TLS edge]), and its per-source share bounds only the
+connections it has not yet handed over; it sets no deadline on the request head that follows the
+handshake, so routing through the front does not bound how much of the counter one source holds.
*Deployment requirement.* Run the gateway behind a front proxy or load balancer that enforces its
own timeout on the request head and closes a connection that does not deliver a complete head in
diff --git a/doc/user/environment-variable-overrides.adoc b/doc/user/environment-variable-overrides.adoc
index 5928f2323..f5dc31968 100644
--- a/doc/user/environment-variable-overrides.adoc
+++ b/doc/user/environment-variable-overrides.adoc
@@ -88,7 +88,7 @@ own it, so the omission is discoverable rather than silent.
| `8443`
| The *terminated* HTTPS listener. This is the variable the SNI passthrough topology moves: a
deployment that enables `tls.passthrough_sni` gives the public TLS port to the front listener and
- sets this to the internal loopback port (`8444`).
+ sets this to the internal port (`8444`).
| `QUARKUS_MANAGEMENT_PORT`
| `9000`
@@ -110,7 +110,9 @@ for what that health state means and how to read it.
| `SHERIFF_TLS_INTERNAL_HTTPS_PORT`
| `8444`
-| The internal loopback port the terminated listener moves to under the passthrough topology.
+| The internal port the terminated listener moves to under the passthrough topology. The listener
+ binds `quarkus.http.host`, which the image sets to `0.0.0.0`, so it listens on every interface of
+ the container, not on loopback alone; keep this port unpublished.
|===
=== Certificate, key and trust material
diff --git a/doc/user/tls-edge.adoc b/doc/user/tls-edge.adoc
index de0eada77..7570d2178 100644
--- a/doc/user/tls-edge.adoc
+++ b/doc/user/tls-edge.adoc
@@ -242,7 +242,8 @@ passthrough backend from holding the others off:
belongs to the backend -- the host and port a passthrough alias resolves to -- not to the SNI
hostname: hostnames whose aliases resolve to the same host and port share its 128, and a backend
host name is the same backend however its letters are cased. Connections to the terminated listener
- are not budgeted: that dial goes to the gateway's own loopback port and completes at once.
+ are not budgeted: that dial goes to the gateway's own internal listener through `localhost` and
+ completes at once.
| Relay idle timeout
| derived
@@ -317,7 +318,9 @@ places:
| `WARN ApiSheriff-146`
| The first refusal of each reason in a 60 s window, naming the reason (`cap` / `source_share` /
- `dial_budget`), the bound and the window. Further refusals of that reason inside the window are
+ `dial_budget`), where that reason refused -- `at accept, without reading from the connection` for
+ `cap` and `source_share`, `at its route decision, before its backend is dialled` for `dial_budget`
+ -- the bound and the window. Further refusals of that reason inside the window are
logged at `DEBUG`, so a flood leaves one line per minute and reason, not one per connection.
|===
@@ -386,13 +389,21 @@ every change to it -- adding a root or removing one -- takes effect only when th
* *An emergency cut-off drops the old root from the file and restarts the gateway.* Until the
restart, the removed root stays trusted. The restart closes every open connection, so none
established under the removed root survives it. From then on a certificate under that root is
- rejected at the handshake, with no per-client exemption, unless a root that stays in the file still
- provides a path to it. A cross-certificate is such a path: if a remaining root has cross-signed the
- removed root or one of its intermediates, a client that presents that cross-certificate can still
- complete the handshake. Before relying on the cut-off, make sure no root left in the file certifies
- the removed one, and confirm the cut-off with a client certificate issued under the removed root.
+ rejected at the handshake, with no per-client exemption, unless a certificate that stays in the file
+ still provides a path to it. An intermediate of the removed root left in the file is such a path,
+ because every certificate in the bundle is an anchor. A cross-certificate is another: if a remaining
+ root has cross-signed the removed root or one of its intermediates, a client that presents that
+ cross-certificate can still complete the handshake. Before relying on the cut-off, make sure no
+ certificate left in the file certifies the removed one or belongs to its chain. The file cannot show
+ a cross-certificate a client presents, so establish with the issuers of the remaining roots whether
+ any of them cross-signed the removed root or one of its intermediates: while such a root stays in
+ the file, the cut-off does not reach a client that presents that cross-certificate. Confirm the
+ cut-off with a client certificate issued under each intermediate of the removed root, not only with
+ one issued directly under the root.
* *There is no per-certificate revocation.* Neither CRL nor OCSP is checked, so the only revocation
- lever is removing every root a certificate chains to.
+ lever is removing from the file every certificate of the chain a client certificate builds to it.
+ Removing the root is not enough on its own: every certificate in the bundle is a trust anchor, so an
+ intermediate left in the file still lets a certificate it issued complete the handshake.
To cut off a single compromised client without rotating the fleet, drop it at the network perimeter.
diff --git a/doc/variants/03-bff-cookie.adoc b/doc/variants/03-bff-cookie.adoc
index 720998ee2..8e3f51c49 100644
--- a/doc/variants/03-bff-cookie.adoc
+++ b/doc/variants/03-bff-cookie.adoc
@@ -196,7 +196,10 @@ link:../user/bff-cookie.adoc#_cookie_size_budget[the cookie-BFF operator guide])
* *RP-initiated* (`oidc.logout.path`). Works as in the
link:02-bff-session.adoc#_logout[session-based variant]: it acts only on a trusted top-level
- document navigation -- `Sec-Fetch-Site: none`, a subresource, a frame or a prefetch is no proof --
+ document navigation -- with no `Origin`, `Sec-Fetch-Site: none` is no proof, and a subresource, a
+ frame or a prefetch is refused when it identifies itself through Fetch Metadata (`Sec-Fetch-Mode`,
+ `Sec-Fetch-Dest`) or a speculative-load marker (`Sec-Purpose`, or the legacy `Purpose` /
+ `X-Moz: prefetch`) --
and answers any other request with a `no-store`, framing-forbidden confirmation page that leaves both
cookies in place; with the proof, the session cookie and the activity cookie are
expired first, then the browser is redirected to the IdP's end-session endpoint with a
diff --git a/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/LocalStackTls.java b/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/LocalStackTls.java
index 2f44c88f3..d3f3f0b21 100644
--- a/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/LocalStackTls.java
+++ b/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/LocalStackTls.java
@@ -25,9 +25,9 @@
import javax.net.ssl.X509TrustManager;
/**
- * Builds JDK {@link HttpClient}s that accept the self-signed {@code localhost} certificate the
- * integration stack serves — the JDK-client counterpart of the relaxed HTTPS validation
- * {@link BaseIntegrationTest} switches on for REST Assured.
+ * Builds JDK {@link HttpClient}s, and the TLS context behind them, that accept the self-signed
+ * {@code localhost} certificate the integration stack serves — the JDK-client counterpart of the
+ * relaxed HTTPS validation {@link BaseIntegrationTest} switches on for REST Assured.
*
* The JDK client is what a suite reaches for when REST Assured cannot express the request: a
* WebSocket handshake, or an HTTP/2 request whose header fields must reach the wire one by one. It
@@ -59,9 +59,20 @@ private LocalStackTls() {
* @throws GeneralSecurityException when the JDK cannot provide a TLS context
*/
static HttpClient.Builder clientBuilder() throws GeneralSecurityException {
+ return HttpClient.newBuilder().sslContext(trustAllContext()).connectTimeout(CONNECT_TIMEOUT);
+ }
+
+ /**
+ * A TLS context that accepts the stack's self-signed certificate, for a suite that must put
+ * hand-framed bytes on the wire through a raw {@link javax.net.ssl.SSLSocket} rather than a client.
+ *
+ * @return a freshly initialised context
+ * @throws GeneralSecurityException when the JDK cannot provide a TLS context
+ */
+ static SSLContext trustAllContext() throws GeneralSecurityException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
- return HttpClient.newBuilder().sslContext(sslContext).connectTimeout(CONNECT_TIMEOUT);
+ return sslContext;
}
/** Accepts every certificate chain; see the class documentation for the scope. */
diff --git a/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/ManagementBodyBoundIT.java b/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/ManagementBodyBoundIT.java
new file mode 100644
index 000000000..b7038d6b3
--- /dev/null
+++ b/integration-tests/src/test/java/de/cuioss/sheriff/gateway/integration/ManagementBodyBoundIT.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright © 2025-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.sheriff.gateway.integration;
+
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSocket;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Proves the management interface's request-body bound on the shipped native image: the
+ * {@code quarkus.management.limits.max-body-size=32K} the shipped {@code application.properties}
+ * declares is the bound the running container's management routes enforce.
+ *
+ * {@code ManagementListenerTransportTest} observes the same bound on a JVM-mode listener. This IT
+ * closes the gap that leaves open: the key is a runtime property baked into the native executable, and
+ * only a request to the container built from this branch shows the image carries it. A body one byte
+ * past 32 KiB is refused {@code 413} on its declared {@code Content-Length}, before any body byte is
+ * sent; a body of exactly 32 KiB is served, which is the matched control that keeps the refusal from
+ * passing on a listener that refuses every body. Under the 10 MiB Quarkus default the refused request
+ * would be served, so the first assertion fails on an image without the key.
+ *
+ * Each listed default SmallRye Health route ({@code /health}, {@code /health/live},
+ * {@code /health/ready}, {@code /health/started}, {@code /health/group}, {@code /health/well}) and the
+ * {@code /metrics} route answers a body-less {@code GET} with {@code 200} on the same container, which
+ * shows the bound costs none of the listed probes a deployment relies on.
+ *
+ * The exchange runs over a raw TLS socket pinned to HTTP/1.1, so the declared {@code Content-Length}
+ * is under the test's control rather than a client's: an HTTP client would refuse to declare a length
+ * it then does not send. The management port and context path come from {@link BaseIntegrationTest},
+ * the stack's self-signed certificate is accepted through {@link LocalStackTls}.
+ *
+ * @author API Sheriff Team
+ * @since 1.0
+ */
+@DisplayName("Management body bound — live on the native image")
+class ManagementBodyBoundIT extends BaseIntegrationTest {
+
+ /** The body bound the shipped file sets on every management route. */
+ private static final int BODY_BOUND = 32 * 1024;
+
+ private static final int OK = 200;
+ private static final int PAYLOAD_TOO_LARGE = 413;
+
+ /**
+ * How long each step of one exchange with the management listener may wait: the TCP connect, and
+ * every read of the handshake and of the answer.
+ */
+ private static final int EXCHANGE_TIMEOUT_MILLIS = 10_000;
+
+ /** The liveness probe, relative to the management root path. */
+ private static final String LIVENESS_ROUTE = "/health/live";
+
+ @Test
+ @DisplayName("refuses a declared body past the shipped 32 KiB with 413, and serves a body of exactly 32 KiB")
+ void boundsTheBodyAtTheShippedBound() throws Exception {
+ int refused = statusOf(requestDeclaringBodyOf(BODY_BOUND + 1));
+ int served = statusOf(requestWithBodyOf(BODY_BOUND));
+
+ assertAll("the native image's management body bound",
+ () -> assertEquals(PAYLOAD_TOO_LARGE, refused,
+ "a declared body one byte past 32 KiB is refused before a body byte is sent"),
+ () -> assertEquals(OK, served, "control: a body of exactly 32 KiB is served"));
+ }
+
+ @ParameterizedTest(name = "GET {0}")
+ @ValueSource(strings = {"/health", "/health/live", "/health/ready", "/health/started", "/health/group",
+ "/health/well", "/metrics"})
+ @DisplayName("answers a body-less GET on each listed default SmallRye Health and metrics route with 200 under the body bound")
+ void servesEveryProbeRouteABodylessGet(String route) throws Exception {
+ assertEquals(OK, statusOf(bodylessGetOf(route)),
+ "the probe route " + route + " is served: no probe needs a body the bound could refuse");
+ }
+
+ /**
+ * @param route the probe route, relative to the management root path
+ * @return a body-less GET of that route
+ */
+ private static String bodylessGetOf(String route) {
+ return "GET " + managementRootPath() + route + " HTTP/1.1\r\nHost: " + authority()
+ + "\r\nConnection: close\r\n\r\n";
+ }
+
+ /**
+ * @param bodyBytes the size of the body
+ * @return a liveness POST carrying a body of exactly that size
+ */
+ private static String requestWithBodyOf(int bodyBytes) {
+ return requestDeclaringBodyOf(bodyBytes) + "o".repeat(bodyBytes);
+ }
+
+ /**
+ * @param bodyBytes the body size the request declares
+ * @return the head of a liveness POST declaring a body of that size, without the body itself
+ */
+ private static String requestDeclaringBodyOf(int bodyBytes) {
+ return "POST " + managementRootPath() + LIVENESS_ROUTE + " HTTP/1.1\r\nHost: " + authority() + "\r\n"
+ + "Content-Type: application/octet-stream\r\n"
+ + "Content-Length: " + bodyBytes + "\r\nConnection: close\r\n\r\n";
+ }
+
+ /** @return the management origin {@link BaseIntegrationTest} resolves, parsed for host and port */
+ private static URI managementOrigin() {
+ return URI.create(managementPortBaseUri());
+ }
+
+ /** @return the {@code host:port} of the management listener, for the {@code Host} header */
+ private static String authority() {
+ return managementOrigin().getAuthority();
+ }
+
+ /**
+ * Sends one raw HTTP/1.1 request over TLS to the management listener and reads the status of its
+ * answer. The socket is created unconnected and connected with {@link #EXCHANGE_TIMEOUT_MILLIS} as
+ * its connect timeout, so a listener that drops the connect attempt fails the exchange within that
+ * time; the same value, as the socket's read timeout, then bounds every read of the handshake and of
+ * the answer.
+ *
+ * @param request the complete request, head, blank line and any body
+ * @return the status code of the answer
+ * @throws IOException when the exchange fails, a connect or read times out, or the
+ * listener closes without answering
+ * @throws GeneralSecurityException when the TLS context cannot be built
+ */
+ private static int statusOf(String request) throws IOException, GeneralSecurityException {
+ URI origin = managementOrigin();
+ try (SSLSocket socket = (SSLSocket) LocalStackTls.trustAllContext().getSocketFactory().createSocket()) {
+ socket.connect(new InetSocketAddress(origin.getHost(), origin.getPort()), EXCHANGE_TIMEOUT_MILLIS);
+ socket.setSoTimeout(EXCHANGE_TIMEOUT_MILLIS);
+ // Pin HTTP/1.1: the request is hand-framed HTTP/1.1, which an ALPN-negotiated HTTP/2
+ // connection would not parse.
+ SSLParameters parameters = socket.getSSLParameters();
+ parameters.setApplicationProtocols(new String[]{"http/1.1"});
+ socket.setSSLParameters(parameters);
+ socket.startHandshake();
+
+ OutputStream out = socket.getOutputStream();
+ out.write(request.getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));
+ String statusLine = reader.readLine();
+ if (statusLine == null) {
+ throw new IOException("the management listener closed the connection without answering");
+ }
+ return Integer.parseInt(statusLine.split(" ", 3)[1]);
+ }
+ }
+}