Commit Graph
8 Commits
Author SHA1 Message Date
Pavlo Ratushnyi b75888fa83 Every source key the console prints is now a question the operator can ask back, and the counts answer it filtered
/streaks learned the ?source= filter the observation and alert listings
learned in OPEN-33, and standingStreaks narrows with the rows while
trackedSources stays the map size. The console narrows observations and
streaks to one key from a box or from a click on any key in any table,
prints the filtered total under each, and says the words 'no recorded
observations for <key>' instead of drawing an empty box.

The first version appended '&source=' to a bare path, which is a
different route: the edge answered 404 and the streak line printed
'unknown scope'. The console gate caught it; the API tests did not,
because they call the API. Hence withSrc, which decides the separator
per path.
2026-10-02 16:21:35 +02:00
Pavlo Ratushnyi 0e2aee6beb A capped listing answered like it was the whole answer, and one said it was capped when it was not
?source= is refused by name now; a limit nobody meant still silently became a
different limit. Measured on the shipped image (openwaf:ci), 1103 sources
recorded:

  GET /admin-api/observations?limit=100000 -> 200, 1000 rows, no total, no
      truncation flag. 103 recorded sources were unreachable and the response
      read like a complete answer.
  GET /admin-api/observations?limit=0 and ?limit=-1 -> 200, one row each.
  GET /admin-api/streaks?limit=1000 -> 200, 2 streaks, trackedSources 3,
      X-Truncated: true. Nothing had been cut: the header compared the page
      against the size of the streak map, and the map keeps a source whose
      streak a clean answer ended while the listing leaves those out on purpose.

The block listing already carried X-Total-Count and X-Truncated, with a comment
saying that is what stops a page reading like a complete answer. The two
listings the console reads most had neither. Now every capped listing carries
both, takes an offset that reaches the rest, and refuses a limit outside its
range by name: "limit must be 1..1000; got 0". /streaks measures truncation
against standing streaks, reports standingStreaks next to trackedSources, and
pages.

The page says what it is showing. The console gate run printed "newest 25 of 42
recorded sources" and "Newest 25 of 274 alerts" — before this change both tables
rendered as if the page were the window, and the volume that survives compose
down is exactly where that matters.

Teeth, each reverted and counted, then restored: headers removed -> 2
integration failures; limit/offset clamped instead of refused -> 13; streak
header counted against the map again -> 1; standingTotal counted as the map size
-> 1 unit + 1 integration.

Gates on this tree: unit 128/128, integration 89/89, smoke passed 19 failed 0,
compose 43 passed 0 failed, console 42 assertions 0 failed.
2026-10-02 02:19:27 +02:00
Pavlo Ratushnyi 00f6dd9513 A block's redirect target went into a header unchecked, and one of them turned the block into a 500
Measured on the shipped image (openwaf:ci). POST /admin-api/blocks answered 204
for every one of these, and the next request from that source paid for it:

  "https://example.com/ok"               301 Location: https://example.com/ok
  "http://bad target"                    301 Location: http://bad target
  "http://x.invalid/<CRLF>X-Injected: 1" 500 Internal Server Error, Content-Length: 0
  "javascript:alert(1)"                  301 Location: javascript:alert(1)
  "not-a-url"                            301 Location: not-a-url

The CRLF row is the defect rather than the wart: Kestrel refuses to write the
header, so the operator's own block — written with a 204 — became a server error
for that visitor. Nothing was injected; the server validated the header, which
is the only part of the old behaviour that was safe. javascript: and data: are
absolute URIs too, and a redirect is a navigation, so those are an execution
request made on the operator's behalf by a string somebody typed into a form.

RedirectTarget.IsSendable is now the one judge: absolute, http(s), no control
characters or surrounding whitespace. The API answers 400 naming the field, and
DecisionEngine ignores a target it cannot send and answers the block's own
default instead — for a row that arrived by a restored backup or a hand edit,
where the API guard never ran.

