From 9fece8344c414fc053056fafd3c37d21d08713dc Mon Sep 17 00:00:00 2001 From: Matefodao3636 <210142123+Matefodao3636@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:45:08 -0300 Subject: [PATCH] WW-5848 Make the Boot session cookie attributes configurable Adds two struts.boot settings, read by BootSettings and applied by StrutsBootServer: - struts.boot.session.cookie.secure: true or false (default false) - struts.boot.session.cookie.sameSite: lax, strict, none or unset (default lax) The starter opens a plain HTTP listener, so the session cookie is sent without Secure, and SameSite=Lax was fixed in code. An application that runs behind an HTTPS reverse proxy can now set secure=true, and pick another SameSite value if it needs one. The defaults are unchanged: SameSite=Lax and no forced Secure. Values ignore case and surrounding spaces. Any other value, an empty one included, fails startup with a ConfigurationException that names the setting and the value. SameSite stays on Tomcat's cookie processor, as WW-5841 introduced it, so it remains the default for every cookie of the context that has no SameSite attribute of its own; Secure only reaches the session cookie. Tests cover both, and the boot-hello README and THREAT_MODEL.md describe it. Implemented with Claude Code, reviewed in two independent rounds by GPT and Gemini, and validated on Linux by GPT with the full project build. Co-Authored-By: Claude Fable 5.2 --- THREAT_MODEL.md | 9 +- apps/boot-hello/README.md | 27 +++- .../org/apache/struts2/boot/BootSettings.java | 49 +++++- .../apache/struts2/boot/StrutsBootServer.java | 18 ++- .../apache/struts2/boot/BootSettingsTest.java | 114 ++++++++++++++ .../struts2/boot/StrutsBootTomcatTest.java | 147 +++++++++++++++++- .../boot/fixture/CookieProbeAction.java | 48 ++++++ .../apache/struts2/boot/fixture/HelloApp.java | 1 + 8 files changed, 392 insertions(+), 21 deletions(-) create mode 100644 boot/src/test/java/org/apache/struts2/boot/fixture/CookieProbeAction.java diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index f6a8521aa5..f80cdd5f1b 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -119,8 +119,8 @@ framework, not by the operator. *(documented — `boot/`, `apps/boot-hello/READM - **Operator** — deploys the WAR, sets `devMode` off, restricts dev-only plugins, configures the container and JVM. **Trusted.** *(documented.)* With Boot, the operator still owns the JVM, the host, the network perimeter and the - `struts.boot.*` settings (port, bind address, context path); the container defaults - the starter applies are Struts' (§5). + `struts.boot.*` settings (port, bind address, context path, session cookie + attributes); the container defaults the starter applies are Struts' (§5). **Component families.** @@ -239,7 +239,10 @@ documented anti-pattern is `OUT-OF-MODEL`. *(documented/inferred — §14 Q-defa - `DefaultServlet` serves only an empty per-run docBase - Tomcat's base directory is a fresh owner-only temp directory, deleted on shutdown - session tracking is cookie-only - - the session cookie carries `SameSite=Lax` + - the session cookie carries `SameSite=Lax`, as does any other cookie without a + `SameSite` attribute of its own (override `struts.boot.session.cookie.sameSite`) + - `Secure` is not forced on the session cookie (override + `struts.boot.session.cookie.secure`) - `devMode` is never switched on A deviation from these defaults is a Struts finding. Anything the developer adds on diff --git a/apps/boot-hello/README.md b/apps/boot-hello/README.md index 20a333f6a7..d2f8309c37 100644 --- a/apps/boot-hello/README.md +++ b/apps/boot-hello/README.md @@ -43,15 +43,32 @@ not deployed to Maven repositories; build it from source. Settings are read from `struts.properties` on the classpath. A `--key=value` argument overrides the file. -| Key | Default | Meaning | -|----------------------------|---------|--------------------------------------------| -| `struts.boot.port` | `8080` | HTTP port; `0` picks a free port | -| `struts.boot.context-path` | `""` | Context path the application is served at | -| `struts.boot.address` | all | Interface to listen on, e.g. `127.0.0.1` | +| Key | Default | Meaning | +|---------------------------------------|---------|------------------------------------------------------------| +| `struts.boot.port` | `8080` | HTTP port; `0` picks a free port | +| `struts.boot.context-path` | `""` | Context path the application is served at | +| `struts.boot.address` | all | Interface to listen on, e.g. `127.0.0.1` | +| `struts.boot.session.cookie.secure` | `false` | `true` marks the session cookie `Secure` | +| `struts.boot.session.cookie.sameSite` | `lax` | `SameSite` attribute: `lax`, `strict`, `none` or `unset` | + +The values of the two session cookie settings ignore case and surrounding spaces. Any other value, an empty one +included, stops the application at startup with an error that names the setting and the value. Keys are matched exactly: +a key that is not in this table, `struts.boot.session.cookie.samesite` for example, is ignored, and so is an argument +without `=`. ## Defaults worth knowing - Tomcat listens on all interfaces, not only on localhost; set `struts.boot.address` to restrict it. +- Sessions are tracked by cookie only. The session cookie carries `SameSite=Lax`, and `Secure` is not forced on it: + over the plain HTTP listener the starter opens, it is sent without `Secure`. Set + `struts.boot.session.cookie.secure=true` when TLS ends in front of the application, at a reverse proxy for example. +- `struts.boot.session.cookie.sameSite` sets the default of Tomcat's cookie processor, so it also applies to every + other cookie the application adds without a `SameSite` attribute of its own. With `unset` the processor adds no + `SameSite` attribute; one the application sets on a cookie itself is kept. +- For `SameSite=None`, the cookie reaching the browser must also carry `Secure`. Set + `struts.boot.session.cookie.secure=true` in Boot, or configure your HTTPS reverse proxy to add the `Secure` + attribute. The starter does not check this combination. The `secure` setting only reaches the session cookie; a + cookie the application adds itself needs its own `Secure`. - Error pages show the status only, without stack traces or the Tomcat version. - `struts.devMode` stays off. - Each start uses a fresh temporary base directory (`struts-boot-`) that is deleted on shutdown. diff --git a/boot/src/main/java/org/apache/struts2/boot/BootSettings.java b/boot/src/main/java/org/apache/struts2/boot/BootSettings.java index 8accb60d4d..c48d2aeb76 100644 --- a/boot/src/main/java/org/apache/struts2/boot/BootSettings.java +++ b/boot/src/main/java/org/apache/struts2/boot/BootSettings.java @@ -22,6 +22,8 @@ import java.io.IOException; import java.io.InputStream; +import java.util.List; +import java.util.Locale; import java.util.Optional; import java.util.Properties; @@ -31,16 +33,23 @@ public final class BootSettings { private static final String PORT_KEY = PREFIX + "port"; private static final String CONTEXT_PATH_KEY = PREFIX + "context-path"; private static final String ADDRESS_KEY = PREFIX + "address"; + private static final String SESSION_COOKIE_SECURE_KEY = PREFIX + "session.cookie.secure"; + private static final String SESSION_COOKIE_SAME_SITE_KEY = PREFIX + "session.cookie.sameSite"; + private static final List SAME_SITE_VALUES = List.of("lax", "strict", "none", "unset"); private static final String ARGUMENT_PREFIX = "--"; private final int port; private final String contextPath; private final String address; + private final boolean sessionCookieSecure; + private final String sessionCookieSameSite; - private BootSettings(int port, String contextPath, String address) { + private BootSettings(int port, String contextPath, String address, boolean sessionCookieSecure, String sessionCookieSameSite) { this.port = port; this.contextPath = contextPath; this.address = address; + this.sessionCookieSecure = sessionCookieSecure; + this.sessionCookieSameSite = sessionCookieSameSite; } public static BootSettings load(String[] args) { @@ -56,7 +65,9 @@ public static BootSettings load(Properties fileProperties, String[] args) { return new BootSettings( parsePort(merged.getProperty(PORT_KEY, "8080")), normaliseContextPath(merged.getProperty(CONTEXT_PATH_KEY, "")), - blankToNull(merged.getProperty(ADDRESS_KEY))); + blankToNull(merged.getProperty(ADDRESS_KEY)), + parseSecure(merged.getProperty(SESSION_COOKIE_SECURE_KEY, "false")), + parseSameSite(merged.getProperty(SESSION_COOKIE_SAME_SITE_KEY, "lax"))); } public int port() { @@ -71,6 +82,20 @@ public Optional address() { return Optional.ofNullable(address); } + /** Whether {@code Secure} is forced on the session cookie; {@code false} unless configured. */ + public boolean sessionCookieSecure() { + return sessionCookieSecure; + } + + /** + * The {@code SameSite} value, in lower case, the container adds to the session cookie and to any + * other cookie without a {@code SameSite} attribute of its own: {@code lax} (the default), + * {@code strict}, {@code none}, or {@code unset} to add none. + */ + public String sessionCookieSameSite() { + return sessionCookieSameSite; + } + private static void applyArgument(Properties target, String arg) { if (!arg.startsWith(ARGUMENT_PREFIX + PREFIX)) { return; @@ -105,6 +130,26 @@ private static int parsePort(String value) { } } + private static boolean parseSecure(String value) { + String normalised = value.trim().toLowerCase(Locale.ROOT); + if (normalised.equals("true")) { + return true; + } + if (normalised.equals("false")) { + return false; + } + throw new ConfigurationException("Invalid " + SESSION_COOKIE_SECURE_KEY + ": '" + value + "' is not true or false"); + } + + private static String parseSameSite(String value) { + String normalised = value.trim().toLowerCase(Locale.ROOT); + if (!SAME_SITE_VALUES.contains(normalised)) { + throw new ConfigurationException("Invalid " + SESSION_COOKIE_SAME_SITE_KEY + ": '" + value + + "' is not one of " + String.join(", ", SAME_SITE_VALUES)); + } + return normalised; + } + private static Properties readStrutsProperties() { Properties properties = new Properties(); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("struts.properties")) { diff --git a/boot/src/main/java/org/apache/struts2/boot/StrutsBootServer.java b/boot/src/main/java/org/apache/struts2/boot/StrutsBootServer.java index 46935e34b3..5b71ec3e36 100644 --- a/boot/src/main/java/org/apache/struts2/boot/StrutsBootServer.java +++ b/boot/src/main/java/org/apache/struts2/boot/StrutsBootServer.java @@ -74,7 +74,7 @@ static StrutsBootServer start(ActionRegistry registry, BootSettings settings) { hideErrorReportDetails(tomcat); Path docBase = Files.createDirectory(baseDir.resolve("webapp")); Context context = tomcat.addContext(settings.contextPath(), docBase.toString()); - restrictSessionTracking(context); + restrictSessionTracking(context, settings); context.addServletContainerInitializer( (classes, servletContext) -> servletContext.setAttribute(ActionRegistry.SERVLET_CONTEXT_ATTRIBUTE, registry), null); @@ -182,16 +182,22 @@ private static void assertContextStarted(Context context, CapturingStrutsFilter } /** - * Restricts the embedded context to cookie-only session tracking with {@code SameSite=Lax}; - * Secure is left to the operator's TLS setup. + * Restricts the embedded context to cookie-only session tracking and applies the session cookie + * settings: {@code SameSite=Lax} and no forced {@code Secure} unless configured otherwise, see + * {@link BootSettings#sessionCookieSameSite()} and {@link BootSettings#sessionCookieSecure()}. + * {@code SameSite} is set on the cookie processor, as before, so it stays the default for every + * cookie of the context that has no {@code SameSite} attribute of its own. */ - private static void restrictSessionTracking(Context context) { + private static void restrictSessionTracking(Context context, BootSettings settings) { // Tomcat defaults to COOKIE+URL when no web.xml sets ; keep cookies only. context.addServletContainerInitializer( - (classes, servletContext) -> servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)), + (classes, servletContext) -> { + servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); + servletContext.getSessionCookieConfig().setSecure(settings.sessionCookieSecure()); + }, null); Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor(); - cookieProcessor.setSameSiteCookies("lax"); + cookieProcessor.setSameSiteCookies(settings.sessionCookieSameSite()); context.setCookieProcessor(cookieProcessor); } diff --git a/boot/src/test/java/org/apache/struts2/boot/BootSettingsTest.java b/boot/src/test/java/org/apache/struts2/boot/BootSettingsTest.java index 593be770f9..8a5bc61cdc 100644 --- a/boot/src/test/java/org/apache/struts2/boot/BootSettingsTest.java +++ b/boot/src/test/java/org/apache/struts2/boot/BootSettingsTest.java @@ -119,4 +119,118 @@ public void testNonNumericPortThrows() { assertThatThrownBy(() -> BootSettings.load(fileProperties, args)) .isInstanceOf(ConfigurationException.class); } + + @Test + public void testSessionCookieDefaults() { + BootSettings settings = BootSettings.load(new Properties(), new String[0]); + + assertThat(settings.sessionCookieSecure()).isFalse(); + assertThat(settings.sessionCookieSameSite()).isEqualTo("lax"); + } + + @Test + public void testSessionCookieSecureFromFile() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.secure", "true"); + + assertThat(BootSettings.load(file, new String[0]).sessionCookieSecure()).isTrue(); + } + + @Test + public void testSessionCookieSecureArgumentBeatsFile() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.secure", "true"); + + BootSettings settings = BootSettings.load(file, new String[]{"--struts.boot.session.cookie.secure=false"}); + + assertThat(settings.sessionCookieSecure()).isFalse(); + } + + @Test + public void testSessionCookieSecureIgnoresCaseAndSpaces() { + assertThat(sessionCookieSecure(" TRUE ")).isTrue(); + assertThat(sessionCookieSecure("False")).isFalse(); + } + + @Test + public void testSessionCookieSameSiteValues() { + assertThat(sessionCookieSameSite("lax")).isEqualTo("lax"); + assertThat(sessionCookieSameSite("strict")).isEqualTo("strict"); + assertThat(sessionCookieSameSite("none")).isEqualTo("none"); + assertThat(sessionCookieSameSite("unset")).isEqualTo("unset"); + assertThat(sessionCookieSameSite(" Strict ")).isEqualTo("strict"); + assertThat(sessionCookieSameSite("NONE")).isEqualTo("none"); + } + + @Test + public void testSessionCookieSameSiteFromFile() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.sameSite", "unset"); + + assertThat(BootSettings.load(file, new String[0]).sessionCookieSameSite()).isEqualTo("unset"); + } + + @Test + public void testSessionCookieSameSiteArgumentBeatsFile() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.sameSite", "strict"); + + BootSettings settings = BootSettings.load(file, new String[]{"--struts.boot.session.cookie.sameSite=none"}); + + assertThat(settings.sessionCookieSameSite()).isEqualTo("none"); + } + + private static boolean sessionCookieSecure(String value) { + return BootSettings.load(new Properties(), new String[]{"--struts.boot.session.cookie.secure=" + value}) + .sessionCookieSecure(); + } + + private static String sessionCookieSameSite(String value) { + return BootSettings.load(new Properties(), new String[]{"--struts.boot.session.cookie.sameSite=" + value}) + .sessionCookieSameSite(); + } + + @Test + public void testInvalidSessionCookieSecureThrows() { + for (String value : new String[]{"yes", "1", "", " "}) { + String[] args = {"--struts.boot.session.cookie.secure=" + value}; + assertThatThrownBy(() -> BootSettings.load(new Properties(), args)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.secure") + .hasMessageContaining("'" + value + "'"); + } + } + + @Test + public void testInvalidSessionCookieSameSiteThrows() { + for (String value : new String[]{"bogus", "true", "", " "}) { + String[] args = {"--struts.boot.session.cookie.sameSite=" + value}; + assertThatThrownBy(() -> BootSettings.load(new Properties(), args)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.sameSite") + .hasMessageContaining("'" + value + "'"); + } + } + + @Test + public void testInvalidSessionCookieSecureFromFileThrows() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.secure", "on"); + + assertThatThrownBy(() -> BootSettings.load(file, new String[0])) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.secure") + .hasMessageContaining("'on'"); + } + + @Test + public void testInvalidSessionCookieSameSiteFromFileThrows() { + Properties file = new Properties(); + file.setProperty("struts.boot.session.cookie.sameSite", "relaxed"); + + assertThatThrownBy(() -> BootSettings.load(file, new String[0])) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.sameSite") + .hasMessageContaining("'relaxed'"); + } } diff --git a/boot/src/test/java/org/apache/struts2/boot/StrutsBootTomcatTest.java b/boot/src/test/java/org/apache/struts2/boot/StrutsBootTomcatTest.java index d693b3fb90..1835b63181 100644 --- a/boot/src/test/java/org/apache/struts2/boot/StrutsBootTomcatTest.java +++ b/boot/src/test/java/org/apache/struts2/boot/StrutsBootTomcatTest.java @@ -19,6 +19,7 @@ package org.apache.struts2.boot; import org.apache.struts2.boot.fixture.BrokenApp; +import org.apache.struts2.boot.fixture.CookieProbeAction; import org.apache.struts2.boot.fixture.HelloApp; import org.apache.struts2.boot.fixture.UserAction; import org.apache.struts2.config.ConfigurationException; @@ -42,6 +43,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -125,13 +127,112 @@ public void testErrorPageHidesStackTraceAndServerInfo() throws Exception { assertThat(response.body()).doesNotContain("at org.apache").doesNotContain("Apache Tomcat/"); } - /** The session cookie carries {@code SameSite=Lax}. */ + /** By default the session cookie carries {@code SameSite=Lax} and no {@code Secure}. */ @Test - public void testSessionCookieHasSameSiteLax() throws Exception { - HttpResponse response = get(server.baseUrl() + "/sessionProbe.action"); + public void testSessionCookieDefaultsToSameSiteLaxWithoutSecure() throws Exception { + assertThat(sessionCookieAttributes(server)).contains("HttpOnly", "SameSite=Lax").doesNotContain("Secure"); + } + + @Test + public void testSessionCookieSecureTrueAddsSecure() throws Exception { + assertThat(sessionCookieAttributesWith("--struts.boot.session.cookie.secure=true")) + .contains("Secure", "HttpOnly", "SameSite=Lax"); + } + + @Test + public void testSessionCookieSecureFalseOmitsSecure() throws Exception { + assertThat(sessionCookieAttributesWith("--struts.boot.session.cookie.secure=false")) + .contains("HttpOnly", "SameSite=Lax").doesNotContain("Secure"); + } + + @Test + public void testSessionCookieSameSiteLax() throws Exception { + assertThat(sameSiteAttributesWith("--struts.boot.session.cookie.sameSite=lax")).containsExactly("SameSite=Lax"); + } + + @Test + public void testSessionCookieSameSiteStrict() throws Exception { + assertThat(sameSiteAttributesWith("--struts.boot.session.cookie.sameSite=strict")).containsExactly("SameSite=Strict"); + } - assertThat(response.headers().firstValue("Set-Cookie")).hasValueSatisfying(cookie -> - assertThat(cookie).contains("SameSite=Lax")); + @Test + public void testSessionCookieSameSiteNone() throws Exception { + assertThat(sameSiteAttributesWith("--struts.boot.session.cookie.sameSite=none")).containsExactly("SameSite=None"); + } + + /** {@code unset} sends no {@code SameSite} attribute at all. */ + @Test + public void testSessionCookieSameSiteUnset() throws Exception { + assertThat(sameSiteAttributesWith("--struts.boot.session.cookie.sameSite=unset")).isEmpty(); + } + + @Test + public void testSessionCookieSecureWithSameSiteNone() throws Exception { + assertThat(sessionCookieAttributesWith("--struts.boot.session.cookie.secure=true", + "--struts.boot.session.cookie.sameSite=none")).contains("Secure", "HttpOnly", "SameSite=None"); + } + + /** By default a cookie the application adds without its own {@code SameSite} gets {@code SameSite=Lax} too. */ + @Test + public void testApplicationCookieDefaultsToSameSiteLax() throws Exception { + HttpResponse response = get(server.baseUrl() + "/cookieProbe.action"); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(cookieAttributes(response, CookieProbeAction.PLAIN_COOKIE)).containsExactly("SameSite=Lax"); + assertThat(cookieAttributes(response, CookieProbeAction.OWN_SAME_SITE_COOKIE)).containsExactly("SameSite=Strict"); + } + + /** + * {@code sameSite} is the default for every cookie without its own {@code SameSite}, while + * {@code secure} only reaches the session cookie. + */ + @Test + public void testSameSiteSettingAppliesToApplicationCookiesButSecureDoesNot() throws Exception { + try (StrutsBootServer configured = StrutsBoot.start(HelloApp.class, loopbackWith( + "--struts.boot.session.cookie.secure=true", "--struts.boot.session.cookie.sameSite=none"))) { + HttpResponse response = get(configured.baseUrl() + "/cookieProbe.action"); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(cookieAttributes(response, CookieProbeAction.PLAIN_COOKIE)).containsExactly("SameSite=None"); + assertThat(cookieAttributes(response, CookieProbeAction.OWN_SAME_SITE_COOKIE)).containsExactly("SameSite=Strict"); + } + } + + /** {@code unset} adds nothing, and leaves a {@code SameSite} the application set itself alone. */ + @Test + public void testSameSiteUnsetKeepsApplicationCookieAttributes() throws Exception { + try (StrutsBootServer configured = StrutsBoot.start(HelloApp.class, loopbackWith( + "--struts.boot.session.cookie.sameSite=unset"))) { + HttpResponse response = get(configured.baseUrl() + "/cookieProbe.action"); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(cookieAttributes(response, CookieProbeAction.PLAIN_COOKIE)).isEmpty(); + assertThat(cookieAttributes(response, CookieProbeAction.OWN_SAME_SITE_COOKIE)).containsExactly("SameSite=Strict"); + } + } + + @Test + public void testInvalidSessionCookieSecureFailsStartup() throws Exception { + Set before = bootTempDirs(); + + assertThatThrownBy(() -> startAndClose("--struts.boot.session.cookie.secure=yes")) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.secure") + .hasMessageContaining("'yes'"); + + assertThat(bootTempDirs()).isEqualTo(before); + } + + @Test + public void testInvalidSessionCookieSameSiteFailsStartup() throws Exception { + Set before = bootTempDirs(); + + assertThatThrownBy(() -> startAndClose("--struts.boot.session.cookie.sameSite=bogus")) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("struts.boot.session.cookie.sameSite") + .hasMessageContaining("'bogus'"); + + assertThat(bootTempDirs()).isEqualTo(before); } /** A session id supplied only in the URL is not resumed; the cookie-based flow still is. */ @@ -160,6 +261,42 @@ private static String extractSessionId(HttpResponse response) { return setCookie.substring("JSESSIONID=".length(), setCookie.indexOf(';')); } + private static List sameSiteAttributesWith(String... arguments) throws IOException, InterruptedException { + return sessionCookieAttributesWith(arguments).stream() + .filter(attribute -> attribute.startsWith("SameSite")) + .collect(Collectors.toList()); + } + + private static List sessionCookieAttributesWith(String... arguments) throws IOException, InterruptedException { + try (StrutsBootServer configured = StrutsBoot.start(HelloApp.class, loopbackWith(arguments))) { + return sessionCookieAttributes(configured); + } + } + + /** The attributes of the session cookie a new session gets, without the {@code JSESSIONID=...} pair. */ + private static List sessionCookieAttributes(StrutsBootServer target) throws IOException, InterruptedException { + return cookieAttributes(get(target.baseUrl() + "/sessionProbe.action"), "JSESSIONID"); + } + + /** The attributes of the one {@code Set-Cookie} header for the named cookie, without the name=value pair. */ + private static List cookieAttributes(HttpResponse response, String cookieName) { + List headers = response.headers().allValues("Set-Cookie").stream() + .filter(header -> header.startsWith(cookieName + "=")) + .collect(Collectors.toList()); + assertThat(headers).as("Set-Cookie headers for %s", cookieName).hasSize(1); + return Stream.of(headers.get(0).split(";")).skip(1).map(String::trim).collect(Collectors.toList()); + } + + /** Starts a server and closes it at once, so a start that wrongly succeeds leaves nothing running. */ + private static void startAndClose(String... arguments) { + StrutsBoot.start(HelloApp.class, loopbackWith(arguments)).close(); + } + + private static String[] loopbackWith(String... arguments) { + return Stream.concat(Stream.of("--struts.boot.port=0", "--struts.boot.address=127.0.0.1"), Stream.of(arguments)) + .toArray(String[]::new); + } + @Test public void testAddressRestrictsListeningInterface() throws Exception { try (StrutsBootServer local = StrutsBoot.start(HelloApp.class, "--struts.boot.port=0", "--struts.boot.address=127.0.0.1")) { diff --git a/boot/src/test/java/org/apache/struts2/boot/fixture/CookieProbeAction.java b/boot/src/test/java/org/apache/struts2/boot/fixture/CookieProbeAction.java new file mode 100644 index 0000000000..9e02b9566f --- /dev/null +++ b/boot/src/test/java/org/apache/struts2/boot/fixture/CookieProbeAction.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.boot.fixture; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.struts2.action.ServletResponseAware; + +/** + * Adds two cookies of the application's own, one plain and one with its own {@code SameSite} + * attribute, so a test can tell which cookie attributes the container adds to them. + */ +public class CookieProbeAction implements ServletResponseAware { + + public static final String PLAIN_COOKIE = "plainProbe"; + public static final String OWN_SAME_SITE_COOKIE = "ownSameSiteProbe"; + + private HttpServletResponse response; + + public String execute() { + response.addCookie(new Cookie(PLAIN_COOKIE, "1")); + Cookie ownSameSite = new Cookie(OWN_SAME_SITE_COOKIE, "1"); + ownSameSite.setAttribute("SameSite", "Strict"); + response.addCookie(ownSameSite); + return "success"; + } + + @Override + public void withServletResponse(HttpServletResponse response) { + this.response = response; + } +} diff --git a/boot/src/test/java/org/apache/struts2/boot/fixture/HelloApp.java b/boot/src/test/java/org/apache/struts2/boot/fixture/HelloApp.java index 0edcc305ec..93dab9e0f3 100644 --- a/boot/src/test/java/org/apache/struts2/boot/fixture/HelloApp.java +++ b/boot/src/test/java/org/apache/struts2/boot/fixture/HelloApp.java @@ -30,6 +30,7 @@ public void actions(ActionRegistry actions) { actions.action("hello", HelloAction.class).success("hello.ftl"); actions.action("boom", ThrowingAction.class).success("hello.ftl"); actions.action("sessionProbe", SessionProbeAction.class).success("sessionProbe.ftl"); + actions.action("cookieProbe", CookieProbeAction.class).success("hello.ftl"); actions.namespace("/admin", admin -> { admin.action("users", UserAction.class).method("list").success("admin/users.ftl"); admin.action("saveUser", UserAction.class).method("save").httpMethods(POST).redirectAction("success", "users");