diff --git a/CHANGELOG.md b/CHANGELOG.md index 99c4c42..0fce872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,77 @@ All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). +## [1.1.1] — 2026-10-29 + +_A patch release: the slow-request-body limit 1.1.0 introduced now covers form posts and multipart uploads too, and +after a restore the Backups screen shows how the site is reached, for review._ + +### Upgrading — read this first + +**From `1.1.0`: a kernel upgrade, no flag.** From `1.0.1` or `1.0.0`, read `1.1.0`'s *Upgrading* first (behind a +reverse proxy its step 1 matters), then install this release directly: `1.1.0` itself is not needed in between. Paths +are the installer defaults (`/opt/runway`, `/opt/runway-data`). + +**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside** +`external/plugins/`. + +**2. Upgrade the kernel:** + +```bash +chmod +x runway-1.1.1.bin +sudo ./runway-1.1.1.bin -y +``` + +The essential plugin moves with the kernel to `1.1.1` (its descriptor changes in version only, and its jar is +rebuilt), so the installer refreshes it; expect these lines, once: + +``` +refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up) +plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback) +plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback) +keeping the bundled plugins in the release: /opt/runway-1.1.1/seed/ (the repair copy — Administration §12) +``` + +**3. Check.** +- **About Runway** shows `1.1.1`. +- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.1`. +- The start log says `request bodies slower than 4096 bytes/s are refused (runway.http.min-request-data-rate)`, with + your value if you changed it. + +**4. Rollback**, if needed: `sudo bash runway-1.1.0.bin -y` puts 1.1.0 back, its protection files included; slow form +posts are then held until the idle timeout again. Nothing this release saves is read differently by 1.1.0. + +### Fixed + +- **Slow request bodies are refused on every path, as 1.1.0 said they would be.** In 1.1.0 + `runway.http.min-request-data-rate` was enforced only where a body was read as a stream. Form posts — every login + form, the console's forms, a plugin's form — and multipart uploads were read past it, so a client trickling one in + still held a request thread until the 30-second idle timeout, as in 1.0.1. Runway now checks the rate on every read + of a request body and answers `408 Request Timeout`: within about two seconds for a steady drip (measured: form and + multipart posts at 20 bytes a second, on both login pages and a plugin's form route), and for a client that pauses + between packets when its next packet arrives, within one idle timeout. Only time spent waiting for the client + counts, and a body that has arrived complete is never refused, however late its last packet came. A proxy that + buffers the whole request body before forwarding it kept such clients off Runway already, in 1.1.0 too. +- **Sending part of a body fast no longer buys a long drip.** 1.1.0 averaged over the whole body, so a client that + sent most of a large one at full speed could then drip the rest for the body's size divided by the rate (16 MiB at + 4 KiB/s: over an hour). Bytes sent early now earn at most 30 seconds of waiting. +- **A request refused for a slow body is answered `408`.** Depending on how the code above handled the failed read, + 1.1.0 could answer it `400` (a form parser's "unable to parse") or an empty `200`. + +### Changed + +- **After a restore, the Backups screen shows how the site is reached.** On the application console, after a restore + or after creating a site from a backup, the screen shows the site's hosts and base URL as they now are, with the + same editor as **Sites → Edit hosts**: a restore made there brings back the hosts and base URL saved in the backup, + which may not be how this installation reaches the site. On a site's own console the hosts are shown read-only: a + restore made there keeps them. See `docs/ADMINISTRATION.md` §10. + +### Documentation + +- **Exempting a same-host proxy's health check from the rate limit** (`docs/ADMINISTRATION.md` §12.4): the proxy sends + its check with a fixed `X-Forwarded-For` that no visitor can produce, and that one address is listed in protection's + allowlist, so the check never shares a rate-limit bucket with a local crawl and loopback stays limited. + ## [1.1.0] — 2026-10-29 _A minor release: plugins can keep their data in PostgreSQL or MariaDB through the new database plugins, platform diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index f74becd..15964ba 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -710,7 +710,7 @@ from the configuration metadata shipped in the jar. | `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password or OAuth2 client secret, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. | | `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` at all (still only from trusted peers; the standard `Forwarded` header is never read) — see **§7**. | | `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. | -| `runway.http.min-request-data-rate` | `4096` | The slowest a request body may arrive, in **bytes per second**, before Runway answers `408 Request Timeout` and frees the request thread. Without it a client sending a byte now and then kept a thread for as long as it liked (the idle timeout only limits one stalled read). Measured from the body's first byte on what has arrived, so a server slow to start reading is never blamed. 4096 (4 KiB/s) is below any real connection; `0` turns the check off. Set on **Settings → Server settings → Request limits**; applies after a restart. | +| `runway.http.min-request-data-rate` | `4096` | The slowest a request body may arrive, in **bytes per second**, before Runway answers `408 Request Timeout` and frees the request thread. It applies to every body — login and other forms, multipart uploads, raw bodies alike. Without it a client sending a byte now and then kept a thread for as long as it liked (the idle timeout only limits one stalled read). Only the time spent waiting for the client counts, from the first second of waiting on, so a server slow to start reading is never blamed, and a body that has arrived complete is never refused, however late its last packet came. Sending part of a body fast earns at most 30 seconds of waiting, so a large body cannot buy a long drip; a client pausing between packets is cut when its next packet arrives, within one idle timeout. 4096 (4 KiB/s) is below any real connection; `0` turns the check off. Set on **Settings → Server settings → Request limits**; applies after a restart. | | `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. | | `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. | | `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. | @@ -1588,7 +1588,10 @@ wherever a site gets hosts: creating a site, installing a demo, and creating a s malformed host or one another site answers on, before anything is created. Restoring a backup brings back the hosts and base URL the site had when the backup was taken when it is made from the application console (a host given to another site since then is left off, the log says which: `restored site '…' without host(s) […]`, and you -can add it back with **Edit hosts** once it is free). A restore made from the site's own console keeps the hosts and +can add it back with **Edit hosts** once it is free). After such a restore, and after creating a site from a backup, +the Backups screen shows the site's hosts and base URL **as they now are**, with the same editor as **Edit hosts**: +check them before anything else, because a backup taken on another installation, or before the site moved, brings +back how it was reached then. A restore made from the site's own console keeps the hosts and base URL the site has: how a site is reached is yours to set, never the site manager's, and a backup file is theirs to write. A host is a plain DNS name: no scheme, path, port (`example.com:8080`), wildcard (`*.example.com`) or underscore, and an international name is written in its @@ -2431,6 +2434,24 @@ runway: - "198.51.100.7" # the audit runner ``` +**A health check from a proxy on the same host.** Behind a same-host reverse proxy, the proxy's own health check +(`GET /actuator/health` or a site's `/__health`) usually reaches Runway from loopback with no `X-Forwarded-For`, so it +shares one rate-limit bucket with everything else run on that host — a local crawl or audit can then earn the check +`429`s and push the proxy towards marking the server down. Exempt the check alone, not loopback: have the proxy send +it with a fixed `X-Forwarded-For` from a documentation range, and list that address here. No visitor can pose as +it: on real traffic the proxy adds the visitor's own address to the right of anything the visitor sent (or replaces +the header), and Runway reads the header from the right. With HAProxy 2.2 or later: + +``` +backend runway + option httpchk + http-check send meth GET uri /actuator/health ver HTTP/1.1 hdr Host www.example.com hdr X-Forwarded-For 192.0.2.53 +``` + +and `192.0.2.53` in `allowlist`. Loopback must be in `runway.proxy.trusted-cidrs` (it is, for a same-host proxy); +leave the probe's address out of it, which is for real proxies only. Checking +`/actuator/health` from outside the proxy (a monitoring service) needs no header: list that service's own address. + > **If you are blocked, stop — do not keep probing.** Once an address is auto-blocked, requests no longer > reach the rate limiter at all; they hit the blocklist. So the `rate-limit` counter freezes while > `blocklist-auto` keeps climbing, and continued probing simply confirms the block rather than measuring it. diff --git a/docs/SETTINGS-REFERENCE.md b/docs/SETTINGS-REFERENCE.md index 8ec37d3..87b3851 100644 --- a/docs/SETTINGS-REFERENCE.md +++ b/docs/SETTINGS-REFERENCE.md @@ -47,7 +47,7 @@ How large a request may be. Applies after a restart. | Setting | Key | What it does | Values | |---|---|---|---| | Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` | -| Slowest request body (bytes per second) *(Advanced)* | `runway.http.min-request-data-rate` | A request body arriving more slowly is answered 408 Request Timeout, so a client sending a byte now and then cannot hold a request thread. Measured on what has arrived since the body's first byte. Default 4096; 0 turns the check off. | whole number from 0 to 1048576; default `4096` | +| Slowest request body (bytes per second) *(Advanced)* | `runway.http.min-request-data-rate` | A request body arriving more slowly is answered 408 Request Timeout: login and other forms, uploads and raw bodies alike, so a client sending a byte now and then cannot keep a request thread. Only time spent waiting for the client counts, and a body that has arrived complete is never refused. Sending part of a body fast earns at most 30 seconds of waiting. Default 4096; 0 turns the check off. | whole number from 0 to 1048576; default `4096` | | Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` | | Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` | | Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` | diff --git a/docs/SITE-MANAGER-GUIDE.md b/docs/SITE-MANAGER-GUIDE.md index 0237563..849d6ae 100644 --- a/docs/SITE-MANAGER-GUIDE.md +++ b/docs/SITE-MANAGER-GUIDE.md @@ -1326,7 +1326,8 @@ Restore is safe by design: the platform first checks the file is a genuine, comp backup and only then swaps it in, in one step. **A corrupt, empty, or wrong file is rejected and your live site is left exactly as it was** — a failed or interrupted restore never leaves you with a half-restored or missing site. After a successful restore the site reflects the -backup immediately (no restart). +backup immediately (no restart), and the Backups screen shows the site's host names and base URL for you to check: a restore made here keeps them as +they were (how the site is reached is set by the platform operator), so if they look wrong, ask the operator. A backup made on a **newer** version of the platform than the one your site runs on is refused the same way, with the message *"This backup was made by a newer version of Runway … Ask the diff --git a/pom.xml b/pom.xml index e839227..1a00683 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ mx.quest runway - 1.1.0 + 1.1.1 pom Runway @@ -42,7 +42,7 @@ extended timestamp through the build JVM's default time zone, so the same source built in CST and in UTC differed by exactly 6 h inside the exec jar (found 2026-10-17 on a second host). .mvn/jvm.config pins -Duser.timezone=UTC for the Maven JVM, which removes the host's zone. --> - 2026-10-29T15:02:00Z + 2026-10-29T17:30:00Z UTF-8 + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/backups.html b/runway-app/src/main/resources/templates/operator/app/backups.html index dab6b1e..dfc7de3 100644 --- a/runway-app/src/main/resources/templates/operator/app/backups.html +++ b/runway-app/src/main/resources/templates/operator/app/backups.html @@ -16,6 +16,38 @@ +
+

