From 32ad846538ca849862f264504fb324fc4999cb43 Mon Sep 17 00:00:00 2001 From: Steve Hu Date: Wed, 28 Oct 2026 15:35:38 -0400 Subject: [PATCH 1/2] fix: apply configured response headers to specification routes --- config/hsts/README.md | 47 ++++ config/hsts/values-overlay.yml | 37 ++++ src/main/resources/config/values.yml | 7 + .../SpecificationHstsConfigurationTest.java | 205 ++++++++++++++++++ 4 files changed, 296 insertions(+) create mode 100644 config/hsts/README.md create mode 100644 config/hsts/values-overlay.yml create mode 100644 src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java diff --git a/config/hsts/README.md b/config/hsts/README.md new file mode 100644 index 0000000..ab4fa8a --- /dev/null +++ b/config/hsts/README.md @@ -0,0 +1,47 @@ +# HTTPS-only HSTS configuration + +This opt-in overlay addresses Checkmarx A02 (`light-rest-4j` favicon HSTS) in a +consuming application using the existing `HeaderHandler`. + +Merge [values-overlay.yml](values-overlay.yml) into the active application's +complete `values.yml`. It is not a standalone routing configuration. Preserve +any application-specific handlers, routes and response-header updates: combine +the header maps, and move `header` to the beginning of every applicable chain +rather than discarding custom chain entries. The supplied chains match the +packaged sidecar defaults. The overlay enables HTTPS, disables plaintext HTTP, +and sets `Strict-Transport-Security: max-age=31536000` without `includeSubDomains` +or `preload`. + +Use a certificate trusted by the consuming browsers; the bundled development +certificate is not a production certificate. Select the merged configuration +through the application's normal external configuration directory or config +server. No running instance is changed by the presence of this overlay. + +The packaged sidecar's direct favicon, Swagger UI, specification, health and +module-management routes now include `header` explicitly. This closes the route +bypass that otherwise prevents configured response headers from reaching them. +The overlay also puts the response-header policy before short-circuiting +handlers in the default and admin chains. Header policy therefore reaches the +supported routes' normal, rejection and error responses. Review any custom +routes, unsupported-method fallback or proxy-generated response separately. + +The default sidecar can still use plaintext HTTP internally and does not emit +HSTS by default. Do not apply this overlay to a publicly accessible plaintext +listener: generic `HeaderHandler` does not check the request scheme. For public +HTTP-to-HTTPS redirects, keep the plaintext redirect handler outside this HSTS +chain. With TLS termination at an edge, ensure the edge preserves or emits one +HSTS header on public HTTPS responses and that the origin cannot be reached +through an untrusted direct path. Client-supplied forwarded-protocol headers +are not a trust decision. + +`SpecificationHstsConfigurationTest` reads both the packaged values and this +overlay, checks the actual route/chain ordering, and tests the real favicon +handler and header middleware over TLS. It covers normal, redirect, not-found +and exception responses and checks the unconfigured control and preserved icon. +The TLS certificate is generated only for the test and is not checked in. + +Before closing the partner finding, deploy the reviewed merged configuration, +capture public HTTPS headers for the favicon and other supported response +paths, confirm one intended HSTS value, and rerun the partner scan. The +configuration and loopback tests do not establish the partner deployment's +state. See [RFC 6797](https://www.rfc-editor.org/rfc/rfc6797.html). diff --git a/config/hsts/values-overlay.yml b/config/hsts/values-overlay.yml new file mode 100644 index 0000000..50c4564 --- /dev/null +++ b/config/hsts/values-overlay.yml @@ -0,0 +1,37 @@ +# Merge into the active application values.yml; do not use as a standalone routing configuration. +server.enableHttps: true +server.enableHttp: false +header.enabled: true +header.response.update: + Cache-Control: no-store + X-Content-Type-Options: nosniff + Strict-Transport-Security: max-age=31536000 +handler.chains: + default: + - header + - exception + - prefix + - metrics + - limit + - correlation + - killapp + - latency + - memory + - exchaos + - requestInterceptor + - audit + - token + - router + - specification + - security + - sanitizer + - validator + - proxy + admin: + - header + - exception + - correlation + - specification + - security + - body + - validator diff --git a/src/main/resources/config/values.yml b/src/main/resources/config/values.yml index 498098d..0ee9686 100644 --- a/src/main/resources/config/values.yml +++ b/src/main/resources/config/values.yml @@ -179,12 +179,14 @@ handler.paths: - path: '/health' method: 'get' exec: + - header - exception - health # the health endpoint for the proxy + downstream backend if enabled without security, this is for teams to monitor overall API health via third party tools or via Control Plane - path: '/health/${server.serviceId}' method: 'get' exec: + - header - exception - limit - proxyHealth @@ -217,11 +219,13 @@ handler.paths: - path: '/adm/modules' method: 'get' exec: + - header - modules - path: '/adm/modules' method: 'post' exec: + - header - body - configReload @@ -253,14 +257,17 @@ handler.paths: - path: '/spec.yaml' method: 'get' exec: + - header - spec - path: '/specui.html' method: 'get' exec: + - header - swaggerui - path: '/favicon.ico' method: 'get' exec: + - header - favicon diff --git a/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java b/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java new file mode 100644 index 0000000..276a594 --- /dev/null +++ b/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java @@ -0,0 +1,205 @@ +package com.networknt.router; + +import com.networknt.specification.FaviconHandler; +import com.networknt.config.Config; +import com.networknt.config.yml.YamlUtils; +import java.util.ArrayList; +import java.util.Map; +import java.util.LinkedHashMap; + +import com.networknt.header.HeaderHandler; +import io.undertow.Handlers; +import io.undertow.Undertow; +import io.undertow.server.HttpHandler; +import io.undertow.server.handlers.ExceptionHandler; +import io.undertow.server.handlers.ResponseCodeHandler; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +class SpecificationHstsConfigurationTest { + private static final String HSTS = "Strict-Transport-Security"; + private static final String CONFIG_NAME = "sidecar-hsts-test-header"; + private static Map application; + private static Map merged; + private static final String POLICY = "max-age=31536000"; + // This password protects a temporary, test-generated loopback certificate only. + private static final String TEST_PASSWORD = "hsts-test-only"; + @TempDir + static Path directory; + private static Undertow configured; + private static Undertow withoutMiddleware; + private static HttpClient client; + + @BeforeAll + static void startTlsServers() throws Exception { + application = readYaml(Path.of("src/main/resources/config/values.yml")); + merged = new LinkedHashMap<>(application); + merged.putAll(readYaml(Path.of("config/hsts/values-overlay.yml"))); + assertEquals(Boolean.TRUE, merged.get("server.enableHttps")); + assertEquals(Boolean.FALSE, merged.get("server.enableHttp")); + Config.getInstance().putInConfigCache(CONFIG_NAME, Map.of( + "enabled", merged.get("header.enabled"), "request", Map.of(), + "response", Map.of("update", merged.get("header.response.update")))); + SSLContext tls = testTlsContext(); + client = HttpClient.newBuilder().sslContext(tls).version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build(); + HttpHandler routes = Handlers.routing() + .get("/favicon.ico", new FaviconHandler()) + .get("/normal", exchange -> exchange.getResponseSender().send("ok")) + .get("/redirect", exchange -> { + exchange.setStatusCode(302); + exchange.getResponseHeaders().put(io.undertow.util.Headers.LOCATION, "/favicon.ico"); + exchange.endExchange(); + }) + .get("/error", exchange -> { throw new IllegalStateException("controlled test failure"); }); + HttpHandler errors = new ExceptionHandler(routes) + .addExceptionHandler(IllegalStateException.class, ResponseCodeHandler.HANDLE_500); + HeaderHandler header = new HeaderHandler(CONFIG_NAME); + assertTrue(header.isEnabled()); + header.setNext(errors); + configured = start(tls, header); + withoutMiddleware = start(tls, errors); + } + + private static Undertow start(SSLContext tls, HttpHandler handler) { + Undertow server = Undertow.builder().setIoThreads(1).setWorkerThreads(2) + .addHttpsListener(0, "127.0.0.1", tls).setHandler(handler).build(); + server.start(); + return server; + } + + @AfterAll + static void stopServers() { + if (client != null) client.close(); + if (configured != null) configured.stop(); + if (withoutMiddleware != null) withoutMiddleware.stop(); + Config.getInstance().clearConfigCache(CONFIG_NAME); + } + + @Test + void faviconWithoutMiddlewareDoesNotClaimHostPolicy() throws Exception { + HttpResponse response = get(withoutMiddleware, "/favicon.ico"); + assertEquals(200, response.statusCode()); + assertTrue(response.headers().allValues(HSTS).isEmpty()); + } + + @Test + void configuredFaviconHasSingleHstsAndPreservesIcon() throws Exception { + HttpResponse response = get(configured, "/favicon.ico"); + assertPolicy(response, 200); + assertEquals("image/x-icon", response.headers().firstValue("Content-Type").orElseThrow()); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElseThrow()); + assertArrayEquals(get(withoutMiddleware, "/favicon.ico").body(), response.body()); + } + + @Test + void normalResponseHasHsts() throws Exception { + HttpResponse response = get(configured, "/normal"); + assertPolicy(response, 200); + assertEquals("ok", new String(response.body(), StandardCharsets.UTF_8)); + } + + @Test + void httpsRedirectHasHsts() throws Exception { + HttpResponse response = get(configured, "/redirect"); + assertPolicy(response, 302); + assertEquals("/favicon.ico", response.headers().firstValue("Location").orElseThrow()); + } + + @Test + void unmatchedRouteHasHsts() throws Exception { + assertPolicy(get(configured, "/not-found"), 404); + } + + @Test + void exceptionResponseHasHsts() throws Exception { + assertPolicy(get(configured, "/error"), 500); + } + + @Test + @SuppressWarnings("unchecked") + void applicationRoutesRunTheConfiguredHeaderBeforeTerminalHandlers() { + Map> chains = (Map>) merged.get("handler.chains"); + List> paths = (List>) merged.get("handler.paths"); + assertFalse(paths.isEmpty()); + for (Map path : paths) { + List expanded = new ArrayList<>(); + for (String handler : (List) path.get("exec")) { + expanded.addAll(chains.getOrDefault(handler, List.of(handler))); + } + assertEquals("header", expanded.getFirst(), "Header must run first for " + path.get("path")); + assertEquals(1L, expanded.stream().filter("header"::equals).count()); + } + assertTrue(paths.stream().anyMatch(path -> "/favicon.ico".equals(path.get("path")))); + } + + @Test + void plaintextApplicationDefaultDoesNotForceHstsPolicy() { + assertEquals(Boolean.TRUE, application.get("server.enableHttp")); + assertFalse(String.valueOf(application.get("header.response.update")).contains(HSTS)); + } + + private static Map readYaml(Path path) throws Exception { + try (InputStream input = Files.newInputStream(path)) { + return YamlUtils.loadMap(Config.getInstance().getYaml(), input); + } + } + + private static void assertPolicy(HttpResponse response, int status) { + assertEquals(status, response.statusCode()); + assertEquals(List.of(POLICY), response.headers().allValues(HSTS)); + } + + private static HttpResponse get(Undertow server, String path) throws Exception { + int port = ((InetSocketAddress) server.getListenerInfo().getFirst().getAddress()).getPort(); + HttpRequest request = HttpRequest.newBuilder(URI.create("https://localhost:" + port + path)) + .timeout(Duration.ofSeconds(5)).GET().build(); + return client.send(request, HttpResponse.BodyHandlers.ofByteArray()); + } + + private static SSLContext testTlsContext() throws Exception { + Path store = directory.resolve("loopback.p12"); + Process keytool = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "keytool").toString(), + "-genkeypair", "-alias", "loopback", "-keyalg", "RSA", "-keysize", "2048", + "-validity", "1", "-dname", "CN=localhost", "-ext", "SAN=dns:localhost,ip:127.0.0.1", + "-storetype", "PKCS12", "-keystore", store.toString(), "-storepass", TEST_PASSWORD, + "-keypass", TEST_PASSWORD, "-noprompt").redirectErrorStream(true).start(); + if (!keytool.waitFor(20, TimeUnit.SECONDS)) { + keytool.destroyForcibly(); + fail("Test certificate generation timed out"); + } + assertEquals(0, keytool.exitValue(), new String(keytool.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(store)) { + keyStore.load(input, TEST_PASSWORD.toCharArray()); + } + KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keys.init(keyStore, TEST_PASSWORD.toCharArray()); + TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trust.init(keyStore); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keys.getKeyManagers(), trust.getTrustManagers(), null); + return context; + } +} From 4d99cd4e84574c157457f220ed29d4e2968d984f Mon Sep 17 00:00:00 2001 From: Steve Hu Date: Wed, 28 Oct 2026 17:25:35 -0400 Subject: [PATCH 2/2] fix: enforce sidecar header policy across real handler chains --- config/hsts/README.md | 81 +++--- config/hsts/values-overlay.yml | 47 +--- pom.xml | 15 ++ src/main/resources/config/values.yml | 3 +- .../router/HstsApplicationFixture.java | 94 +++++++ .../SpecificationHstsConfigurationTest.java | 247 ++++++------------ 6 files changed, 242 insertions(+), 245 deletions(-) create mode 100644 src/test/java/com/networknt/router/HstsApplicationFixture.java diff --git a/config/hsts/README.md b/config/hsts/README.md index ab4fa8a..2dd14bb 100644 --- a/config/hsts/README.md +++ b/config/hsts/README.md @@ -1,47 +1,48 @@ -# HTTPS-only HSTS configuration +# Dedicated HTTPS ingress HSTS configuration -This opt-in overlay addresses Checkmarx A02 (`light-rest-4j` favicon HSTS) in a -consuming application using the existing `HeaderHandler`. +This opt-in [overlay](values-overlay.yml) addresses Checkmarx A02 using the existing +HeaderHandler. It is for a **dedicated HTTPS ingress instance** with a browser-trusted +certificate. It disables HTTP, including the sidecar's normal plaintext egress port +9080. **Do not apply it to the usual co-located sidecar whose application calls +http://localhost:9080**: those calls would fail even while HTTPS probes stay healthy. +Use a separate ingress instance or configure HSTS at the trusted TLS edge instead. +The packaged defaults retain HTTP egress and do not enable HSTS. -Merge [values-overlay.yml](values-overlay.yml) into the active application's -complete `values.yml`. It is not a standalone routing configuration. Preserve -any application-specific handlers, routes and response-header updates: combine -the header maps, and move `header` to the beginning of every applicable chain -rather than discarding custom chain entries. The supplied chains match the -packaged sidecar defaults. The overlay enables HTTPS, disables plaintext HTTP, -and sets `Strict-Transport-Security: max-age=31536000` without `includeSubDomains` -or `preload`. +Merge the overlay into the complete application values.yml using the normal external +configuration directory or config server. It is not a standalone configuration. +Preserve custom routes/chains and merge any existing `header.pathPrefixHeader` rules; +review overlapping prefixes so another rule cannot override the host policy. +The overlay does not copy or replace handler chains or the existing comma-string +`header.response.update` / `header.response.remove` settings. -Use a certificate trusted by the consuming browsers; the bundled development -certificate is not a production certificate. Select the merged configuration -through the application's normal external configuration directory or config -server. No running instance is changed by the presence of this overlay. +The packaged default and admin chains now start with header. Direct favicon, +specification, Swagger UI, health and module routes include it explicitly. The root +prefix response rule applies headers when the response is sent, after the proxy +copies backend headers. It enforces one HSTS value, no-store and nosniff, and removes +X-Powered-By even when a backend supplies conflicting values. Custom routes and +unsupported-method fallback chains must also run header before terminating. -The packaged sidecar's direct favicon, Swagger UI, specification, health and -module-management routes now include `header` explicitly. This closes the route -bypass that otherwise prevents configured response headers from reaching them. -The overlay also puts the response-header policy before short-circuiting -handlers in the default and admin chains. Header policy therefore reaches the -supported routes' normal, rejection and error responses. Review any custom -routes, unsupported-method fallback or proxy-generated response separately. +HeaderHandler does not distinguish HTTP from HTTPS listeners. This profile cannot +provide TLS-only HSTS in a single dual-listener process. Keep public HTTP redirect +handling outside this policy. With TLS offload, configure the trusted edge to emit +or preserve HSTS and prevent untrusted direct-origin access; client-supplied +forwarded-protocol headers do not establish trust. -The default sidecar can still use plaintext HTTP internally and does not emit -HSTS by default. Do not apply this overlay to a publicly accessible plaintext -listener: generic `HeaderHandler` does not check the request scheme. For public -HTTP-to-HTTPS redirects, keep the plaintext redirect handler outside this HSTS -chain. With TLS termination at an edge, ensure the edge preserves or emits one -HSTS header on public HTTPS responses and that the origin cannot be reached -through an untrusted direct path. Client-supplied forwarded-protocol headers -are not a trust decision. +SpecificationHstsConfigurationTest loads the packaged values and overlay from the +classpath, then initializes the real handler orchestration in isolated JVMs. It +loads header.yml through values substitution, retains production routes/chains, +and uses existing test keystores. Loopback checks cover favicon bytes, health, +spec/Swagger, admin routes and proxied success/redirect/error/not-found responses +with conflicting backend headers. A default-profile control checks plaintext +proxy access remains usable. External authentication/token integrations are disabled +only in the fixture; this is handler-pipeline qualification, not a deployment test. -`SpecificationHstsConfigurationTest` reads both the packaged values and this -overlay, checks the actual route/chain ordering, and tests the real favicon -handler and header middleware over TLS. It covers normal, redirect, not-found -and exception responses and checks the unconfigured control and preserved icon. -The TLS certificate is generated only for the test and is not checked in. +The policy intentionally omits `includeSubDomains` and `preload`; either needs a +separate domain-wide compatibility review. HSTS is learned over a secure connection, +so first-visit protection requires an appropriate preload arrangement. See +[RFC 6797](https://www.rfc-editor.org/rfc/rfc6797.html). -Before closing the partner finding, deploy the reviewed merged configuration, -capture public HTTPS headers for the favicon and other supported response -paths, confirm one intended HSTS value, and rerun the partner scan. The -configuration and loopback tests do not establish the partner deployment's -state. See [RFC 6797](https://www.rfc-editor.org/rfc/rfc6797.html). +Before closing the partner finding, deploy the reviewed configuration and capture +public HTTPS headers for the favicon, normal, redirect and error responses. Verify +one intended HSTS value and direct-origin access restrictions, then rerun the scan. +Loopback tests do not establish the partner deployment's state. diff --git a/config/hsts/values-overlay.yml b/config/hsts/values-overlay.yml index 50c4564..6cbbbab 100644 --- a/config/hsts/values-overlay.yml +++ b/config/hsts/values-overlay.yml @@ -1,37 +1,16 @@ -# Merge into the active application values.yml; do not use as a standalone routing configuration. +# Dedicated HTTPS ingress instance only. Disables HTTP egress (normally localhost:9080). +# Do NOT merge into a normal co-located dual-listener sidecar. See README.md. server.enableHttps: true server.enableHttp: false header.enabled: true -header.response.update: - Cache-Control: no-store - X-Content-Type-Options: nosniff - Strict-Transport-Security: max-age=31536000 -handler.chains: - default: - - header - - exception - - prefix - - metrics - - limit - - correlation - - killapp - - latency - - memory - - exchaos - - requestInterceptor - - audit - - token - - router - - specification - - security - - sanitizer - - validator - - proxy - admin: - - header - - exception - - correlation - - specification - - security - - body - - validator +# Prefix response rules run at response-send time, after proxy backend headers are copied. +# Preserve/merge any existing prefix rules when adopting this policy. +header.pathPrefixHeader: + /: + response: + remove: + - X-Powered-By + update: + Cache-Control: no-store + X-Content-Type-Options: nosniff + Strict-Transport-Security: max-age=31536000 diff --git a/pom.xml b/pom.xml index db9f2e9..106feb1 100644 --- a/pom.xml +++ b/pom.xml @@ -441,6 +441,21 @@ ${project.artifactId} + + + src/test/resources + + + src/main/resources/config + hsts-input + values.yml + + + config/hsts + hsts-input/overlay + values-overlay.yml + + org.codehaus.mojo diff --git a/src/main/resources/config/values.yml b/src/main/resources/config/values.yml index 0ee9686..72e4313 100644 --- a/src/main/resources/config/values.yml +++ b/src/main/resources/config/values.yml @@ -111,6 +111,7 @@ handler.handlers: handler.chains: default: + - header - exception - prefix - metrics @@ -122,7 +123,6 @@ handler.chains: - memory - exchaos # - cors - - header - requestInterceptor # - responseInterceptor - audit @@ -137,6 +137,7 @@ handler.chains: - proxy admin: + - header - exception - correlation - specification diff --git a/src/test/java/com/networknt/router/HstsApplicationFixture.java b/src/test/java/com/networknt/router/HstsApplicationFixture.java new file mode 100644 index 0000000..3e0a99d --- /dev/null +++ b/src/test/java/com/networknt/router/HstsApplicationFixture.java @@ -0,0 +1,94 @@ +package com.networknt.router; + +import com.networknt.config.Config; +import com.networknt.config.yml.YamlUtils; +import com.networknt.handler.Handler; +import com.networknt.server.ServerConfig; +import com.networknt.handler.OrchestrationHandler; +import io.undertow.Undertow; +import io.undertow.util.HttpString; +import javax.net.ssl.*; +import java.io.*; +import java.net.InetSocketAddress; +import java.nio.file.*; +import java.security.KeyStore; +import java.util.*; + +/** Isolated JVM: production handler configuration without sharing static caches with other tests. */ +public class HstsApplicationFixture { + static Map yaml(String resource) throws Exception { + try (InputStream in = HstsApplicationFixture.class.getResourceAsStream(resource)) { + return YamlUtils.loadMap(Config.getInstance().getYaml(), Objects.requireNonNull(in, resource)); + } + } + + static SSLContext tls() throws Exception { + KeyStore keys = KeyStore.getInstance("JKS"); + try (InputStream in = HstsApplicationFixture.class.getResourceAsStream("/config/server.keystore")) { + keys.load(in, "password".toCharArray()); + } + KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + km.init(keys, "password".toCharArray()); + KeyStore trust = KeyStore.getInstance("JKS"); + try (InputStream in = HstsApplicationFixture.class.getResourceAsStream("/config/client.truststore")) { + trust.load(in, "password".toCharArray()); + } + TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tm.init(trust); + SSLContext tls = SSLContext.getInstance("TLS"); + tls.init(km.getKeyManagers(), tm.getTrustManagers(), null); + return tls; + } + + static int port(Undertow server) { + return ((InetSocketAddress) server.getListenerInfo().getFirst().getAddress()).getPort(); + } + + public static void main(String[] args) throws Exception { + Path directory = Path.of(args[1]); + Undertow backend = Undertow.builder().setIoThreads(1).setWorkerThreads(2) + .addHttpListener(0, "127.0.0.1").setHandler(exchange -> { + exchange.getResponseHeaders().put(new HttpString("Strict-Transport-Security"), "max-age=0"); + exchange.getResponseHeaders().put(new HttpString("Cache-Control"), "public"); + exchange.getResponseHeaders().put(new HttpString("X-Powered-By"), "backend"); + String path = exchange.getRequestPath(); + exchange.setStatusCode(switch (path) { + case "/redirect" -> 302; case "/error" -> 500; case "/missing" -> 404; default -> 200; + }); + if (path.equals("/redirect")) exchange.getResponseHeaders().put(new HttpString("Location"), "/get"); + exchange.getResponseSender().send("controlled backend"); + }).build(); + backend.start(); + Map values = new LinkedHashMap<>(yaml("/hsts-input/values.yml")); + boolean overlay = args[0].equals("hsts"); + if (overlay) values.putAll(yaml("/hsts-input/overlay/values-overlay.yml")); + // Only external integrations are disabled. Production handlers, chains and routes are retained. + values.put("server.enableRegistry", false); + values.put("security.enableVerifyJwt", false); + values.put("unified-security.enabled", false); + values.put("openapi-validator.enabled", false); + values.put("token.enabled", false); + values.put("openapi-handler.ignoreInvalidPath", true); + values.put("proxy.hosts", "http://127.0.0.1:" + port(backend)); + values.put("proxy.metricsInjection", false); + values.put("router.metricsInjection", false); + Files.writeString(directory.resolve("values.yml"), Config.getInstance().getMapper().writeValueAsString(values)); + System.setProperty("light-4j-config-dir", directory.toString()); + Config.getInstance().clear(); + ServerConfig server = ServerConfig.load(); + if (!server.isEnableHttps() || server.isEnableHttp() == overlay) { + throw new IllegalStateException("Unexpected listener policy loaded from values"); + } + Handler.init(); + Undertow.Builder builder = Undertow.builder().setIoThreads(1).setWorkerThreads(4) + .addHttpsListener(0, "127.0.0.1", tls()).setHandler(new OrchestrationHandler()); + if (server.isEnableHttp()) builder.addHttpListener(0, "127.0.0.1"); + Undertow app = builder.build(); + app.start(); + String ports = Integer.toString(port(app)); + if (!overlay) ports += "," + ((InetSocketAddress) app.getListenerInfo().get(1).getAddress()).getPort(); + Files.writeString(directory.resolve("ready"), ports); + try { System.in.read(); } finally { app.stop(); backend.stop(); } + System.exit(0); + } +} diff --git a/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java b/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java index 276a594..dae8ea7 100644 --- a/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java +++ b/src/test/java/com/networknt/router/SpecificationHstsConfigurationTest.java @@ -1,205 +1,112 @@ package com.networknt.router; -import com.networknt.specification.FaviconHandler; -import com.networknt.config.Config; -import com.networknt.config.yml.YamlUtils; -import java.util.ArrayList; -import java.util.Map; -import java.util.LinkedHashMap; - -import com.networknt.header.HeaderHandler; -import io.undertow.Handlers; -import io.undertow.Undertow; -import io.undertow.server.HttpHandler; -import io.undertow.server.handlers.ExceptionHandler; -import io.undertow.server.handlers.ResponseCodeHandler; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.junit.jupiter.api.io.TempDir; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import java.io.InputStream; -import java.net.InetSocketAddress; import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.KeyStore; +import java.net.http.*; +import java.nio.file.*; import java.time.Duration; -import java.util.List; +import java.util.*; import java.util.concurrent.TimeUnit; - import static org.junit.jupiter.api.Assertions.*; class SpecificationHstsConfigurationTest { - private static final String HSTS = "Strict-Transport-Security"; - private static final String CONFIG_NAME = "sidecar-hsts-test-header"; - private static Map application; - private static Map merged; - private static final String POLICY = "max-age=31536000"; - // This password protects a temporary, test-generated loopback certificate only. - private static final String TEST_PASSWORD = "hsts-test-only"; - @TempDir - static Path directory; - private static Undertow configured; - private static Undertow withoutMiddleware; - private static HttpClient client; + @TempDir static Path directory; + static final List processes = new ArrayList<>(); + static HttpClient client; + static int[] configured, defaults; - @BeforeAll - static void startTlsServers() throws Exception { - application = readYaml(Path.of("src/main/resources/config/values.yml")); - merged = new LinkedHashMap<>(application); - merged.putAll(readYaml(Path.of("config/hsts/values-overlay.yml"))); - assertEquals(Boolean.TRUE, merged.get("server.enableHttps")); - assertEquals(Boolean.FALSE, merged.get("server.enableHttp")); - Config.getInstance().putInConfigCache(CONFIG_NAME, Map.of( - "enabled", merged.get("header.enabled"), "request", Map.of(), - "response", Map.of("update", merged.get("header.response.update")))); - SSLContext tls = testTlsContext(); - client = HttpClient.newBuilder().sslContext(tls).version(HttpClient.Version.HTTP_1_1) + @BeforeAll static void start() throws Exception { + client = HttpClient.newBuilder().sslContext(HstsApplicationFixture.tls()) .connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build(); - HttpHandler routes = Handlers.routing() - .get("/favicon.ico", new FaviconHandler()) - .get("/normal", exchange -> exchange.getResponseSender().send("ok")) - .get("/redirect", exchange -> { - exchange.setStatusCode(302); - exchange.getResponseHeaders().put(io.undertow.util.Headers.LOCATION, "/favicon.ico"); - exchange.endExchange(); - }) - .get("/error", exchange -> { throw new IllegalStateException("controlled test failure"); }); - HttpHandler errors = new ExceptionHandler(routes) - .addExceptionHandler(IllegalStateException.class, ResponseCodeHandler.HANDLE_500); - HeaderHandler header = new HeaderHandler(CONFIG_NAME); - assertTrue(header.isEnabled()); - header.setNext(errors); - configured = start(tls, header); - withoutMiddleware = start(tls, errors); + configured = launch("hsts"); + defaults = launch("default"); } - private static Undertow start(SSLContext tls, HttpHandler handler) { - Undertow server = Undertow.builder().setIoThreads(1).setWorkerThreads(2) - .addHttpsListener(0, "127.0.0.1", tls).setHandler(handler).build(); - server.start(); - return server; + static int[] launch(String mode) throws Exception { + Path config = Files.createDirectory(directory.resolve(mode)); + Path log = directory.resolve(mode + ".log"); + Process process = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-Dlight-4j-config-dir=" + config, "-cp", System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")), + HstsApplicationFixture.class.getName(), mode, config.toString()) + .redirectErrorStream(true).redirectOutput(log.toFile()).start(); + processes.add(process); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45); + while (!Files.exists(config.resolve("ready")) && process.isAlive() && System.nanoTime() < deadline) Thread.sleep(50); + assertTrue(Files.exists(config.resolve("ready")), () -> { + try { return Files.readString(log); } catch (Exception e) { return e.toString(); } + }); + return Arrays.stream(Files.readString(config.resolve("ready")).split(",")).mapToInt(Integer::parseInt).toArray(); } - @AfterAll - static void stopServers() { + @AfterAll static void stop() throws Exception { if (client != null) client.close(); - if (configured != null) configured.stop(); - if (withoutMiddleware != null) withoutMiddleware.stop(); - Config.getInstance().clearConfigCache(CONFIG_NAME); - } - - @Test - void faviconWithoutMiddlewareDoesNotClaimHostPolicy() throws Exception { - HttpResponse response = get(withoutMiddleware, "/favicon.ico"); - assertEquals(200, response.statusCode()); - assertTrue(response.headers().allValues(HSTS).isEmpty()); - } - - @Test - void configuredFaviconHasSingleHstsAndPreservesIcon() throws Exception { - HttpResponse response = get(configured, "/favicon.ico"); - assertPolicy(response, 200); - assertEquals("image/x-icon", response.headers().firstValue("Content-Type").orElseThrow()); - assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElseThrow()); - assertArrayEquals(get(withoutMiddleware, "/favicon.ico").body(), response.body()); - } - - @Test - void normalResponseHasHsts() throws Exception { - HttpResponse response = get(configured, "/normal"); - assertPolicy(response, 200); - assertEquals("ok", new String(response.body(), StandardCharsets.UTF_8)); + for (Process process : processes) { + if (process.isAlive()) { + process.getOutputStream().write(10); + process.getOutputStream().flush(); + if (!process.waitFor(10, TimeUnit.SECONDS)) process.destroyForcibly(); + } + } } - @Test - void httpsRedirectHasHsts() throws Exception { - HttpResponse response = get(configured, "/redirect"); - assertPolicy(response, 302); - assertEquals("/favicon.ico", response.headers().firstValue("Location").orElseThrow()); + static HttpResponse get(String scheme, int port, String path) throws Exception { + return client.send(HttpRequest.newBuilder(URI.create(scheme + "://localhost:" + port + path)) + .timeout(Duration.ofSeconds(10)).GET().build(), HttpResponse.BodyHandlers.ofByteArray()); } - @Test - void unmatchedRouteHasHsts() throws Exception { - assertPolicy(get(configured, "/not-found"), 404); + static void policy(HttpResponse response) { + assertEquals(List.of("max-age=31536000"), response.headers().allValues("Strict-Transport-Security")); + assertEquals(List.of("no-store"), response.headers().allValues("Cache-Control")); + assertEquals(List.of("nosniff"), response.headers().allValues("X-Content-Type-Options")); + assertTrue(response.headers().allValues("X-Powered-By").isEmpty()); } - @Test - void exceptionResponseHasHsts() throws Exception { - assertPolicy(get(configured, "/error"), 500); + @Test void faviconPreservesContent() throws Exception { + var response = get("https", configured[0], "/favicon.ico"); + assertEquals(200, response.statusCode()); + policy(response); + assertEquals("image/x-icon", response.headers().firstValue("Content-Type").orElseThrow()); + var control = get("https", defaults[0], "/favicon.ico"); + assertTrue(control.headers().allValues("Strict-Transport-Security").isEmpty()); + assertArrayEquals(control.body(), response.body()); } - @Test - @SuppressWarnings("unchecked") - void applicationRoutesRunTheConfiguredHeaderBeforeTerminalHandlers() { - Map> chains = (Map>) merged.get("handler.chains"); - List> paths = (List>) merged.get("handler.paths"); - assertFalse(paths.isEmpty()); - for (Map path : paths) { - List expanded = new ArrayList<>(); - for (String handler : (List) path.get("exec")) { - expanded.addAll(chains.getOrDefault(handler, List.of(handler))); - } - assertEquals("header", expanded.getFirst(), "Header must run first for " + path.get("path")); - assertEquals(1L, expanded.stream().filter("header"::equals).count()); + @Test void directAndAdminRoutesReceivePolicy() throws Exception { + for (String path : List.of("/health", "/spec.yaml", "/specui.html", "/adm/modules", "/adm/logger", "/adm/server/info")) { + var response = get("https", configured[0], path); + policy(response); + assertTrue(response.statusCode() < 500, path + " status " + response.statusCode()); } - assertTrue(paths.stream().anyMatch(path -> "/favicon.ico".equals(path.get("path")))); } - @Test - void plaintextApplicationDefaultDoesNotForceHstsPolicy() { - assertEquals(Boolean.TRUE, application.get("server.enableHttp")); - assertFalse(String.valueOf(application.get("header.response.update")).contains(HSTS)); - } - - private static Map readYaml(Path path) throws Exception { - try (InputStream input = Files.newInputStream(path)) { - return YamlUtils.loadMap(Config.getInstance().getYaml(), input); + @Test void backendCannotOverridePolicyIncludingRedirectAndErrors() throws Exception { + for (var entry : Map.of("/get", 200, "/redirect", 302, "/error", 500, "/missing", 404).entrySet()) { + var response = get("https", configured[0], entry.getKey()); + assertEquals(entry.getValue(), response.statusCode()); + assertEquals("controlled backend", new String(response.body(), java.nio.charset.StandardCharsets.UTF_8)); + policy(response); } } - private static void assertPolicy(HttpResponse response, int status) { - assertEquals(status, response.statusCode()); - assertEquals(List.of(POLICY), response.headers().allValues(HSTS)); - } - - private static HttpResponse get(Undertow server, String path) throws Exception { - int port = ((InetSocketAddress) server.getListenerInfo().getFirst().getAddress()).getPort(); - HttpRequest request = HttpRequest.newBuilder(URI.create("https://localhost:" + port + path)) - .timeout(Duration.ofSeconds(5)).GET().build(); - return client.send(request, HttpResponse.BodyHandlers.ofByteArray()); + @Test void packagedDefaultRetainsPlaintextEgress() throws Exception { + var response = get("http", defaults[1], "/get"); + assertEquals(200, response.statusCode()); + assertEquals("controlled backend", new String(response.body(), java.nio.charset.StandardCharsets.UTF_8)); + assertTrue(get("http", defaults[1], "/favicon.ico").headers().allValues("Strict-Transport-Security").isEmpty()); + assertEquals(List.of("no-store"), get("https", defaults[0], "/adm/logger").headers().allValues("Cache-Control")); } - private static SSLContext testTlsContext() throws Exception { - Path store = directory.resolve("loopback.p12"); - Process keytool = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "keytool").toString(), - "-genkeypair", "-alias", "loopback", "-keyalg", "RSA", "-keysize", "2048", - "-validity", "1", "-dname", "CN=localhost", "-ext", "SAN=dns:localhost,ip:127.0.0.1", - "-storetype", "PKCS12", "-keystore", store.toString(), "-storepass", TEST_PASSWORD, - "-keypass", TEST_PASSWORD, "-noprompt").redirectErrorStream(true).start(); - if (!keytool.waitFor(20, TimeUnit.SECONDS)) { - keytool.destroyForcibly(); - fail("Test certificate generation timed out"); - } - assertEquals(0, keytool.exitValue(), new String(keytool.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (InputStream input = Files.newInputStream(store)) { - keyStore.load(input, TEST_PASSWORD.toCharArray()); + @Test @SuppressWarnings("unchecked") void allPackagedRoutesStartWithHeaderAndOverlayPreservesChains() throws Exception { + var values = HstsApplicationFixture.yaml("/hsts-input/values.yml"); + var overlay = HstsApplicationFixture.yaml("/hsts-input/overlay/values-overlay.yml"); + assertFalse(overlay.containsKey("handler.chains")); + assertFalse(overlay.containsKey("header.response.update")); + assertEquals("X-Powered-By", values.get("header.response.remove")); + Map> chains = (Map>) values.get("handler.chains"); + for (var route : (List>) values.get("handler.paths")) { + String first = ((List) route.get("exec")).getFirst(); + assertEquals("header", chains.getOrDefault(first, List.of(first)).getFirst(), route.get("path").toString()); } - KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keys.init(keyStore, TEST_PASSWORD.toCharArray()); - TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trust.init(keyStore); - SSLContext context = SSLContext.getInstance("TLS"); - context.init(keys.getKeyManagers(), trust.getTrustManagers(), null); - return context; } }