Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions config/hsts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Dedicated HTTPS ingress HSTS configuration

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 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.

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.

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.

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.

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 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.
16 changes: 16 additions & 0 deletions config/hsts/values-overlay.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 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
# 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
15 changes: 15 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,21 @@

<build>
<finalName>${project.artifactId}</finalName>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<directory>src/main/resources/config</directory>
<targetPath>hsts-input</targetPath>
<includes><include>values.yml</include></includes>
</testResource>
<testResource>
<directory>config/hsts</directory>
<targetPath>hsts-input/overlay</targetPath>
<includes><include>values-overlay.yml</include></includes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
Expand Down
10 changes: 9 additions & 1 deletion src/main/resources/config/values.yml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ handler.handlers:

handler.chains:
default:
- header
- exception
- prefix
- metrics
Expand All @@ -122,7 +123,6 @@ handler.chains:
- memory
- exchaos
# - cors
- header
- requestInterceptor
# - responseInterceptor
- audit
Expand All @@ -137,6 +137,7 @@ handler.chains:
- proxy

admin:
- header
- exception
- correlation
- specification
Expand Down Expand Up @@ -179,12 +180,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
Expand Down Expand Up @@ -217,11 +220,13 @@ handler.paths:
- path: '/adm/modules'
method: 'get'
exec:
- header
- modules

- path: '/adm/modules'
method: 'post'
exec:
- header
- body
- configReload

Expand Down Expand Up @@ -253,14 +258,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


Expand Down
94 changes: 94 additions & 0 deletions src/test/java/com/networknt/router/HstsApplicationFixture.java
Original file line number Diff line number Diff line change
@@ -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<String, Object> 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<String, Object> 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);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.networknt.router;

import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;

class SpecificationHstsConfigurationTest {
@TempDir static Path directory;
static final List<Process> processes = new ArrayList<>();
static HttpClient client;
static int[] configured, defaults;

@BeforeAll static void start() throws Exception {
client = HttpClient.newBuilder().sslContext(HstsApplicationFixture.tls())
.connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
configured = launch("hsts");
defaults = launch("default");
}

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 stop() throws Exception {
if (client != null) client.close();
for (Process process : processes) {
if (process.isAlive()) {
process.getOutputStream().write(10);
process.getOutputStream().flush();
if (!process.waitFor(10, TimeUnit.SECONDS)) process.destroyForcibly();
}
}
}

static HttpResponse<byte[]> 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());
}

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 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 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());
}
}

@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);
}
}

@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"));
}

@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<String, List<String>> chains = (Map<String, List<String>>) values.get("handler.chains");
for (var route : (List<Map<String, Object>>) values.get("handler.paths")) {
String first = ((List<String>) route.get("exec")).getFirst();
assertEquals("header", chains.getOrDefault(first, List.of(first)).getFirst(), route.get("path").toString());
}
}
}
Loading