Runway 1.1.2

This commit is contained in:
Runway committed 2026-10-29 12:42:22 -06:00
1 parent 67d61f339c
commit f1a905df9f
29 files changed
+548 -76

No files matched your search

+76
View File
@@ -2,6 +2,82 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [1.1.2] — 2026-10-29
_A patch release: the access log now records every public request that gets past the protection edge, including the
ones a filter answers on its own: login attempts, refused form posts, a suspended or maintenance site, a slow body's
`408`, an oversized form's `413`, plugin routes such as `robots.txt` and the sitemap._
### Upgrading — read this first
**From `1.1.1`: a kernel upgrade, no flag.** From `1.1.0`, `1.0.1` or `1.0.0`, read `1.1.1`'s and `1.1.0`'s
*Upgrading* first, then install this release directly. Paths are the installer defaults (`/opt/runway`,
`/opt/runway-data`).
**Your access log will carry more lines.** Nothing is removed and the line format is unchanged, but requests that
used to leave no line now leave one: in the `runway.access` stream and in each site's own access log (its **Logs**
screen). Expect, among others, `POST /login -> 302` for a login attempt, `POST /login -> 403` for a form post refused
for its missing token, `-> 503` while a site is suspended, in maintenance or over its quota, `-> 408` for a refused
slow body, `-> 413` for a `PUT`/`PATCH`/`DELETE` form over `runway.endpoints.max-form-bytes`, and `GET /robots.txt`,
`GET /sitemap.xml` and other plugin routes. A tool that reads `runway.access` (a
log shipper, an alert on `4xx`/`5xx` counts, a ban list fed by failed logins) sees these from now on; check any
threshold that assumed they were absent; under a flood of login attempts that gets past the protection edge, the
`runway.access` stream now grows by one line per attempt, which a journal rate limit may also count. Each site's
**Insights** does not count the refusals (it counts only `GET` page views and `404`s), but it now sees plugin routes:
a page a plugin serves counts as a page view, and a plugin route answering `404` (a missing blog post, an icon the
site has not set) appears among the top 404s. Requests the protection edge turns away (`403`/`429`) still go to
`runway.protect` only, throttled, as before.
**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.2.bin
sudo ./runway-1.1.2.bin -y
```
The essential plugin moves with the kernel to `1.1.2` (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.2/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.1.2`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.2`.
- A login form posted without its token appears in the access log:
`curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: <a site host>' -d 'username=x&password=y' http://127.0.0.1:8080/login`
answers `403`, and `journalctl -u runway --since '-5min' | grep 'runway.access' | grep -c 'POST /login -> 403'` is
at least `1`.
**4. Rollback**, if needed: `sudo bash runway-1.1.1.bin -y` puts 1.1.1 back, its protection files included; those
requests then leave no access-log line again. Nothing this release saves is read differently by 1.1.1.
### Fixed
- **The access log records every public request past the protection edge.** It used to be written by the innermost
filter, so any request answered by a filter further out left no line in either the platform log or the site's
own: every attempt at a site's login page, successful or not (Spring Security answers it itself), a form post
refused for its missing token, the `503` of a suspended, maintenance or over-quota site, a request body refused for
arriving too slowly, a `PUT`/`PATCH`/`DELETE` form refused unread for its size, and every plugin route
(`robots.txt`, the sitemap, `llms.txt`, a plugin's form). A password-guessing run against a site's login was
invisible in its access log. The log is now written just inside the protection edge, from where it sees how each
request was answered. A plugin page served by a route now also counts in **Insights** like any other page.
- **Audit lines are kept ahead of access lines when a site's log queue is full.** Both share one queue
(`runway.logs.queue-capacity`); an eighth of it is now held for audit lines, so a flood that fills it drops access
lines first and keeps the `login.failure` records of the very attack that filled it.
### Documentation
- OPERATIONS §3 (what the access log records, and since when), PLUGIN-DEVELOPMENT (which plugin filters' answers are
logged), SITE-MANAGER-GUIDE §3 and §10 (login attempts and refusals on **Logs**; not counted by **Insights**).
## [1.1.1] — 2026-10-29 ## [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 _A patch release: the slow-request-body limit 1.1.0 introduced now covers form posts and multipart uploads too, and
+2 -1
View File
@@ -2775,7 +2775,8 @@ Each site keeps its own access log (its public traffic) and audit log (its manag
- `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and - `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and
the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for: the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for:
the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is
logged at most once a minute. Raise it if that count grows; each queued line takes a little memory. logged at most once a minute. An eighth of the queue is held for audit lines (sign-ins, changes), so a flood of
public requests drops access lines first. Raise it if that count grows; each queued line takes a little memory.
### Bandwidth metering (`runway.bandwidth.*`) ### Bandwidth metering (`runway.bandwidth.*`)
+11 -2
View File
@@ -223,7 +223,9 @@ is written **only in detached launcher mode** — the supervisor appends the JVM
usually empty; do not go looking for application logs there when running as a service. usually empty; do not go looking for application logs there when running as a service.
**The public access log.** One line is emitted per **public** request under the logger **The public access log.** One line is emitted per **public** request under the logger
`runway.access`, from the innermost filter (so the status is final): `runway.access`, written once every filter and handler has finished with it, so with the status it was answered
with (the one exception: an error escaping a plugin's own controller is logged with the status set before it,
while the client receives `500`):
``` ```
203.0.113.7 GET /about -> 200 (12ms) 203.0.113.7 GET /about -> 200 (12ms)
@@ -237,6 +239,13 @@ fetch will **not** appear here; that is by design (this is a traffic log, not an
client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a
raw spoofable header. raw spoofable header.
It records **every** public request that gets past the protection edge (§3.1), whoever answers it: a page, a
plugin's route (`robots.txt`, the sitemap, a form), the sign-in form (every login attempt, successful or not, and
a form post refused for its missing token, `403`), an oversized form refused unread (`413`), a suspended, maintenance or over-quota site (`503`), and a
request body refused for arriving too slowly (`408`). Before 1.1.2 every one of these except the page was missing,
because the log was written by the innermost filter and each of them is answered by a filter outside it. Only the
edge's own `403`/`429` stay out: those go to `runway.protect` (§3.1).
**What to grep for** (systemd, hence `journalctl`): **What to grep for** (systemd, hence `journalctl`):
```bash ```bash
@@ -302,7 +311,7 @@ rejections, §3.1); everything else logs under its package, `mx.quest.runway.*`.
### 3.1 Seeing what the edge rejected ### 3.1 Seeing what the edge rejected
A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot — A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot —
and the chain is never called. The access log lives at the innermost slot. So a `403`/`429` from the edge and the chain is never called. The access log sits just inside that slot, so a `403`/`429` from the edge
**appears in no other log**, and without a log of its own a site manager would have no way to tell that a **appears in no other log**, and without a log of its own a site manager would have no way to tell that a
crawler was being throttled. crawler was being throttled.
+3 -1
View File
@@ -738,7 +738,9 @@ You declare a **`FilterBand` + a small offset** — never a raw order. The kerne
escape its band to preempt the protection floor or run before security. The bands (outermost → escape its band to preempt the protection floor or run before security. The bands (outermost →
innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting), innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting),
`TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of `TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of
security; the default). **`SECURITY` is not contributable** — it belongs to the kernel's realm security; the default). The kernel's access log sits between `EDGE_INGRESS` and the rest: whatever an
`EDGE_EGRESS`, `TENANT` or `APPLICATION` filter answers is logged with its status, while a request an
`EDGE_INGRESS` filter turns away is not (log it yourself, throttled, if you need to). **`SECURITY` is not contributable** — it belongs to the kernel's realm
security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either. security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either.
**Verify:** the boot log prints one line per plugin filter — **Verify:** the boot log prints one line per plugin filter —
+4 -3
View File
@@ -230,7 +230,8 @@ name or the default language. While no field is set and no manifest icon (192, 5
`/manifest.webmanifest` answers 404 and pages do not link to it. `/manifest.webmanifest` answers 404 and pages do not link to it.
The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent
lines) and its **audit journal**: who did what on your site, and when. The journal records sign-ins lines; every sign-in attempt on your site's login page is there too, as a `POST /login`, and so is a request your
site refused, such as a `503` while it is in maintenance) and its **audit journal**: who did what on your site, and when. The journal records sign-ins
(`login.success`, `login.failure`) and sign-outs (`logout`), each with the address it came from (`ip=…`, in full: (`login.success`, `login.failure`) and sign-outs (`logout`), each with the address it came from (`ip=…`, in full:
the anonymizing setting below applies to the access log only); password recovery through an emailed link the anonymizing setting below applies to the access log only); password recovery through an emailed link
(`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`, (`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`,
@@ -1184,10 +1185,10 @@ two lists, for the **last 7 or 30 days** (never longer than your log retention
with a corrected link, the missing page or file, or a redirect from the old address. with a corrected link, the missing page or file, or a redirect from the old address.
- **Most-visited pages** — your pages by how often they were successfully viewed, with when last. - **Most-visited pages** — your pages by how often they were successfully viewed, with when last.
**What it counts.** Only `GET` requests (a form post or a crawler's `HEAD` is not a visit). A **page view** is a **What it counts.** Only `GET` requests (a form post, a sign-in attempt or a crawler's `HEAD` is not a visit). A **page view** is a
successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html` successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html`
— so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it — so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it
already has (a `304`) is not a new view. A **404** counts for any address, images included, because a missing already has (a `304`) is not a new view, and neither is a refusal (a `403`, or a `503` during maintenance). A **404** counts for any address, images included, because a missing
image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as
`/search`), and very long ones are shortened on screen (hover to see the whole stored address). `/search`), and very long ones are shortened on screen (hover to see the whole stored address).
+2 -2
View File
@@ -13,7 +13,7 @@
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Runway</name> <name>Runway</name>
@@ -42,7 +42,7 @@
extended timestamp through the build JVM's default time zone, so the same source built in CST and 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). 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. --> .mvn/jvm.config pins -Duser.timezone=UTC for the Maven JVM, which removes the host's zone. -->
<project.build.outputTimestamp>2026-10-29T17:30:00Z</project.build.outputTimestamp> <project.build.outputTimestamp>2026-10-29T18:30:00Z</project.build.outputTimestamp>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- runway-spi and runway-spi-testkit attach a sources jar (release assets for third-party plugin authors, <!-- runway-spi and runway-spi-testkit attach a sources jar (release assets for third-party plugin authors,
docs/PLUGIN-DEVELOPMENT.md §3). Boot's parent manages 3.3.1; 3.4.0 is the version the build hosts' docs/PLUGIN-DEVELOPMENT.md §3). Boot's parent manages 3.3.1; 3.4.0 is the version the build hosts'
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
</parent> </parent>
<artifactId>runway-app</artifactId> <artifactId>runway-app</artifactId>
@@ -6,14 +6,16 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import mx.quest.runway.web.FilterOrder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.servlet.filter.OrderedFormContentFilter; import org.springframework.boot.servlet.filter.OrderedFormContentFilter;
/** /**
* Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter outermost (order * Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter early (order
* {@code -9900}) so a {@code PUT}/{@code PATCH}/{@code DELETE} form body becomes request parameters for * {@code -9900}; Runway places it at {@link FilterOrder#CORE_FORM_CONTENT}, inside the access log and the site
* binding, so its {@code 413} is logged for the site) so a {@code PUT}/{@code PATCH}/{@code DELETE} form body becomes request parameters for
* {@code @RequestParam}; it does that by <b>reading the body</b>, so a plugin route used to receive an empty * {@code @RequestParam}; it does that by <b>reading the body</b>, so a plugin route used to receive an empty
* {@code RouteRequest.form()} and {@code body()} for those methods — and a {@code _csrf} field in such a body was not * {@code RouteRequest.form()} and {@code body()} for those methods — and a {@code _csrf} field in such a body was not
* found either ({@code RouteBodyMethodsE2ETest}). A request whose method and path match a registered route * found either ({@code RouteBodyMethodsE2ETest}). A request whose method and path match a registered route
@@ -51,6 +53,7 @@ public class RouteAwareFormContentFilter extends OrderedFormContentFilter {
public RouteAwareFormContentFilter(ObjectProvider<EndpointContributorRegistry> registry, long cap) { public RouteAwareFormContentFilter(ObjectProvider<EndpointContributorRegistry> registry, long cap) {
this.registry = registry; this.registry = registry;
this.cap = Math.max(0, cap); this.cap = Math.max(0, cap);
setOrder(FilterOrder.CORE_FORM_CONTENT);
} }
@Override @Override
@@ -1,6 +1,5 @@
package mx.quest.runway.log; package mx.quest.runway.log;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.FilterOrder; import mx.quest.runway.web.FilterOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
@@ -8,19 +7,18 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** /**
* Registers {@link AccessLogFilter} as the innermost filter ({@link FilterOrder#CORE_ACCESS_LOG}), so its * Registers {@link AccessLogFilter} at {@link FilterOrder#CORE_ACCESS_LOG}, just inside the abuse floor, so it logs
* post-phase observes the final response status of every public request, and enables {@link LogProperties}. * every public request the floor lets through with its final status, and enables {@link LogProperties}.
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LogProperties.class) @EnableConfigurationProperties(LogProperties.class)
public class AccessLogConfig { public class AccessLogConfig {
@Bean @Bean
public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteResolver siteResolver, public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteLogService siteLog,
SiteLogService siteLog,
LogProperties properties) { LogProperties properties) {
FilterRegistrationBean<AccessLogFilter> registration = new FilterRegistrationBean<>( FilterRegistrationBean<AccessLogFilter> registration = new FilterRegistrationBean<>(
new AccessLogFilter(siteResolver, siteLog, properties.isAccessLogUserAgent())); new AccessLogFilter(siteLog, properties.isAccessLogUserAgent()));
registration.setOrder(FilterOrder.CORE_ACCESS_LOG); registration.setOrder(FilterOrder.CORE_ACCESS_LOG);
registration.addUrlPatterns("/*"); registration.addUrlPatterns("/*");
registration.setName("accessLogFilter"); registration.setName("accessLogFilter");
@@ -5,8 +5,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import mx.quest.runway.site.Site; import mx.quest.runway.site.SiteContextFilter;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.ClientIp; import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.LogSafe; import mx.quest.runway.web.LogSafe;
import mx.quest.runway.web.RequestPaths; import mx.quest.runway.web.RequestPaths;
@@ -15,9 +14,16 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
/** /**
* The innermost filter ({@code FilterOrder.CORE_ACCESS_LOG}): it logs one event per <b>public</b> request from * The access log: one event per <b>public</b> request, written from its {@code post} phase, once every inner filter
* its {@code post} phase, so it observes the <b>final</b> status set by every inner filter and the handler. * and the handler have finished, so the status it records is the one the request was answered with. (The exception:
* Being innermost is the whole point — an outer position would log a not-yet-decided status. * an exception escaping the chain, which only a plugin's own MVC controller can let through, is logged with the
* status set before it, while the container answers {@code 500}.) It sits at {@code FilterOrder.CORE_ACCESS_LOG}, just inside the abuse floor and outside every
* other filter, so it sees every request the floor lets through however it is answered: by a page, an endpoint
* route, Spring Security (a login attempt, a CSRF {@code 403}), a tenant gate (a suspended or over-quota site's
* {@code 503}), a refused slow body ({@code 408}) or an oversized form refused unread ({@code 413}). A filter that answers without calling the chain is invisible
* to every filter inside it, which is why this one is not innermost: there, until 1.1.2, a password-guessing run
* against a site's login left no line at all. Rejections by the floor itself are reported, throttled, by
* {@code EdgeRejectionRecorder} instead.
* *
* <p>It is a <b>public-traffic</b> log, not an audit trail: it skips the internal surfaces (anything under * <p>It is a <b>public-traffic</b> log, not an audit trail: it skips the internal surfaces (anything under
* {@code /__…} — the app/admin/preview/assets/CSP-report consoles — plus {@code /app/…} and {@code /actuator}), * {@code /__…} — the app/admin/preview/assets/CSP-report consoles — plus {@code /app/…} and {@code /actuator}),
@@ -25,29 +31,24 @@ import org.springframework.web.filter.OncePerRequestFilter;
* {@link ClientIp#of} (never a raw forwarded header). * {@link ClientIp#of} (never a raw forwarded header).
* *
* <p>It emits to two sinks: the operator's {@code runway.access} SLF4J logger (the whole-platform stream), and — * <p>It emits to two sinks: the operator's {@code runway.access} SLF4J logger (the whole-platform stream), and —
* when a site is bound (a public tenant request) — that site's own {@link SiteLogService#access per-site access * when a site answered (a public tenant request) — that site's own {@link SiteLogService#access per-site access
* log}. This filter runs <em>inside</em> the site-context filter, so the tenant binding is still live in the * log}. The site is read from the {@link SiteContextFilter#SITE_ID_ATTRIBUTE request attribute} the site-context
* post phase. * filter leaves, not from {@code SiteResolver.current()}: that filter is inner of this one and has cleared its
* thread binding by the time this {@code post} runs. A request refused before the site is resolved has no site and
* goes to the platform log only.
*/ */
public class AccessLogFilter extends OncePerRequestFilter { public class AccessLogFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger("runway.access"); private static final Logger log = LoggerFactory.getLogger("runway.access");
private final SiteResolver siteResolver;
private final SiteLogService siteLog; private final SiteLogService siteLog;
private final boolean logUserAgent; private final boolean logUserAgent;
public AccessLogFilter(SiteResolver siteResolver, SiteLogService siteLog, boolean logUserAgent) { public AccessLogFilter(SiteLogService siteLog, boolean logUserAgent) {
this.siteResolver = siteResolver;
this.siteLog = siteLog; this.siteLog = siteLog;
this.logUserAgent = logUserAgent; this.logUserAgent = logUserAgent;
} }
/** Pre-{@code logUserAgent} form, kept so existing call sites (and tests) compile unchanged: agent off. */
public AccessLogFilter(SiteResolver siteResolver, SiteLogService siteLog) {
this(siteResolver, siteLog, false);
}
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException { throws ServletException, IOException {
@@ -69,9 +70,8 @@ public class AccessLogFilter extends OncePerRequestFilter {
log.info("{} {} {} -> {} ({}ms)", ip, request.getMethod(), log.info("{} {} {} -> {} ({}ms)", ip, request.getMethod(),
request.getRequestURI(), response.getStatus(), millis); request.getRequestURI(), response.getStatus(), millis);
} }
Site site = siteResolver.current().orElse(null); if (request.getAttribute(SiteContextFilter.SITE_ID_ATTRIBUTE) instanceof String siteId) {
if (site != null) { siteLog.access(siteId, ip, request.getMethod(), request.getRequestURI(), response.getStatus());
siteLog.access(site.id(), ip, request.getMethod(), request.getRequestURI(), response.getStatus());
} }
} }
} }
@@ -62,6 +62,14 @@ public class SiteLogService {
private final SiteLogConfigService configs; private final SiteLogConfigService configs;
private final LogProperties props; private final LogProperties props;
private final BlockingQueue<LogEvent> queue; private final BlockingQueue<LogEvent> queue;
/**
* Queue slots only audit events may take. Access and audit lines share the queue, and a flood that gets past the
* protection edge (a credential-stuffing run, two events per attempt) would otherwise drop audit lines, the
* {@code login.failure} records that are the evidence of that very attack, as often as access lines. With an
* eighth of the queue held back, access lines are dropped first.
*/
private final int auditReserve;
static final int AUDIT_RESERVE_DIVISOR = 8;
private final AtomicLong dropped = new AtomicLong(); private final AtomicLong dropped = new AtomicLong();
private static final long DROP_WARN_INTERVAL_MS = 60_000L; private static final long DROP_WARN_INTERVAL_MS = 60_000L;
private volatile long lastDropWarnAt; private volatile long lastDropWarnAt;
@@ -73,7 +81,9 @@ public class SiteLogService {
this.layout = layout; this.layout = layout;
this.configs = configs; this.configs = configs;
this.props = props; this.props = props;
this.queue = new ArrayBlockingQueue<>(Math.max(16, props.getQueueCapacity())); int capacity = Math.max(16, props.getQueueCapacity());
this.queue = new ArrayBlockingQueue<>(capacity);
this.auditReserve = capacity / AUDIT_RESERVE_DIVISOR;
} }
@PostConstruct @PostConstruct
@@ -113,6 +123,16 @@ public class SiteLogService {
List.of(clean(actor), clean(action), clean(detail)))); List.of(clean(actor), clean(action), clean(detail))));
} }
/** Accepts events without starting the writer, so a test can fill the queue. */
void acceptWithoutWriting() {
running = true;
}
/** Events waiting to be written (tests). */
int queued() {
return queue.size();
}
/** The number of events dropped because the queue was full (best-effort observability). */ /** The number of events dropped because the queue was full (best-effort observability). */
public long droppedCount() { public long droppedCount() {
return dropped.get(); return dropped.get();
@@ -219,7 +239,9 @@ public class SiteLogService {
if (!running) { if (!running) {
return; return;
} }
if (!queue.offer(event)) { boolean accepted = event.kind() == LogKind.ACCESS && queue.remainingCapacity() <= auditReserve
? false : queue.offer(event);
if (!accepted) {
long total = dropped.incrementAndGet(); long total = dropped.incrementAndGet();
// A saturated queue silently losing events (audit lines included) is exactly what an operator needs // A saturated queue silently losing events (audit lines included) is exactly what an operator needs
// told — but the drop path must stay non-blocking and un-spammy, so warn at most once a minute. // told — but the drop path must stay non-blocking and un-spammy, so warn at most once a minute.
@@ -15,9 +15,9 @@ import org.slf4j.LoggerFactory;
* <h2>The blind spot this closes</h2> * <h2>The blind spot this closes</h2>
* {@link EdgeRejectFilter} sits at {@code FilterOrder.CORE_PROTECTION}, the outermost slot after the forwarded * {@link EdgeRejectFilter} sits at {@code FilterOrder.CORE_PROTECTION}, the outermost slot after the forwarded
* header gate, and a reject <b>does not call the chain</b>. {@code AccessLogFilter} sits at * header gate, and a reject <b>does not call the chain</b>. {@code AccessLogFilter} sits at
* {@code CORE_ACCESS_LOG}, the innermost. So every edge {@code 403}/{@code 429} short-circuits <i>before</i> * {@code CORE_ACCESS_LOG}, inside the floor (on purpose: see the throttling below). So every edge
* anything logs it: the request appears in no log anywhere in the product, and the access log never carried a * {@code 403}/{@code 429} short-circuits <i>before</i> anything logs it: without this recorder the request
* {@code User-Agent} to begin with. The practical result was that nobody could answer either half of the * appears in no log anywhere in the product, and the access log carries a {@code User-Agent} only when asked to. The practical result was that nobody could answer either half of the
* obvious question — <i>was a crawler throttled</i>, and <i>why was this request rejected</i>. * obvious question — <i>was a crawler throttled</i>, and <i>why was this request rejected</i>.
* *
* <p>A rejection is also emitted <b>before</b> {@code CORE_SITE_CONTEXT}, so there is no resolved site and it * <p>A rejection is also emitted <b>before</b> {@code CORE_SITE_CONTEXT}, so there is no resolved site and it
@@ -20,6 +20,7 @@ import org.springframework.core.Ordered;
* <pre> * <pre>
* CORE_FORWARDED Integer.MIN_VALUE EDGE_INGRESS TrustedForwardedHeaderFilter (gates X-Forwarded-*) * CORE_FORWARDED Integer.MIN_VALUE EDGE_INGRESS TrustedForwardedHeaderFilter (gates X-Forwarded-*)
* CORE_PROTECTION MIN_VALUE + 1 EDGE_INGRESS EdgeRejectFilter (the O(1) reject seam) * CORE_PROTECTION MIN_VALUE + 1 EDGE_INGRESS EdgeRejectFilter (the O(1) reject seam)
* CORE_ACCESS_LOG -500 (own slot) AccessLogFilter (one line per request past the floor)
* CORE_BANDWIDTH -300 EDGE_EGRESS BandwidthFilter (meters the on-the-wire bytes) * CORE_BANDWIDTH -300 EDGE_EGRESS BandwidthFilter (meters the on-the-wire bytes)
* CORE_SITE_METRICS -290 EDGE_EGRESS SiteRequestMetricsFilter (per-site request timing) * CORE_SITE_METRICS -290 EDGE_EGRESS SiteRequestMetricsFilter (per-site request timing)
* CORE_COMPRESSION -200 EDGE_EGRESS CompressionFilter (brotli / gzip, one decision) * CORE_COMPRESSION -200 EDGE_EGRESS CompressionFilter (brotli / gzip, one decision)
@@ -30,13 +31,13 @@ import org.springframework.core.Ordered;
* CORE_SITE_RELOAD 56 TENANT SiteReloadFilter (loopback /__reload/**) * CORE_SITE_RELOAD 56 TENANT SiteReloadFilter (loopback /__reload/**)
* CORE_CONSOLE_HOST 57 TENANT ConsoleHostFilter (operator console off site hosts) * CORE_CONSOLE_HOST 57 TENANT ConsoleHostFilter (operator console off site hosts)
* CORE_ROUTE_FORM_CAPTURE 58 TENANT RouteFormCaptureFilter (reads a plugin route's form body) * CORE_ROUTE_FORM_CAPTURE 58 TENANT RouteFormCaptureFilter (reads a plugin route's form body)
* CORE_FORM_CONTENT 59 TENANT RouteAwareFormContentFilter (PUT/PATCH/DELETE forms)
* CORE_SUSPENDED_SITE 60 TENANT SuspendedSiteFilter (503s a suspended tenant) * CORE_SUSPENDED_SITE 60 TENANT SuspendedSiteFilter (503s a suspended tenant)
* CORE_QUARANTINED_SITE 65 TENANT QuarantinedSiteFilter (503s a quarantined admin) * CORE_QUARANTINED_SITE 65 TENANT QuarantinedSiteFilter (503s a quarantined admin)
* CORE_MAINTENANCE 68 TENANT MaintenanceSiteFilter (503s a self-maintenance tenant) * CORE_MAINTENANCE 68 TENANT MaintenanceSiteFilter (503s a self-maintenance tenant)
* CORE_BANDWIDTH_LIMIT 69 TENANT BandwidthLimitFilter (503s a tenant over its quota) * CORE_BANDWIDTH_LIMIT 69 TENANT BandwidthLimitFilter (503s a tenant over its quota)
* CORE_EDGE_MODE 70 TENANT (reserved — read-only edge/replica topology, later) * CORE_EDGE_MODE 70 TENANT (reserved — read-only edge/replica topology, later)
* CORE_SECURITY 100 SECURITY the Spring Security FilterChainProxy * CORE_SECURITY 100 SECURITY the Spring Security FilterChainProxy
* CORE_ACCESS_LOG Integer.MAX_VALUE innermost AccessLogFilter (final status, post-chain)
* </pre> * </pre>
* *
* <h2>Why these values</h2> * <h2>Why these values</h2>
@@ -197,13 +198,33 @@ public final class FilterOrder {
/** /**
* The kernel route dispatcher for {@code EndpointContributor} routes (robots.txt, sitemap, …) — a terminal * The kernel route dispatcher for {@code EndpointContributor} routes (robots.txt, sitemap, …) — a terminal
* application handler, inner of the plugin APPLICATION window so a plugin filter can still wrap it. It * application handler, inner of the plugin APPLICATION window so a plugin filter can still wrap it. It
* short-circuits a matched route, so such responses are not seen by the (inner) access log — endpoint/bot * short-circuits a matched route; the access log, far outside it, still records the answer.
* traffic is a separate category from the public page access log.
*/ */
public static final int CORE_ENDPOINT_DISPATCH = Integer.MAX_VALUE - 100; public static final int CORE_ENDPOINT_DISPATCH = Integer.MAX_VALUE - 100;
/** {@code AccessLogFilter} — innermost, so its post observes the final status after every inner filter. */ /**
public static final int CORE_ACCESS_LOG = Ordered.LOWEST_PRECEDENCE; * {@code AccessLogFilter} — inner of the whole EDGE_INGRESS band (the kernel's reject floor and any plugin
* ingress filter) and outer of everything else, so every request that gets past the abuse floor is logged,
* whoever answers it: a tenant gate's {@code 503}, Spring Security (a login attempt, a CSRF {@code 403}), a
* slow body's {@code 408}, an endpoint route, a page. Its {@code post} runs after every inner filter has
* returned, so the status it reads is final.
*
* <p>Until 1.1.2 it sat innermost ({@code Integer.MAX_VALUE}), and every filter that answered without calling
* the chain answered unseen: a password-guessing run against a site's {@code /login} left no line at all.
* Floor rejections stay out on purpose: a flood the floor turns away in O(1) must not become a flood of log
* writes; {@code EdgeRejectionRecorder} reports them, throttled, under {@code runway.protect}.
*/
public static final int CORE_ACCESS_LOG = -500;
/**
* {@code RouteAwareFormContentFilter} (Boot's {@code FormContentFilter}, which parses a {@code PUT}/{@code PATCH}/
* {@code DELETE} form body into parameters, bounded). Boot's own order is {@code -9900}, outer of the access log,
* where its {@code 413} for an oversized body went unlogged. Here it is inner of the site binding, so the refusal
* is in that site's log too, and inner of {@link #CORE_ROUTE_FORM_CAPTURE}, which must read a route's body
* first; and outer of the tenant gates, every plugin TENANT filter and the security chain, which read
* parameters (the CSRF check above all).
*/
public static final int CORE_FORM_CONTENT = 59;
private FilterOrder() { private FilterOrder() {
} }
@@ -85,8 +85,7 @@ class RouteAwareFormContentFilterTest {
} }
@Test @Test
void itKeepsBootsOrder() { void itSitsInsideTheAccessLogAndTheSiteBindingSoItsRefusalsAreLogged() {
assertEquals(org.springframework.boot.servlet.filter.OrderedFormContentFilter.DEFAULT_ORDER, assertEquals(mx.quest.runway.web.FilterOrder.CORE_FORM_CONTENT, filter(registry()).getOrder());
filter(registry()).getOrder());
} }
} }
@@ -4,8 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ILoggingEvent;
@@ -17,10 +20,12 @@ import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Optional; import mx.quest.runway.site.SiteContextFilter;
import mx.quest.runway.site.SiteResolver;
/** The access log fires from the post-phase (final status) for public traffic, and skips internal surfaces. */ /**
* The access log fires from the post-phase (final status) for public traffic, and skips internal surfaces. Which
* requests reach it on the running application, whoever answers them, is {@code AccessLogCoverageEndToEndTest}.
*/
class AccessLogFilterTest { class AccessLogFilterTest {
private Logger accessLogger; private Logger accessLogger;
@@ -39,10 +44,10 @@ class AccessLogFilterTest {
accessLogger.detachAppender(appender); accessLogger.detachAppender(appender);
} }
private static AccessLogFilter filter() { private final SiteLogService siteLog = mock(SiteLogService.class);
SiteResolver resolver = mock(SiteResolver.class);
when(resolver.current()).thenReturn(Optional.empty()); private AccessLogFilter filter() {
return new AccessLogFilter(resolver, mock(SiteLogService.class)); return new AccessLogFilter(siteLog, false);
} }
private void runWithFinalStatus(String path, int finalStatus) throws Exception { private void runWithFinalStatus(String path, int finalStatus) throws Exception {
@@ -94,4 +99,25 @@ class AccessLogFilterTest {
assertEquals(1, appender.list.size(), "the access log fires from finally even on an exception"); assertEquals(1, appender.list.size(), "the access log fires from finally even on an exception");
assertTrue(appender.list.get(0).getFormattedMessage().contains("/about")); assertTrue(appender.list.get(0).getFormattedMessage().contains("/about"));
} }
@Test
void theSiteThatAnsweredGetsTheLineFromTheRequestAttribute() throws Exception {
// The site-context filter is inner of this one: by the post-phase its thread binding is gone, and only the
// attribute it set on the request says which site answered.
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
request.setRequestURI("/login");
request.setRemoteAddr("198.51.100.4");
filter().doFilter(request, new MockHttpServletResponse(), (req, res) -> {
req.setAttribute(SiteContextFilter.SITE_ID_ATTRIBUTE, "acme");
((HttpServletResponse) res).setStatus(403);
});
verify(siteLog).access("acme", "198.51.100.4", "POST", "/login", 403);
}
@Test
void aRequestNoSiteAnsweredGoesToThePlatformLogOnly() throws Exception {
runWithFinalStatus("/about", 404);
assertEquals(1, appender.list.size());
verify(siteLog, never()).access(anyString(), anyString(), anyString(), anyString(), anyInt());
}
} }
@@ -103,7 +103,14 @@ class SiteInsightsServiceTest {
line(TODAY, "11:29:00", "GET", "/.well-known/security.txt", 404), line(TODAY, "11:29:00", "GET", "/.well-known/security.txt", 404),
line(TODAY, "11:30:00", "GET", "/actuator/health", 200), line(TODAY, "11:30:00", "GET", "/actuator/health", 200),
line(TODAY, "11:31:00", "GET", "/app/x", 404), line(TODAY, "11:31:00", "GET", "/app/x", 404),
line(TODAY, "11:32:00", "GET", "/broken", 500)); // neither 2xx nor 404 line(TODAY, "11:32:00", "GET", "/broken", 500), // neither 2xx nor 404
// Answers the access log has carried since 1.1.2 (refusals and login traffic): none is a view.
line(TODAY, "11:40:00", "POST", "/login", 403), // a bot's post without a form token
line(TODAY, "11:41:00", "POST", "/login", 302), // a login attempt
line(TODAY, "11:42:00", "POST", "/login", 408), // a refused slow body
line(TODAY, "11:43:00", "GET", "/members", 302), // sent to the login page
line(TODAY, "11:44:00", "GET", "/members", 403), // signed in, not allowed
line(TODAY, "11:45:00", "GET", "/", 503)); // suspended, maintenance, quota
Report r = service().report("acme", 7); Report r = service().report("acme", 7);
@@ -117,7 +124,7 @@ class SiteInsightsServiceTest {
assertEquals(TODAY + " 11:10:00", row(r.topNotFound(), "/missing").lastSeen()); assertEquals(TODAY + " 11:10:00", row(r.topNotFound(), "/missing").lastSeen());
assertEquals(1, row(r.topNotFound(), "/img/logo.png").count()); assertEquals(1, row(r.topNotFound(), "/img/logo.png").count());
assertEquals(2, r.topNotFound().size()); assertEquals(2, r.topNotFound().size());
assertEquals(20, r.linesScanned()); assertEquals(26, r.linesScanned());
assertEquals(1, r.filesScanned()); assertEquals(1, r.filesScanned());
assertFalse(r.lineCapReached()); assertFalse(r.lineCapReached());
assertFalse(r.approximate()); assertFalse(r.approximate());
@@ -161,4 +161,22 @@ class SiteLogServiceTest {
assertEquals(3, lines.size()); assertEquals(3, lines.size());
assertTrue(lines.get(2).endsWith("/page-19999\t200"), lines.get(2)); // the newest line survives assertTrue(lines.get(2).endsWith("/page-19999\t200"), lines.get(2)); // the newest line survives
} }
@Test
void underAFloodAccessLinesAreDroppedBeforeAuditLines() {
props.setQueueCapacity(16); // reserve: 16 / 8 = 2 slots for audit only
SiteLogService svc = new SiteLogService(layout, configs, props);
svc.acceptWithoutWriting();
for (int i = 0; i < 20; i++) {
svc.access("acme", "203.0.113.9", "POST", "/login", 302);
}
assertEquals(14, svc.queued(), "access lines stop short of the audit reserve");
assertEquals(6, svc.droppedCount());
svc.audit("acme", "-", "login.failure", "user=a");
svc.audit("acme", "-", "login.failure", "user=b");
assertEquals(16, svc.queued(), "the reserve takes the audit lines the flood would have crowded out");
assertEquals(6, svc.droppedCount());
svc.audit("acme", "-", "login.failure", "user=c");
assertEquals(7, svc.droppedCount(), "a full queue drops an audit line too: the reserve is not unbounded");
}
} }
@@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
/** The protection floor and access log sit at their pinned slots, and the kernel default guard passes. */ /** The protection floor and the access log just inside it sit at their pinned slots; the default guard passes. */
@SpringBootTest @SpringBootTest
class EdgeProtectionConfigTest { class EdgeProtectionConfigTest {
@@ -30,9 +30,10 @@ class EdgeProtectionConfigTest {
} }
@Test @Test
void theAccessLogSitsInnermost() { void theAccessLogSitsJustInsideTheFloor() {
assertEquals(FilterOrder.CORE_ACCESS_LOG, accessLog.getOrder()); assertEquals(FilterOrder.CORE_ACCESS_LOG, accessLog.getOrder());
assertEquals(Integer.MAX_VALUE, accessLog.getOrder()); assertTrue(accessLog.getOrder() > edgeReject.getOrder(), "floor rejections stay out of the access log");
assertTrue(accessLog.getOrder() < FilterOrder.CORE_SITE_CONTEXT, "outer of every gate that answers alone");
} }
@Test @Test
@@ -12,8 +12,8 @@ import org.junit.jupiter.api.Test;
/** /**
* The recorder that closes the edge-rejection blind spot: a reject short-circuits at * The recorder that closes the edge-rejection blind spot: a reject short-circuits at
* {@code FilterOrder.CORE_PROTECTION} without calling the chain, so it never reaches the innermost access log * {@code FilterOrder.CORE_PROTECTION} without calling the chain, so it never reaches the access log (inside the
* and appeared in <b>no</b> log anywhere in the product. * floor) and appeared in <b>no</b> log anywhere in the product.
* *
* <p>The behaviour under test is mostly about what must remain true <em>under abuse</em>, since that is exactly * <p>The behaviour under test is mostly about what must remain true <em>under abuse</em>, since that is exactly
* when this code runs: the count must stay exact, the log must not become an amplifier, and the memory used to * when this code runs: the count must stay exact, the log must not become an amplifier, and the memory used to
@@ -0,0 +1,263 @@
package mx.quest.runway.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mx.quest.runway.log.LogKind;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.protect.EdgeGuard;
import mx.quest.runway.protect.EdgeVerdict;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteStatus;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/**
* Every request the abuse floor lets through is in the access log, however it is answered: in the platform's
* {@code runway.access} stream and in the answering site's own log. Until 1.1.2 the access log sat innermost, and
* each answer below except the plain page was given by a filter outside it, so none of them was logged: a login
* attempt, a CSRF refusal, a suspended or maintenance site, a refused slow body, an oversized form refused unread,
* an endpoint route. Floor rejections and the internal surfaces stay out.
*
* <p>Against a real Jetty and the real filter chain, over raw sockets, because the gap was the chain's shape.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AccessLogCoverageEndToEndTest {
private static final Pattern CSRF = Pattern.compile("name=\"_csrf\"[^>]*?value=\"([^\"]*)\"");
/** The test guard turns this path away at the floor. */
private static final String FLOOR_REJECTED = "/floor-rejected";
@DynamicPropertySource
static void config(DynamicPropertyRegistry registry) throws IOException {
Path external = Files.createTempDirectory("runway-access-log");
ConsoleHostEndToEndTest.seed(external, null);
StorageProperties props = new StorageProperties();
props.setExternal(external);
SiteStore sites = new SiteStore(StorageLayout.from(props), new YamlStore());
sites.save(new Site("sus", "Sus", List.of("sus.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.SUSPENDED, false, null));
sites.save(new Site("mnt", "Mnt", List.of("mnt.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.ACTIVE, true, "Back soon"));
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");
}
@TestConfiguration
static class Beans {
@Bean
@Primary
EdgeGuard floorRejectingOnePath() {
return request -> FLOOR_REJECTED.equals(request.path()) ? EdgeVerdict.reject(429) : EdgeVerdict.pass();
}
}
@LocalServerPort
private int port;
@Autowired
private SiteLogService siteLogs;
private Logger accessLogger;
private ListAppender<ILoggingEvent> platformLines;
@BeforeEach
void attach() {
accessLogger = (Logger) LoggerFactory.getLogger("runway.access");
platformLines = new ListAppender<>();
platformLines.start();
accessLogger.addAppender(platformLines);
}
@AfterEach
void detach() {
accessLogger.detachAppender(platformLines);
}
@Test
void aPageIsLogged() throws IOException {
String path = "/page-" + System.nanoTime();
assertEquals(404, get("main.test", path).status());
assertLogged("main", "GET", path, 404);
}
@Test
void aLoginPostWithoutItsFormTokenIsLogged() throws IOException {
assertEquals(403, RawHttp.send(port, "POST", "main.test:" + port, "/login",
"username=guess&password=guess").status());
assertLogged("main", "POST", "/login", 403);
}
@Test
void aFailedLoginAttemptIsLogged() throws IOException {
RawHttp.Response page = get("main.test", "/login");
assertEquals(200, page.status());
Matcher token = CSRF.matcher(page.body());
assertTrue(token.find(), "a form token on /login");
RawHttp.Response attempt = RawHttp.send(port, "POST", "main.test:" + port, "/login",
"username=nobody&password=wrong-guess&_csrf=" + URLEncoder.encode(token.group(1),
StandardCharsets.UTF_8), Map.of("Cookie", String.join("; ", page.cookies())));
assertEquals(302, attempt.status(), "Spring Security answers the attempt itself, with a redirect");
assertLogged("main", "POST", "/login", 302);
}
@Test
void aSuspendedSitesRefusalIsLogged() throws IOException {
String path = "/suspended-" + System.nanoTime();
assertEquals(503, get("sus.test", path).status());
assertLogged("sus", "GET", path, 503);
}
@Test
void aSiteInMaintenanceIsLogged() throws IOException {
String path = "/maintenance-" + System.nanoTime();
assertEquals(503, get("mnt.test", path).status());
assertLogged("mnt", "GET", path, 503);
}
@Test
void anEndpointRouteIsLogged() throws IOException {
int status = get("main.test", "/manifest.webmanifest").status();
assertLogged("main", "GET", "/manifest.webmanifest", status);
}
@Test
void anOversizedPutFormRefusedUnreadIsLogged() throws IOException {
// The form-content filter answers 413 from the declared length, without reading the body or calling the chain.
String path = "/put-form-" + System.nanoTime();
assertEquals(413, RawHttp.send(port, "PUT", "main.test:" + port, path, null, Map.of(
"Content-Type", "application/x-www-form-urlencoded", "Content-Length", "99999999")).status());
assertLogged("main", "PUT", path, 413);
}
@Test
void aRefusedSlowLoginBodyIsLogged() throws Exception {
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write(("POST /login HTTP/1.1\r\nHost: main.test:" + port + "\r\nContent-Type: "
+ "application/x-www-form-urlencoded\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n"
+ "username=").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);
assertTrue(response.startsWith("HTTP/1.1 408"), response.lines().findFirst().orElse(""));
}
assertLogged("main", "POST", "/login", 408);
}
@Test
void aFloorRejectionStaysOutOfTheAccessLog() throws IOException {
assertEquals(429, get("main.test", FLOOR_REJECTED).status());
String control = "/after-floor-" + System.nanoTime();
get("main.test", control);
awaitSiteLine("main", control);
assertFalse(platformText().contains(FLOOR_REJECTED), platformText());
assertFalse(siteText("main").contains(FLOOR_REJECTED), "reported by runway.protect, throttled, instead");
}
@Test
void theInternalSurfacesStayOut() throws IOException {
get("main.test", "/app/login");
get("127.0.0.1:" + port, "/app/login");
String control = "/after-internal-" + System.nanoTime();
get("main.test", control);
awaitSiteLine("main", control);
assertFalse(platformText().contains("/app/login"), platformText());
assertFalse(siteText("main").contains("/app/login"));
}
// ---------------------------------------------------------------------------------------------------------------
private RawHttp.Response get(String host, String path) throws IOException {
return RawHttp.send(port, "GET", host.contains(":") ? host : host + ":" + port, path);
}
/**
* Both sinks carry the request with its final status. Both are waited for: the line is written when the chain
* unwinds, which can be after the client has read a response the application already completed and closed.
*/
private void assertLogged(String siteId, String method, String path, int status) {
String platform = " " + method + " " + path + " -> " + status + " (";
await(() -> platformText().contains(platform), () -> "runway.access lacks [" + platform + "]: "
+ platformText());
awaitSiteLine(siteId, "\t" + method + "\t" + path + "\t" + status);
}
private String platformText() {
StringBuilder text = new StringBuilder();
for (ILoggingEvent event : List.copyOf(platformLines.list)) {
text.append(event.getFormattedMessage()).append('\n');
}
return text.toString();
}
private String siteText(String siteId) {
return String.join("\n", siteLogs.tail(siteId, LogKind.ACCESS, 1000));
}
/** Waits (up to 15 s) until the site's access log has a line containing {@code text}. */
private void awaitSiteLine(String siteId, String text) {
await(() -> siteText(siteId).contains(text),
() -> "no access line with [" + text + "] for " + siteId + ": " + siteText(siteId));
}
private static void await(BooleanSupplier condition, Supplier<String> failure) {
long deadline = System.nanoTime() + 15_000_000_000L;
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
throw new AssertionError(failure.get());
}
}
@@ -410,7 +410,9 @@ class EncodedPathEndToEndTest {
get("main.test", control); get("main.test", control);
awaitLine("main", LogKind.ACCESS, control); awaitLine("main", LogKind.ACCESS, control);
List<String> lines = siteLogs.tail("main", LogKind.ACCESS, 1000); List<String> lines = siteLogs.tail("main", LogKind.ACCESS, 1000);
assertFalse(lines.stream().anyMatch(l -> l.contains("%6Cogin") || l.contains("%5F%5Fapp")), lines.toString()); // The console's paths only: a site's own login spelled /%6Cogin is public traffic, and logged since 1.1.2.
assertFalse(lines.stream().anyMatch(l -> l.contains("/app/%6Cogin") || l.contains("%5F%5Fapp")),
lines.toString());
} }
// --- Health, reload, Prometheus, console assets, the error page ------------------------------------------------- // --- Health, reload, Prometheus, console assets, the error page -------------------------------------------------
@@ -13,6 +13,9 @@ class FilterOrderTest {
int[] ladder = { int[] ladder = {
FilterOrder.CORE_FORWARDED, FilterOrder.CORE_FORWARDED,
FilterOrder.CORE_PROTECTION, FilterOrder.CORE_PROTECTION,
FilterOrder.CORE_ACCESS_LOG,
FilterOrder.CORE_BANDWIDTH,
FilterOrder.CORE_SITE_METRICS,
FilterOrder.CORE_COMPRESSION, FilterOrder.CORE_COMPRESSION,
FilterOrder.CORE_CSP_FINALIZE, FilterOrder.CORE_CSP_FINALIZE,
FilterOrder.CORE_HEAD_INJECTION, FilterOrder.CORE_HEAD_INJECTION,
@@ -21,13 +24,13 @@ class FilterOrderTest {
FilterOrder.CORE_SITE_RELOAD, FilterOrder.CORE_SITE_RELOAD,
FilterOrder.CORE_CONSOLE_HOST, FilterOrder.CORE_CONSOLE_HOST,
FilterOrder.CORE_ROUTE_FORM_CAPTURE, FilterOrder.CORE_ROUTE_FORM_CAPTURE,
FilterOrder.CORE_FORM_CONTENT,
FilterOrder.CORE_SUSPENDED_SITE, FilterOrder.CORE_SUSPENDED_SITE,
FilterOrder.CORE_QUARANTINED_SITE, FilterOrder.CORE_QUARANTINED_SITE,
FilterOrder.CORE_ESSENTIAL_FLOOR, FilterOrder.CORE_ESSENTIAL_FLOOR,
FilterOrder.CORE_EDGE_MODE, FilterOrder.CORE_EDGE_MODE,
FilterOrder.CORE_SECURITY, FilterOrder.CORE_SECURITY,
FilterOrder.CORE_ENDPOINT_DISPATCH, FilterOrder.CORE_ENDPOINT_DISPATCH,
FilterOrder.CORE_ACCESS_LOG,
}; };
for (int i = 1; i < ladder.length; i++) { for (int i = 1; i < ladder.length; i++) {
assertTrue(ladder[i - 1] < ladder[i], assertTrue(ladder[i - 1] < ladder[i],
@@ -97,9 +100,13 @@ class FilterOrderTest {
// TENANT: after the kernel tenant gates, before security. // TENANT: after the kernel tenant gates, before security.
assertTrue(tenant.outer() > FilterOrder.CORE_EDGE_MODE); assertTrue(tenant.outer() > FilterOrder.CORE_EDGE_MODE);
assertTrue(tenant.inner() < FilterOrder.CORE_SECURITY); assertTrue(tenant.inner() < FilterOrder.CORE_SECURITY);
// APPLICATION: inner of security (never preempts it), outer of the access log. // APPLICATION: inner of security (never preempts it).
assertTrue(application.outer() > FilterOrder.CORE_SECURITY); assertTrue(application.outer() > FilterOrder.CORE_SECURITY);
assertTrue(application.inner() < FilterOrder.CORE_ACCESS_LOG); // The access log: inner of every EDGE_INGRESS filter (floor rejections stay out of it), outer of every
// other band, so whatever a plugin filter answers is logged.
assertTrue(ingress.inner() < FilterOrder.CORE_ACCESS_LOG);
assertTrue(FilterOrder.CORE_ACCESS_LOG < FilterOrder.CORE_BANDWIDTH);
assertTrue(FilterOrder.CORE_ACCESS_LOG < egress.outer());
// The windows are disjoint and nested outer→inner. // The windows are disjoint and nested outer→inner.
assertTrue(ingress.inner() < egress.outer()); assertTrue(ingress.inner() < egress.outer());
assertTrue(egress.inner() < tenant.outer()); assertTrue(egress.inner() < tenant.outer());
@@ -36,7 +36,23 @@ class PluginFilterPlacementTest {
for (int offset : new int[] {Integer.MIN_VALUE, -1000, 0, 5, 999_000, Integer.MAX_VALUE}) { for (int offset : new int[] {Integer.MIN_VALUE, -1000, 0, 5, 999_000, Integer.MAX_VALUE}) {
int order = PluginFilterPlacement.resolve(FilterBand.APPLICATION, offset); int order = PluginFilterPlacement.resolve(FilterBand.APPLICATION, offset);
assertTrue(order > FilterOrder.CORE_SECURITY, "APPLICATION offset " + offset + " escaped inner-of-security"); assertTrue(order > FilterOrder.CORE_SECURITY, "APPLICATION offset " + offset + " escaped inner-of-security");
assertTrue(order < FilterOrder.CORE_ACCESS_LOG, "APPLICATION offset " + offset + " escaped outer-of-access-log"); assertTrue(order > FilterOrder.CORE_ACCESS_LOG, "APPLICATION offset " + offset + " escaped the access log");
}
}
@Test
void onlyAnIngressPluginFilterSitsOuterOfTheAccessLog() {
// Ingress filters turn abuse away like the floor and stay out of the access log with it; whatever any other
// plugin filter answers is logged.
for (FilterBand band : FilterBand.values()) {
if (!band.contributable()) {
continue;
}
for (int offset : new int[] {Integer.MIN_VALUE, -1000, 0, 5, 999_000, Integer.MAX_VALUE}) {
int order = PluginFilterPlacement.resolve(band, offset);
assertTrue(band == FilterBand.EDGE_INGRESS ? order < FilterOrder.CORE_ACCESS_LOG
: order > FilterOrder.CORE_ACCESS_LOG, band + " offset " + offset + " -> " + order);
}
} }
} }
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
</parent> </parent>
<artifactId>runway-dist</artifactId> <artifactId>runway-dist</artifactId>
+1 -1
View File
@@ -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 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 # "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. # hashes, not versions, and no plugin may `requires:` an essential plugin, so nothing keys on it.
version: 1.1.1 version: 1.1.2
essential: true essential: true
# The mandatory floor (SPI 1.0.0): every plugin with a mainClass declares one; the kernel's own plugin declares the # 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 # 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
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
</parent> </parent>
<artifactId>runway-plugin-protection</artifactId> <artifactId>runway-plugin-protection</artifactId>
@@ -35,7 +35,7 @@ class ProtectionDescriptorK4Test {
PluginDescriptor descriptor = shipped(); PluginDescriptor descriptor = shipped();
assertEquals("protection", descriptor.id()); assertEquals("protection", descriptor.id());
assertTrue(descriptor.isEssential()); assertTrue(descriptor.isEssential());
assertEquals("1.1.1", descriptor.version(), "versioned on the kernel's line"); assertEquals("1.1.2", descriptor.version(), "versioned on the kernel's line");
assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor()); assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor());
assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(), assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(),
"the floor names the kernel's own SPI major line"); "the floor names the kernel's own SPI major line");
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
</parent> </parent>
<artifactId>runway-spi-testkit</artifactId> <artifactId>runway-spi-testkit</artifactId>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.1</version> <version>1.1.2</version>
</parent> </parent>
<artifactId>runway-spi</artifactId> <artifactId>runway-spi</artifactId>