Runway 1.1.2

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

No files matched your search

@@ -6,14 +6,16 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import mx.quest.runway.web.FilterOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.servlet.filter.OrderedFormContentFilter;
/**
* Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter outermost (order
* {@code -9900}) so a {@code PUT}/{@code PATCH}/{@code DELETE} form body becomes request parameters for
* Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter early (order
* {@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 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
@@ -51,6 +53,7 @@ public class RouteAwareFormContentFilter extends OrderedFormContentFilter {
public RouteAwareFormContentFilter(ObjectProvider<EndpointContributorRegistry> registry, long cap) {
this.registry = registry;
this.cap = Math.max(0, cap);
setOrder(FilterOrder.CORE_FORM_CONTENT);
}
@Override
@@ -1,6 +1,5 @@
package mx.quest.runway.log;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.FilterOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
@@ -8,19 +7,18 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Registers {@link AccessLogFilter} as the innermost filter ({@link FilterOrder#CORE_ACCESS_LOG}), so its
* post-phase observes the final response status of every public request, and enables {@link LogProperties}.
* Registers {@link AccessLogFilter} at {@link FilterOrder#CORE_ACCESS_LOG}, just inside the abuse floor, so it logs
* every public request the floor lets through with its final status, and enables {@link LogProperties}.
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LogProperties.class)
public class AccessLogConfig {
@Bean
public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteResolver siteResolver,
SiteLogService siteLog,
public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteLogService siteLog,
LogProperties properties) {
FilterRegistrationBean<AccessLogFilter> registration = new FilterRegistrationBean<>(
new AccessLogFilter(siteResolver, siteLog, properties.isAccessLogUserAgent()));
new AccessLogFilter(siteLog, properties.isAccessLogUserAgent()));
registration.setOrder(FilterOrder.CORE_ACCESS_LOG);
registration.addUrlPatterns("/*");
registration.setName("accessLogFilter");
@@ -5,8 +5,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.site.SiteContextFilter;
import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.LogSafe;
import mx.quest.runway.web.RequestPaths;
@@ -15,9 +14,16 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* The innermost filter ({@code FilterOrder.CORE_ACCESS_LOG}): it logs one event per <b>public</b> request from
* its {@code post} phase, so it observes the <b>final</b> status set by every inner filter and the handler.
* Being innermost is the whole point — an outer position would log a not-yet-decided status.
* The access log: one event per <b>public</b> request, written from its {@code post} phase, once every inner filter
* and the handler have finished, so the status it records is the one the request was answered with. (The exception:
* 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
* {@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).
*
* <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
* log}. This filter runs <em>inside</em> the site-context filter, so the tenant binding is still live in the
* post phase.
* when a site answered (a public tenant request) — that site's own {@link SiteLogService#access per-site access
* log}. The site is read from the {@link SiteContextFilter#SITE_ID_ATTRIBUTE request attribute} the site-context
* 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 {
private static final Logger log = LoggerFactory.getLogger("runway.access");
private final SiteResolver siteResolver;
private final SiteLogService siteLog;
private final boolean logUserAgent;
public AccessLogFilter(SiteResolver siteResolver, SiteLogService siteLog, boolean logUserAgent) {
this.siteResolver = siteResolver;
public AccessLogFilter(SiteLogService siteLog, boolean logUserAgent) {
this.siteLog = siteLog;
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
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
@@ -69,9 +70,8 @@ public class AccessLogFilter extends OncePerRequestFilter {
log.info("{} {} {} -> {} ({}ms)", ip, request.getMethod(),
request.getRequestURI(), response.getStatus(), millis);
}
Site site = siteResolver.current().orElse(null);
if (site != null) {
siteLog.access(site.id(), ip, request.getMethod(), request.getRequestURI(), response.getStatus());
if (request.getAttribute(SiteContextFilter.SITE_ID_ATTRIBUTE) instanceof String siteId) {
siteLog.access(siteId, ip, request.getMethod(), request.getRequestURI(), response.getStatus());
}
}
}
@@ -62,6 +62,14 @@ public class SiteLogService {
private final SiteLogConfigService configs;
private final LogProperties props;
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 static final long DROP_WARN_INTERVAL_MS = 60_000L;
private volatile long lastDropWarnAt;
@@ -73,7 +81,9 @@ public class SiteLogService {
this.layout = layout;
this.configs = configs;
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
@@ -113,6 +123,16 @@ public class SiteLogService {
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). */
public long droppedCount() {
return dropped.get();
@@ -219,7 +239,9 @@ public class SiteLogService {
if (!running) {
return;
}
if (!queue.offer(event)) {
boolean accepted = event.kind() == LogKind.ACCESS && queue.remainingCapacity() <= auditReserve
? false : queue.offer(event);
if (!accepted) {
long total = dropped.incrementAndGet();
// 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.
@@ -15,9 +15,9 @@ import org.slf4j.LoggerFactory;
* <h2>The blind spot this closes</h2>
* {@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
* {@code CORE_ACCESS_LOG}, the innermost. So every edge {@code 403}/{@code 429} short-circuits <i>before</i>
* anything logs it: the request appears in no log anywhere in the product, and the access log never carried a
* {@code User-Agent} to begin with. The practical result was that nobody could answer either half of the
* {@code CORE_ACCESS_LOG}, inside the floor (on purpose: see the throttling below). So every edge
* {@code 403}/{@code 429} short-circuits <i>before</i> anything logs it: without this recorder the request
* 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>.
*
* <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>
* 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_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_SITE_METRICS -290 EDGE_EGRESS SiteRequestMetricsFilter (per-site request timing)
* 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_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_FORM_CONTENT 59 TENANT RouteAwareFormContentFilter (PUT/PATCH/DELETE forms)
* CORE_SUSPENDED_SITE 60 TENANT SuspendedSiteFilter (503s a suspended tenant)
* CORE_QUARANTINED_SITE 65 TENANT QuarantinedSiteFilter (503s a quarantined admin)
* CORE_MAINTENANCE 68 TENANT MaintenanceSiteFilter (503s a self-maintenance tenant)
* 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_SECURITY 100 SECURITY the Spring Security FilterChainProxy
* CORE_ACCESS_LOG Integer.MAX_VALUE innermost AccessLogFilter (final status, post-chain)
* </pre>
*
* <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
* 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
* traffic is a separate category from the public page access log.
* short-circuits a matched route; the access log, far outside it, still records the answer.
*/
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() {
}
@@ -85,8 +85,7 @@ class RouteAwareFormContentFilterTest {
}
@Test
void itKeepsBootsOrder() {
assertEquals(org.springframework.boot.servlet.filter.OrderedFormContentFilter.DEFAULT_ORDER,
filter(registry()).getOrder());
void itSitsInsideTheAccessLogAndTheSiteBindingSoItsRefusalsAreLogged() {
assertEquals(mx.quest.runway.web.FilterOrder.CORE_FORM_CONTENT, 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.assertThrows;
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.when;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
@@ -17,10 +20,12 @@ import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Optional;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.site.SiteContextFilter;
/** 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 {
private Logger accessLogger;
@@ -39,10 +44,10 @@ class AccessLogFilterTest {
accessLogger.detachAppender(appender);
}
private static AccessLogFilter filter() {
SiteResolver resolver = mock(SiteResolver.class);
when(resolver.current()).thenReturn(Optional.empty());
return new AccessLogFilter(resolver, mock(SiteLogService.class));
private final SiteLogService siteLog = mock(SiteLogService.class);
private AccessLogFilter filter() {
return new AccessLogFilter(siteLog, false);
}
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");
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:30:00", "GET", "/actuator/health", 200),
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);
@@ -117,7 +124,7 @@ class SiteInsightsServiceTest {
assertEquals(TODAY + " 11:10:00", row(r.topNotFound(), "/missing").lastSeen());
assertEquals(1, row(r.topNotFound(), "/img/logo.png").count());
assertEquals(2, r.topNotFound().size());
assertEquals(20, r.linesScanned());
assertEquals(26, r.linesScanned());
assertEquals(1, r.filesScanned());
assertFalse(r.lineCapReached());
assertFalse(r.approximate());
@@ -161,4 +161,22 @@ class SiteLogServiceTest {
assertEquals(3, lines.size());
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.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
class EdgeProtectionConfigTest {
@@ -30,9 +30,10 @@ class EdgeProtectionConfigTest {
}
@Test
void theAccessLogSitsInnermost() {
void theAccessLogSitsJustInsideTheFloor() {
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
@@ -12,8 +12,8 @@ import org.junit.jupiter.api.Test;
/**
* 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
* and appeared in <b>no</b> log anywhere in the product.
* {@code FilterOrder.CORE_PROTECTION} without calling the chain, so it never reaches the access log (inside the
* 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
* 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);
awaitLine("main", LogKind.ACCESS, control);
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 -------------------------------------------------
@@ -13,6 +13,9 @@ class FilterOrderTest {
int[] ladder = {
FilterOrder.CORE_FORWARDED,
FilterOrder.CORE_PROTECTION,
FilterOrder.CORE_ACCESS_LOG,
FilterOrder.CORE_BANDWIDTH,
FilterOrder.CORE_SITE_METRICS,
FilterOrder.CORE_COMPRESSION,
FilterOrder.CORE_CSP_FINALIZE,
FilterOrder.CORE_HEAD_INJECTION,
@@ -21,13 +24,13 @@ class FilterOrderTest {
FilterOrder.CORE_SITE_RELOAD,
FilterOrder.CORE_CONSOLE_HOST,
FilterOrder.CORE_ROUTE_FORM_CAPTURE,
FilterOrder.CORE_FORM_CONTENT,
FilterOrder.CORE_SUSPENDED_SITE,
FilterOrder.CORE_QUARANTINED_SITE,
FilterOrder.CORE_ESSENTIAL_FLOOR,
FilterOrder.CORE_EDGE_MODE,
FilterOrder.CORE_SECURITY,
FilterOrder.CORE_ENDPOINT_DISPATCH,
FilterOrder.CORE_ACCESS_LOG,
};
for (int i = 1; i < ladder.length; i++) {
assertTrue(ladder[i - 1] < ladder[i],
@@ -97,9 +100,13 @@ class FilterOrderTest {
// TENANT: after the kernel tenant gates, before security.
assertTrue(tenant.outer() > FilterOrder.CORE_EDGE_MODE);
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.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.
assertTrue(ingress.inner() < egress.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}) {
int order = PluginFilterPlacement.resolve(FilterBand.APPLICATION, offset);
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);
}
}
}