Review how the site is reached

+
+

The restore applied the hosts and base URL saved in the + backup. Check them, and correct them here if this installation reaches the site differently.

+
+
Hosts
+
example.com
+
Base URL
+
https://example.com
+
+
+ +
+
+ + + Comma-separated. +
+
+ + + The origin of the site's absolute links. +
+
+ +
+
+
+

Create a site from a backup

diff --git a/runway-app/src/main/resources/templates/operator/app/backups.th.xml b/runway-app/src/main/resources/templates/operator/app/backups.th.xml index 339c478..d549966 100644 --- a/runway-app/src/main/resources/templates/operator/app/backups.th.xml +++ b/runway-app/src/main/resources/templates/operator/app/backups.th.xml @@ -5,6 +5,27 @@ + + + + + + + + + + + + + + + + + + Edit hosts and changes the site. + */ + @Test + void aRestoreIsFollowedByTheRestoredHostsWithTheirEditor() throws Exception { + Site original = sites.find("acme").orElseThrow(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + backups.backup("acme", baos); // carries acme.test and https://acme.test + try { + sites.save(new Site("acme", "Acme", List.of("acme.live"), Locale.ENGLISH, List.of(Locale.ENGLISH), null, + SiteStatus.ACTIVE)); + MockHttpSession admin = sessionFor("admin"); + MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray()); + mvc.perform(multipart("/__app/backups/acme/restore").file(file).session(admin) + .with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "acme")); + + String page = mvc.perform(get("/__app/backups").session(admin)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("Review how site acme is reached"), "the review card is shown"); + assertTrue(page.contains(">acme.test<"), "the hosts as restored from the backup, not acme.live"); + assertTrue(page.contains(">https://acme.test<"), "the restored base URL"); + assertTrue(page.contains("action=\"/__app/sites/acme/hosts\""), "the editor posts to Sites -> Edit hosts"); + assertTrue(page.contains("value=\"acme.test\""), "the editor starts from the hosts as they stand"); + + String plain = mvc.perform(get("/__app/backups").session(admin)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertFalse(plain.contains("Review how site"), "no review card without a restore"); + + mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/__app/sites/acme/hosts") + .session(admin).with(csrf()).param("hosts", "acme.fixed").param("baseUrl", "")) + .andExpect(status().is3xxRedirection()); + assertEquals(List.of("acme.fixed"), sites.find("acme").orElseThrow().hosts(), "corrected from the review"); + } finally { + sites.save(original); + } + } + + /** A site created from a backup without hosts is not the default site: the review says nothing reaches it. */ + @Test + void aSiteCreatedWithoutHostsIsReportedUnreachableNotAsTheDefault() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + backups.backup("acme", baos); + MockHttpSession admin = sessionFor("admin"); + MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray()); + mvc.perform(multipart("/__app/backups/create-site").file(file).session(admin).with(csrf()) + .param("newId", "hostless").param("name", "Hostless").param("hosts", "")) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "hostless")); + String page = mvc.perform(get("/__app/backups").session(admin)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("Review how site hostless is reached")); + assertTrue(page.contains("none: no address reaches this site until you give it a host"), "not the default"); + assertFalse(page.contains("catch-all default site"), "it is not the default site"); + } + /** An archive from a newer Runway: the operator is told to upgrade, and nothing is replaced or created. */ @Test void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception { diff --git a/runway-app/src/test/java/mx/quest/runway/console/TenantBackupsScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/TenantBackupsScreenTest.java index 86001a2..2675294 100644 --- a/runway-app/src/test/java/mx/quest/runway/console/TenantBackupsScreenTest.java +++ b/runway-app/src/test/java/mx/quest/runway/console/TenantBackupsScreenTest.java @@ -284,6 +284,31 @@ class TenantBackupsScreenTest { assertEquals("ORIGINAL_CONTENT", Files.readString(home, StandardCharsets.UTF_8), "the page was restored"); } + /** After a restore the screen shows how the site is reached, read-only: a restore here keeps the hosts. */ + @Test + void aRestoreIsFollowedByTheSitesHostsForReview() throws Exception { + MockHttpSession admin = sessionFor("admin"); + mvc.perform(post("/__admin/backups/create").session(admin).with(csrf())).andExpect(status().is3xxRedirection()); + mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()); // the create's redirect + String name = backups.list("acme").get(0).name(); + mvc.perform(post("/__admin/backups/" + name + "/restore").session(admin).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE)); + + MvcResult shown = mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()).andReturn(); + String page = shown.getResponse().getContentAsString(); + assertTrue(page.contains("id=\"bk-review\""), "the review card is shown"); + assertTrue(page.contains("How the site is reached")); + assertTrue(page.contains("only a platform administrator can change them")); + assertTrue(page.contains(">localhost<"), "the site's host"); + assertTrue(page.contains("not set, so https://localhost (https:// and the first host)"), "the derived base URL"); + assertTrue(!page.contains("/__app/sites/acme/hosts"), "no editor on the site console"); + + String plain = mvc.perform(get("/__admin/backups").session(admin)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertTrue(!plain.contains("id=\"bk-review\""), "no review card without a restore"); + } + /** An archive from a newer Runway is refused on both restore paths, with the upgrade message. */ @Test void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception { diff --git a/runway-app/src/test/java/mx/quest/runway/web/SlowClientConfigTest.java b/runway-app/src/test/java/mx/quest/runway/web/SlowClientConfigTest.java index 0962ef3..2fca77e 100644 --- a/runway-app/src/test/java/mx/quest/runway/web/SlowClientConfigTest.java +++ b/runway-app/src/test/java/mx/quest/runway/web/SlowClientConfigTest.java @@ -26,16 +26,18 @@ import org.springframework.boot.web.server.WebServer; /** * The minimum request data rate, against a real Jetty: a body trickled in is cut with {@code 408} instead of holding a - * request thread, and a server that is slow to start reading is not blamed for it. Guards the behaviour across Jetty - * upgrades, since the rate check is Jetty's. + * request thread, whether the servlet reads the stream, form parameters or multipart parts, and a server that is slow + * to start reading is not blamed for it. The check is {@link RequestBodyRateHandler}'s; Jetty's own is turned off. */ class SlowClientConfigTest { /** The bean, as Spring binds and applies it: the property, the clamp, and every connector of Boot's own Jetty. */ @Test void theBoundPropertyReachesEveryConnectorOfTheServerBootBuilds() throws Exception { - assertThat(rateOnBootsServer("1024")).containsOnly(1024L).isNotEmpty(); - assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off").containsOnly(0L); + assertThat(rateOnBootsServer("1024")).as("Jetty's own check off on every connector; ours in Boot's chain") + .containsOnly(0L, 1024L * 1_000_000).contains(0L, 1024L * 1_000_000); + assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off, and no handler is installed") + .containsOnly(0L).isNotEmpty(); } private java.util.List rateOnBootsServer(String configured) throws Exception { @@ -55,6 +57,13 @@ class SlowClientConfigTest { } } } + // The handler chain, outermost first: a RequestBodyRateHandler is reported as its rate x 1_000_000. + for (org.eclipse.jetty.server.Handler h = ((JettyWebServer) web).getServer().getHandler(); h != null; + h = h instanceof org.eclipse.jetty.server.Handler.Wrapper w ? w.getHandler() : null) { + if (h instanceof RequestBodyRateHandler rate) { + rates.add(rate.bytesPerSecond() * 1_000_000); + } + } return rates; } finally { web.stop(); @@ -70,27 +79,66 @@ class SlowClientConfigTest { } } + /** How the servlet reads the body: the input stream (Jetty's own check), form parameters, or multipart parts. */ + private enum Body { STREAM, FORM, MULTIPART, SWALLOWED, ESCAPED } + /** A server whose servlet reads the whole body after {@code pauseMillis}, with the rate applied by the config. */ private int start(long bytesPerSecond, long pauseMillis) throws Exception { + return start(bytesPerSecond, pauseMillis, Body.STREAM); + } + + private int start(long bytesPerSecond, long pauseMillis, Body body) throws Exception { + return start(bytesPerSecond, pauseMillis, body, RequestBodyRateHandler.CREDIT_SECONDS); + } + + private int start(long bytesPerSecond, long pauseMillis, Body body, long creditSeconds) throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory()); connector.setPort(0); connector.setIdleTimeout(30_000); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(); - context.addServlet(new ServletHolder(new HttpServlet() { + ServletHolder holder = new ServletHolder(new HttpServlet() { @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException, jakarta.servlet.ServletException { try { Thread.sleep(pauseMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - response.getWriter().write("read " + request.getInputStream().readAllBytes().length); + String read = switch (body) { + case STREAM -> "read " + request.getInputStream().readAllBytes().length; + case FORM -> "a=" + request.getParameter("a").length(); + case MULTIPART -> "parts " + request.getParts().size(); + case SWALLOWED -> { // the read fails and the code carries on as if nothing happened + try { + request.getInputStream().readAllBytes(); + } catch (IOException ignored) { + // swallowed on purpose + } + yield "fine"; + } + case ESCAPED -> { // the failure escapes, as from a filter that reads the stream itself + request.getInputStream().readAllBytes(); + yield "unreachable"; + } + }; + response.getWriter().write(read); } - }), "/*"); + }); + if (body == Body.MULTIPART) { + holder.getRegistration().setMultipartConfig(new jakarta.servlet.MultipartConfigElement("")); + } + context.addServlet(holder, "/*"); server.setHandler(context); assertThat(SlowClientConfig.apply(server, bytesPerSecond)).isEqualTo(1); + if (creditSeconds != RequestBodyRateHandler.CREDIT_SECONDS + && server.getHandler() instanceof RequestBodyRateHandler installed) { + RequestBodyRateHandler shortCredit = new RequestBodyRateHandler(bytesPerSecond, creditSeconds); + shortCredit.setHandler(installed.getHandler()); + server.setHandler(shortCredit); + } server.start(); return connector.getLocalPort(); } @@ -136,6 +184,133 @@ class SlowClientConfigTest { } } + /** Sends {@code head}, then {@code drip} one byte a second until the server answers or 20 bytes are sent. */ + private static String drip(int port, String head) throws Exception { + long started = System.nanoTime(); + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(head.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + try { + for (int i = 0; i < 20; i++) { + Thread.sleep(1000); + out.write('a'); + out.flush(); + } + } catch (IOException closedByServer) { + // expected: answered and closed while the client was still trickling + } + String status = statusLine(socket); + assertThat(Duration.ofNanos(System.nanoTime() - started)).as("cut long before the idle timeout") + .isLessThan(Duration.ofSeconds(15)); + return status; + } + } + + @Test + void aTrickledFormIsCutToo() throws Exception { + // 1.1.0: form parameters were read past Jetty's own check, and this request was held for the idle timeout. + int port = start(1024, 0, Body.FORM); + assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: 1000\r\nConnection: close\r\n\r\na=")).isEqualTo("HTTP/1.1 408 Request Timeout"); + } + + @Test + void aTrickledMultipartBodyIsCutToo() throws Exception { + int port = start(1024, 0, Body.MULTIPART); + assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: multipart/form-data; boundary=XyZ\r\n" + + "Content-Length: 1000\r\nConnection: close\r\n\r\n--XyZ\r\n" + + "Content-Disposition: form-data; name=\"a\"\r\n\r\n")).isEqualTo("HTTP/1.1 408 Request Timeout"); + } + + @Test + void aRefusedBodyIsAnswered408HoweverTheCodeHandledTheFailedRead() throws Exception { + // Measured on 1.1.1-SNAPSHOT before this guard: a route reading the stream itself answered an empty 200. + for (Body body : new Body[] {Body.SWALLOWED, Body.ESCAPED}) { + int port = start(4096, 0, body); + assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/octet-stream\r\n" + + "Content-Length: 1000\r\nConnection: close\r\n\r\n")).as(body.name()) + .isEqualTo("HTTP/1.1 408 Request Timeout"); + server.stop(); + server = null; + } + } + + @Test + void aBodySentFastAtFirstCannotBuyALongDripLater() throws Exception { + // 32 KiB at line speed, then a byte a second: averaged over the whole body (1.1.0, and this fix's first form) + // that bought 32 s of dripping at 1 KiB/s, and with 16 MiB over an hour. The credit is capped (2 s here). + int port = start(1024, 0, Body.FORM, 2); + long started = System.nanoTime(); + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: 65536\r\nConnection: close\r\n\r\na=" + "b".repeat(32 * 1024)) + .getBytes(StandardCharsets.US_ASCII)); + out.flush(); + try { + for (int i = 0; i < 20; i++) { + Thread.sleep(1000); + out.write('c'); + out.flush(); + } + } catch (IOException closedByServer) { + // expected + } + assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 408 Request Timeout"); + } + assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(10)); + } + + @Test + void aSmallFormWhoseOnlyPacketArrivesLateIsAccepted() throws Exception { + // A network stall before the body: the body then arrives whole, so no thread is held by a slow client. + int port = start(1024, 0, Body.FORM); + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: 12\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); + out.flush(); + Thread.sleep(2500); + out.write("a=1234567890".getBytes(StandardCharsets.US_ASCII)); + out.flush(); + assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK"); + } + } + + @Test + void aLargeFormAtAGoodRateIsAccepted() throws Exception { + int port = start(4096, 0, Body.FORM); + int size = 64 * 1024; + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: " + (size + 2) + "\r\nConnection: close\r\n\r\na=") + .getBytes(StandardCharsets.US_ASCII)); + for (int i = 0; i < size / 4096; i++) { // 4 KiB every 100 ms: 40 KiB/s, ten times the minimum + out.write("b".repeat(4096).getBytes(StandardCharsets.US_ASCII)); + out.flush(); + Thread.sleep(100); + } + socket.setSoTimeout(10_000); + String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII); + assertThat(response).startsWith("HTTP/1.1 200 OK").endsWith("a=" + size); + } + } + + @Test + void aFormServerSlowToReadIsNotBlamed() throws Exception { + int port = start(1024, 3000, Body.FORM); + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: 102\r\nConnection: close\r\n\r\na=" + "c".repeat(100)) + .getBytes(StandardCharsets.US_ASCII)); + out.flush(); + assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK"); + } + } + @Test void theDefaultIsFourKilobytesPerSecond() { assertThat(new SlowClientConfig.HttpLimitProperties().getMinRequestDataRate()).isEqualTo(4096); diff --git a/runway-app/src/test/java/mx/quest/runway/web/SlowRequestBodyEndToEndTest.java b/runway-app/src/test/java/mx/quest/runway/web/SlowRequestBodyEndToEndTest.java new file mode 100644 index 0000000..2f660ac --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/web/SlowRequestBodyEndToEndTest.java @@ -0,0 +1,126 @@ +package mx.quest.runway.web; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * The slow-body limit on the running application, where it was missing in 1.1.0: the login forms of both realms and a + * multipart post, trickled in, are answered {@code 408} within seconds instead of holding a request thread until the + * idle timeout. Through the whole chain (Spring Security reads the login form), which a bare Jetty cannot stand in + * for: there, a refused read that the chain treats as a client gone away was answered an empty {@code 200}. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class SlowRequestBodyEndToEndTest { + + private static final String HOST = "localhost"; + /** The console is never served on a site's host; this one is no site's. */ + private static final String CONSOLE_HOST = "127.0.0.1"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-slow-body"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + YamlStore yaml = new YamlStore(); + new SiteStore(StorageLayout.from(props), yaml).save(new Site("acme", "Acme", List.of(HOST), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE, false, null)); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode("Slow-Body-7x"); + new UserStore(yaml).save(external.resolve("app-users.yml"), + new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + registry.add("runway.health.content-check", () -> "false"); + registry.add("runway.http.min-request-data-rate", () -> "1024"); + } + + @LocalServerPort + private int port; + + /** Sends the head of a 1000-byte body, then one byte a second; returns the status line and how long it took. */ + private String drip(String path, String contentType, String bodyStart) throws Exception { + String host = path.startsWith("/app/") ? CONSOLE_HOST : HOST; + long started = System.nanoTime(); + try (Socket socket = new Socket("127.0.0.1", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST " + path + " HTTP/1.1\r\nHost: " + host + "\r\nContent-Type: " + contentType + + "\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n" + bodyStart) + .getBytes(StandardCharsets.US_ASCII)); + out.flush(); + try { + for (int i = 0; i < 20; i++) { + Thread.sleep(1000); + out.write('a'); + out.flush(); + } + } catch (IOException closedByServer) { + // expected: answered and closed while the client was still trickling + } + socket.setSoTimeout(40_000); + String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII); + assertThat(Duration.ofNanos(System.nanoTime() - started)).as(path + ": cut long before the idle timeout") + .isLessThan(Duration.ofSeconds(15)); + return response.isEmpty() ? "" : response.substring(0, response.indexOf("\r\n")); + } + } + + @Test + void aTrickledSiteLoginIsAnswered408() throws Exception { + assertThat(drip("/login", "application/x-www-form-urlencoded", "username=")) + .isEqualTo("HTTP/1.1 408 Request Timeout"); + } + + @Test + void aTrickledConsoleLoginIsAnswered408() throws Exception { + assertThat(drip("/app/login", "application/x-www-form-urlencoded", "username=")) + .isEqualTo("HTTP/1.1 408 Request Timeout"); + } + + @Test + void aTrickledMultipartPostIsAnswered408() throws Exception { + assertThat(drip("/app/login", "multipart/form-data; boundary=XyZ", + "--XyZ\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n")) + .isEqualTo("HTTP/1.1 408 Request Timeout"); + } + + @Test + void aLoginSentAtOnceIsNotTouched() throws Exception { + try (Socket socket = new Socket("127.0.0.1", port)) { + String body = "username=root&password=wrong"; + socket.getOutputStream().write(("POST /app/login HTTP/1.1\r\nHost: " + CONSOLE_HOST + + "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: " + body.length() + + "\r\nConnection: close\r\n\r\n" + body).getBytes(StandardCharsets.US_ASCII)); + socket.setSoTimeout(10_000); + String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII); + assertThat(response).as("refused for its missing CSRF token, as before: not a slow body") + .startsWith("HTTP/1.1 403"); + } + } +} diff --git a/runway-dist/pom.xml b/runway-dist/pom.xml index f602704..83b2d63 100644 --- a/runway-dist/pom.xml +++ b/runway-dist/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.0 + 1.1.1 runway-dist diff --git a/runway-plugin-protection/plugin.yml b/runway-plugin-protection/plugin.yml index e7863b8..724ea55 100644 --- a/runway-plugin-protection/plugin.yml +++ b/runway-plugin-protection/plugin.yml @@ -6,7 +6,7 @@ name: Essential Protection # The essential plugin ships with the kernel, in the same release, on the kernel's version line (docs/SPI-STABILITY.md, # "The essential-plugin exception"): its version is the kernel's plain MAJOR.MINOR.PATCH. Seeding compares SHA-256 # hashes, not versions, and no plugin may `requires:` an essential plugin, so nothing keys on it. -version: 1.1.0 +version: 1.1.1 essential: true # The mandatory floor (SPI 1.0.0): every plugin with a mainClass declares one; the kernel's own plugin declares the # SPI major's floor (>=1.0.0, met by every 1.x kernel; raised only when it uses a newer SPI member), so the floor rule diff --git a/runway-plugin-protection/pom.xml b/runway-plugin-protection/pom.xml index d27cec7..ef24d76 100644 --- a/runway-plugin-protection/pom.xml +++ b/runway-plugin-protection/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.0 + 1.1.1 runway-plugin-protection diff --git a/runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionDescriptorK4Test.java b/runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionDescriptorK4Test.java index b778ace..65e6a10 100644 --- a/runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionDescriptorK4Test.java +++ b/runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionDescriptorK4Test.java @@ -35,7 +35,7 @@ class ProtectionDescriptorK4Test { PluginDescriptor descriptor = shipped(); assertEquals("protection", descriptor.id()); assertTrue(descriptor.isEssential()); - assertEquals("1.1.0", descriptor.version(), "versioned on the kernel's line"); + assertEquals("1.1.1", descriptor.version(), "versioned on the kernel's line"); assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor()); assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(), "the floor names the kernel's own SPI major line"); diff --git a/runway-spi-testkit/pom.xml b/runway-spi-testkit/pom.xml index b1003fb..f02a30c 100644 --- a/runway-spi-testkit/pom.xml +++ b/runway-spi-testkit/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.0 + 1.1.1 runway-spi-testkit diff --git a/runway-spi/pom.xml b/runway-spi/pom.xml index 6216d9f..307f3ef 100644 --- a/runway-spi/pom.xml +++ b/runway-spi/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.0 + 1.1.1 runway-spi diff --git a/scripts/dev/gen-kernel-settings.py b/scripts/dev/gen-kernel-settings.py index a511533..bfdc369 100644 --- a/scripts/dev/gen-kernel-settings.py +++ b/scripts/dev/gen-kernel-settings.py @@ -38,7 +38,7 @@ S = [ ("runway.csp.form-action","string","'self'",None,"server.csp",True,None,"form-action","Where forms may submit.","form-action","A dónde pueden enviarse los formularios."), ("runway.csp.frame-ancestors","string","'self'",None,"server.csp",True,None,"frame-ancestors","Which sites may show these pages in a frame. 'none' forbids all.","frame-ancestors","Qué sitios pueden mostrar estas páginas en un marco. 'none' lo prohíbe."), ("runway.endpoints.max-form-bytes","int","262144","1024..104857600","server.limits",False,None,"Largest request before sign-in (bytes)","The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB).","Solicitud máxima sin sesión (bytes)","Lo máximo que un visitante sin sesión puede enviar en una solicitud, en cualquier ruta. Por omisión 262144 (256 KiB)."), - ("runway.http.min-request-data-rate","int","4096","0..1048576","server.limits",True,None,"Slowest request body (bytes per second)","A request body arriving more slowly is answered 408 Request Timeout, so a client sending a byte now and then cannot hold a request thread. Measured on what has arrived since the body's first byte. Default 4096; 0 turns the check off.","Cuerpo de solicitud más lento (bytes por segundo)","Un cuerpo de solicitud que llega más despacio recibe 408 Request Timeout, así que un cliente que envía un byte de vez en cuando no puede ocupar un hilo de solicitud. Se mide sobre lo recibido desde el primer byte del cuerpo. Por omisión 4096; 0 desactiva la comprobación."), + ("runway.http.min-request-data-rate","int","4096","0..1048576","server.limits",True,None,"Slowest request body (bytes per second)","A request body arriving more slowly is answered 408 Request Timeout: login and other forms, uploads and raw bodies alike, so a client sending a byte now and then cannot keep a request thread. Only time spent waiting for the client counts, and a body that has arrived complete is never refused. Sending part of a body fast earns at most 30 seconds of waiting. Default 4096; 0 turns the check off.","Cuerpo de solicitud más lento (bytes por segundo)","Un cuerpo de solicitud que llega más despacio recibe 408 Request Timeout: formularios (también el de inicio de sesión), subidas y cuerpos sin formato por igual, así que un cliente que envía un byte de vez en cuando no puede retener un hilo de solicitud. Solo cuenta el tiempo de espera por el cliente, y un cuerpo que ya llegó completo nunca se rechaza. Enviar rápido parte del cuerpo da como máximo 30 segundos de espera. Por omisión 4096; 0 desactiva la comprobación."), ("runway.endpoints.max-body-bytes","int","10485760","1024..1073741824","server.limits",False,None,"Largest request to a plugin (bytes)","The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB).","Solicitud máxima a un complemento (bytes)","Lo máximo que un usuario con sesión puede enviar a una ruta de un complemento. Por omisión 10485760 (10 MiB)."), ("spring.servlet.multipart.max-file-size","string","256MB",None,"server.limits",False,None,"Largest uploaded file","For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB.","Archivo subido máximo","Para subidas como una copia a restaurar. Un tamaño como 256MB o 1GB. Por omisión 256MB."), ("spring.servlet.multipart.max-request-size","string","256MB",None,"server.limits",False,None,"Largest upload request","All the files of one upload together. A size like 256MB. Default 256MB.","Solicitud de subida máxima","Todos los archivos de una subida juntos. Un tamaño como 256MB. Por omisión 256MB."),