The console gate also asserts the other half of the same boundary: every value
that came from the API is rendered through esc(), and two of those values are
not authored by the person reading the page — the path in an observation row is
whatever an anonymous visitor asked for, and a block reason is a form field. The
seed now sends a percent-encoded path carrying <img onerror=...> and an operator
block whose reason carries <svg onload=...>, and the page must show both as text
and create no elements from them.

  unit 105 -> 126 (+21: the target table, and the decision point's fallback)
  integration 55 -> 62 (+7: 400 by name for five targets, a valid target
    reaching the wire as 301, and a hand-written row with CRLF answering 301 to
    the default target instead of the 500 it used to answer)
  console 33 -> 37 assertions

Teeth, each measured by removing the thing: esc() reduced to identity in the
shipped page makes the console gate go red with 6 failures, and the page title
becomes "XSS" — the anonymous visitor's path executed script in the operator's
browser. Dropping the API guard fails exactly 5 integration tests; dropping the
decision-point guard fails exactly 6 unit tests and the 1 hand-written-row test.
2026-10-02 00:34:35 +02:00
Pavlo Ratushnyi 52f4167867 A policy value nobody believed was stored, echoed back, and obeyed
The admin API answered 200 to anything. Measured on the shipped image
(openwaf:ci) before this commit:

  PUT {"streakThreshold":0}          -> 200, streakThreshold still 3, 0 log lines
  PUT {"maxTrackedSources":0}        -> 200, unchanged
  PUT {"banDurationMinutes":-1}      -> 200, unchanged
  PUT {"streakWindowMinutes":0}      -> 200, unchanged
  PUT {"refusalRange":"not-a-range"} -> 200, unchanged
  PUT {"engineBlockStatus":999}      -> 200, and the edge answered HTTP/1.1 999
  PUT {"engineBlockStatus":1000}     -> 200, and every banned request died as
                                       "curl: (1) Unsupported HTTP/1 subversion
                                        in response" — no HTTP response at all
  PUT {"ipv4KeyPrefixLength":0}      -> 200, one 404 banned the key "*", and the
                                       next three never-seen addresses were
                                       refused on their first request
  PUT {"ipv4KeyPrefixLength":999}    -> 200, GET echoed 999, enforcement used 32

Two different failures hid behind that 200. A value the code did not want was
dropped without a word, so the operator read "OK" over a policy that had not
moved. A value the code did want was stored and obeyed literally, and one of
those (engineBlockStatus=1000) takes the site down for every banned visitor
from one admin call.

So the ranges now live in one place, PolicyBounds, next to the reason for each
one, and three layers read it:

  * the admin endpoint answers 400 naming the key and the range — the same
    shape mode, geo and the state TTL already used;
  * the loader ignores a row outside the range and logs the key and the value,
    for a backup restored or a row edited by hand;
  * DecisionEngine refuses to put an unsendable status on the wire at all, and
    answers 403 instead.

ipv4KeyPrefixLength keeps a floor of 8 rather than 0, because 0 is not a coarse
grouping, it is the literal key "*" — one streak and one ban shared by every
IPv4 address on the internet.

Tests: 46 unit (the bounds table, the "*" mechanism, the wire guard) and 18
integration (400 by name, a refused write changing nothing, an accepted value
reaching the wire as 451, a hand-edited row ignored). Teeth, each measured by
removing the layer: no API validation -> 16 integration tests fail; no wire
guard -> 3 unit tests fail; no loader gate -> 1 integration test fails.
2026-10-01 23:51:30 +02:00
Pavlo Ratushnyi eea385e90c A refusal ended the error run but not the alert episode, so the next outage was silent
Review finding on the edge-trigger rule. The Refusal branch zeroes
ConsecutiveServerErrors without clearing LastAlertedServerErrors, so a source
alternating 5xx with 4xx kept a stale "already alerted at 12" mark while its
error count restarted at 1: the next twelve broken answers stayed silent until
the count doubled the stale mark. One refusal inside the window was enough.

Now the mark goes with the run it describes. A_refusal_ends_the_server_error_
episode_so_the_next_outage_is_not_silent pins it: 3 alerts, one refusal, 3 more
alerts. With the reset removed exactly that test fails (1 failed, 58 passed).

Gates: build 0 warnings, unit 59/59, integration 32/32, smoke 19/19.
2026-10-01 18:29:25 +02:00
Pavlo Ratushnyi 9615352144 Both alerts were level-triggered, so a storm wrote one alert row per request
The streak engine raised an alert on every response once the count was past
the threshold, and neither condition ends on its own: a 5xx never bans, and in
Observe mode nothing bans at all, so the source stays observable on every
request. Measured on the shipped image in the compose gate: 12 upstream 502s
at N=3 wrote 10 alert rows, and 11 refusals in a dry run wrote 9. That is
attacker-shaped growth kept for the whole retention window, and the operator's
alert list (newest 100 in the console, limit=500 on the endpoint) showed one
source and nothing else.

Both kinds are now edge-triggered: one row on the crossing, then one per
doubling. Same two measurements answer 3 and 2. A gap past the window or a
clean answer ends the episode, so the next outage announces itself again —
alerting once per source per process would hide an outage that got ten times
worse while nobody was looking.

Teeth, measured rather than asserted: with IsEscalation forced to the old
level-triggered answer, exactly the four new unit tests and the two new
integration tests fail, and the compose gate reports 10 and 9 and fails those
two checks; the other 41 compose checks stay green.

Gates on this commit — host (macOS): build 0 warnings, unit 58/58, integration
32/32, smoke 19/19, image 261 MB, compose-smoke 43/43. Linux rehearsal
(scripts/ci-linux-rehearsal.sh): source, compose and console gates all PASS,
exit 0.
2026-10-01 17:34:59 +02:00
Pavlo Ratushnyi f516b3fc85 Show the streak that is standing, and make a clean answer end it
Two things, found in that order, and the second one is the reason the first
was worth building.

The console could say how many sources the edge was tracking but not which one
was three refusals from a ban. GET /admin-api/streaks now answers that with the
current consecutive count — not the maximum the durable observation row keeps,
which reports a source that has been clean for an hour as if it were still at
the gate. The payload names its own scope ("this-process") and carries the
threshold, the window and the map cap, because the number is meaningless
without them; the console says so above the table. This is the same fact the
two-edge measurement in research/2026-10-01-multi-instance/ cost real time to
establish, now visible to whoever is operating the box.

Reading that endpoint is what exposed the bug. The README promises "a 2xx/3xx
resets the streak to zero" and lists it as the mitigation for banning honest
traffic off a shared egress. StreakTracker honours that. The observer never
told it: ResponseObservationMiddleware returned early for every neutral
response, so on the wire a visitor alternating a 404 with a normal page view
accumulated refusals across every honest request and still matured a ban. The
documented mitigation existed in the domain object and not in the pipeline.

Fix: the observer calls StreakTracker.ResetIfTracked for a 2xx/3xx. No evidence
is built and no MMDB read is paid for a clean answer; an untracked source costs
one dictionary lookup. Measured in the image, 600 proxied clean answers, before
and after: p50 1.45 -> 1.50 ms, p95 2.98 -> 2.96 ms. Nothing to see.

Gates on this commit: build 0 warnings; unit 54/54; integration 27/27;
scripts/smoke.sh 19/19; scripts/compose-smoke.sh 27/27. The new tests have
teeth, checked by removing the fix: with ResetIfTracked commented out, exactly
two tests fail - the wire-level one and the streaks listing - and all 27 pass
when it is put back. On the wire in the container, threshold 3: probe, clean,
probe, clean, probe leaves a streak of 1; three consecutive probes take it to
4; one clean answer empties the list.
2026-10-01 13:19:56 +02:00
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00