19 Commits
Author SHA1 Message Date
Pavlo Ratushnyi ddddfc864b recovered-partial: the blast-radius preview exists on disk with nobody's record on it
Recovered-partial, UNVERIFIED. These changes were in the working tree at session
start with no checkpoint record on any item (OPEN-75 carries no execution plan,
work result or handoff note), so they are preserved rather than built on.

Attribution: they are the OPEN-75 surface — GET /admin-api/impact, the console
panel that calls it, the write-path refusal of abbreviated v4 spellings, and the
smoke / compose / console scenes for it. The README section and endpoint-list
entry the item's definition of done asks for are not here.

Gate evidence taken against this state, not claimed for it:
  build (warnings-as-errors)  clean
  unit                        378/378
  integration                 403/405 — AlertPushQueueTests.Attempts_run_out_and_
                              the_surface_says_who_was_never_told and
                              PillarFailureVisibilityTests.The_snapshot_age_is_
                              measured_against_the_ttl_it_is_supposed_to_respect
                              fail here AND fail identically at 6f92d37 with
                              these changes absent, in a separate worktree, so
                              they are not this work's failures; their failure
                              site moves between runs (assertion vs fixture
                              StartServer), which is what an environment-sensitive
                              test looks like.
2026-10-05 18:20:42 +02:00
Pavlo Ratushnyi 4280ebb2ca a request budget says who it is pausing, and one source can be let out
The budget listing has carried three numbers per budget since OPEN-68 — sources
counted, windows running, over budget now — and no name. "3 over budget" is the
half an operator cannot act on, and the only lever for one of those three was
`DELETE /admin-api/rate-rules/{id}`: take the budget off every source on the site
to release one office behind one NAT. The edge-wide budget never had this hole,
because /admin-api/rate names its sources.

  * GET /admin-api/rate-rules/{id}/sources — who this budget is inside right now:
    sourceKey, count against the limit, when the window ends and how many seconds
    are left, overBudget. Busiest first, live windows only, paged with
    X-Total-Count / X-Truncated like every other listing. `total` is the same
    number the listing's `liveWindows` reports and the over-budget count matches
    `overBudgetNow`: the names come from the same state as the three counters,
    not from a second ledger.
  * DELETE /admin-api/rate-rules/{id}/sources?source=<key> — drop one source's
    window on one budget. Not an exemption, and the answer says so: the window
    restarts at zero and the budget counts this source again from there, while
    every other source stays paused. An operator who types an address gets the
    key this edge files it under, and the answer names the key it dropped,
    because the others sharing it are still paused. A second clear answers
    `cleared: false` and writes no second record; the first is in the change log
    under `rate rule / changed`.
  * Console: a `who` button per budget row, and a `let out` button per source.

Rulings kept: the entries are source keys with the prefix rule printed beside
them (a /24 in the list is the point, not a bug); the limit is passed in from the
rule row rather than copied into the counter, so one number is enforced once;
reading spends nothing, so the page that exists to show a pause cannot cause one;
an empty list says which kind of empty it is — "counting, nobody inside a window"
and "this budget has expired" are different answers; and the read-only token gets
a 403 on the clear, not a 401, because the token is known and its level is the
answer.

What the run caught, on this tree: two console scenes failed with `answered 403`
because the gate's own probes are refusals and the streak pillar had banned the
probe addresses — a correct edge, and a scene that cannot retry past a one-hour
ban. Both now clear that one ban by name, leaving the engine bans the netblock
scene reads standing. The first run of the feature also caught the clear
reporting `cleared: false` after actually dropping the window: the derived-key
branch dropped the state and never set the flag.

build 0 warnings / 0 errors, unit 377/377, integration 365/365 in 31 s,
console 129 assertions / 0 failed, smoke passed 202 / failed 0, compose 317
passed / 0 failed against the built image at 262 MB.

Refs OPEN-71.
2026-10-05 10:13:29 +02:00
Pavlo Ratushnyi bcfc83db40 one address in, and the edge answers everything it knows about it
An operator investigating one source had to open six admin calls — blocks,
allow, streaks, observations, alerts, the dry run — and hold the join in their
head. The join is where the wrong answers are: a v6 address looked up in full
when the ban is filed on the /64, a CIDR ban looked up by equality that never
finds it, an exemption that expired last week read as a live one, a streak
counted in one process read as the deployment's.

GET /admin-api/source?ip=<address>[&path=<path>] answers it in one call, by
asking the same objects the request path asks rather than a second copy of
their logic. Three rulings hold it together:

  * Containment, not equality. operatorBlock carries cameFromRange and the
    match that covered the address, through the same NetworkBanIndex the wire
    matches with (longest prefix first) and NetworkMatch for the allowlist.
    There is no second matcher in this build to drift.
  * The key, not the address. sourceKey and the prefix lengths that produced
    it travel in the answer: bans, streaks and budgets are filed under the key,
    the allowlist and the range bans are matched against the address, and the
    answer separates them.
  * `none` and "not visible here" are different words. A live engine ban under
    Observe mode reports applies: false with a verdict of none; an expired row
    reports live: false rather than null, because "this address used to be
    exempt" is a fact an operator acts on.

Nothing is written and nothing is spent — the dry run's rule applied to the
whole dossier. RateRuleTracker.WindowsFor is a new read that lists every path
budget a source is already inside without being handed a path, so the dossier
does not have to guess from a path it was not given, and N dossiers leave every
counter where they found it. ip is required and must be a full address: a typo
is a 400 naming the value, never a none. The read-only token may ask it.

What the run caught, on this tree: the console scene waited for "an answer is
in the box", which the previous answer still sitting there satisfies — three
assertions read the address asked one click earlier. The scene now empties the
box and waits for the address it asked by name, and matches a range row by the
key its delete button holds rather than by a cell that prints a `range` badge.

build 0 warnings / 0 errors, unit 374/374, integration 356/356 in 39 s,
console 126 assertions / 0 failed, smoke passed 192 / failed 0, compose 311
passed / 0 failed against the built image at 262 MB.

Refs OPEN-70.
2026-10-05 09:43:39 +02:00
Pavlo Ratushnyi 6a65cbf344 the dry run says what the volume pillar would answer for that source
`GET /admin-api/decide` answers what would happen to a named request and which
pillar said so, and it stayed silent about the one pillar whose number the
operator is choosing. The count is kept in the guard rather than read off a
snapshot, so the preview printed `rate: not_evaluated` and left "would this source
be rate-limited" as the one question the surface exists to answer could not ask.

The rulings this had to make, and the answer each one got:

* Reading, never spending, is the invariant. The section is built from peek reads
  of both trackers, so N dry runs leave `count` exactly where it was and write no
  alert. A preview that answered by counting its own question would refuse the next
  real request because somebody pressed a button — the tool for finding an
  over-tight budget would itself be the cause of it.
* Four silences stay apart: `not_counted` (the pillar is off, so there is no budget
  to cross), `no_source` (no address was asked, and a budget is a claim about a
  source), `refused_now`, `would_be_counted`. A fifth, `over_budget_not_enforced`,
  exists because "over budget" and "would be refused" are two answers separated by
  the mode, and collapsing them is how an observe budget becomes a surprise the day
  someone switches it on.
* `reached: false` says an earlier pillar answers the request, so the guard would
  never consult the counter for it. The volume section still reports the counters —
  they are true — but the note stops talking about a budget this request would
  never touch.
* A budget in force for the path with nothing counted for this source yet prints
  `counted: false`, not `count: 0`. "0 of 2" and "nothing yet" are answers an
  operator acts on differently.
* The path budgets are matched by the same `PathPattern.Matches`, in the same
  order, as the guard: a preview that matched differently would be a preview of a
  different edge.
* The counters are this process's (`scope: "this-process"`), said in the answer
  rather than left for the operator to remember.
* The `rate` pillar row keeps `not_evaluated` — the engine really did not evaluate
  it — and its note now points at the section that did, instead of ending as a
  silence.

What the runs caught, in order:

* The first version answered `refused_now` for an Observe crossing. The counters
  were right and the sentence was wrong: observe enforces nothing. The mode is now
  part of the verdict.
* An integration expectation asserted the note of the `rate` pillar row after a
  crossing, and read the engine ban the crossing itself had written instead — the
  request was no longer reaching the volume pillar. The assertion moved to the
  preview taken before the crossing, and the ban case now asserts the honest note.
* Rewording that note broke an older preview test that keyed on the word "preview"
  in it; the wording keeps the word, and the older test is the one that caught the
  rewording.
* The smoke scene compared a listing's over-budget count against a request count,
  which would have passed for the wrong reason; it now asserts the pair
  (tracked, over) before and after six previews.

Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit
371/371, integration 345/345 in 43 s, console 122 assertions 0 failed, smoke
passed 182 failed 0, compose 304 passed 0 failed against the built image at
262 MB, 0 containers left behind.

Refs OPEN-69.
2026-10-05 09:14:09 +02:00
Pavlo Ratushnyi 7beaa7e463 a source's request budget can be written for one path
The edge-wide budget is one number for the whole site, and for a login path that
number is always wrong: a hundred requests a minute does not stop a
credential-stuffing run that makes twenty attempts a minute — twenty looks like
a person — while five a minute locks an honest office behind one NAT out of every
page they own. The only way to make both statements true is to price the paths
differently.

The rulings this had to make, and the answer each one got:

* A rate rule is not a path rule. A path rule refuses a request because of what
  it asked for; a budget refuses it because of how often that source asked. The
  pattern language is shared because the thing being described — this path and
  what hangs off it — is the same.
* Crossing a budget writes no engine ban. The claim is about one path, so a ban
  would refuse the rest of the site as punishment for a login-page rate. The
  answer is 429 with Retry-After for the rest of that source's window, and the
  reason names the rule, its count, its limit and the pattern it was written for.
* The counters are a separate tracker, not a scope inside RateTracker. The
  edge-wide counter reads its limit and window from the policy; a rule carries
  its own. One map whose parameters change per entry is a map whose eviction and
  idle rules stop meaning anything.
* The budgets hang off rateMode rather than getting a switch of their own:
  Enforce refuses, Observe counts and raises one rate_breach alert per source per
  window naming the pattern, Off counts nothing at all. A half-counting edge is
  the state an operator cannot reason about.
* A second live budget for one pattern is a 409 — two live numbers for one path
  mean the stricter one wins by accident rather than by the operator's choice.
* The bounds are the policy's own (1..100000 requests, 1..3600 seconds), so one
  vocabulary of numbers covers both budgets and a document cannot bring in a
  budget the API would have refused.
* The listing answers with three counters — sources counted, windows running,
  over budget now — because "nobody has blown this" and "nobody can" look
  identical on paper and are different decisions.

What the runs caught, in order:

* The smoke scene first ran on 198.51.100.0/24, which an earlier scene of the
  same gate allowlists. An allowlisted source never reaches the counter, so the
  scene would have printed a row of 200s while measuring nothing. It runs on
  TEST-NET-1 now.
* The console scene drew three 404s of its own and the streak pillar banned the
  address, so the reopen assertion read the streak's 403 instead of the absence
  of the budget. The engine list is cleared before that probe and the comment
  says which pillar the clearing belongs to.
* The compose assertion compared a JSON boolean against the word "yes".
* The change-log vocabulary test still listed six sections; there are seven now.
* A unit expectation counted requests where the tracker holds windows: one
  (rule, source) pair is one window, and the count inside it is what the budget
  is measured against.

Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit
361/361, integration 337/337 in 30 s, console 120 assertions 0 failed, smoke
passed 169 failed 0, compose 300 passed 0 failed against the built image at
262 MB, 0 containers left behind.

Refs OPEN-68.
2026-10-05 08:40:58 +02:00
Pavlo Ratushnyi 848ec1a82a an operator can ban a range, not only an address
A scanner rotating through a rented /29 used to cost one row and one write per
address: POST /admin-api/blocks answered "not an IP address" for a CIDR while
the allowlist control beside it accepted one, and the config export could not
carry the operator's answer either. A CIDR now has its own table and is enforced
by containment.

The rulings:

- One list, two shapes. GET /admin-api/blocks merges address rows and range rows
  and says which is which with `kind`; DELETE ?key= takes the CIDR as it was
  typed; ?source=engine still cannot reach an operator's range, while
  ?source=operator clears both operator shapes.
- Containment is checked on the raw peer address, the same field the allowlist is
  matched on, after the exact operator block and before the engine's own ban. The
  verdict stays block_operator, so nothing downstream had to learn a new reason;
  the decision trace names the range that answered, and an allow entry still
  outranks a range.
- What is written is normalised before it is stored: 203.0.113.37/28 is stored as
  203.0.113.32/28, a /32 or /128 is stored as the bare address it already was,
  and the full-width prefix is refused on meaning rather than on form — "0.0.0.0/0"
  covers every address there is, including the one this was written from; that is
  a shutdown, not a ban on a source.
- A request pays for the number of distinct prefix lengths, not for the number of
  ranges: the index buckets by prefix and asks a set for the request address
  masked to it, most specific first, and an expired row does not stop the search
  for a broader live one.
- Export carries ranges in the blocks section and import lands them idempotently,
  so an edge's decisions survive the move. /state counts them apart from address
  blocks, and the console prints the shape beside the row.

What the run caught:

- BlockRow read Range?.Field ?? Entry!.Field. The two rows are mutually
  exclusive, so a range with no expiry, reason or redirect — the common case —
  dereferenced the row that is not there and GET /admin-api/blocks answered 500.
- NetworkBanIndex filed a row under "a.b.c.d/24" while the lookup compared a
  masked address with no prefix, so no range ever matched: ten unit tests red
  before the bucket key was fixed to the network address alone.
- smoke and compose both wrote their JSON bodies with escaped quotes straight
  inside a command substitution, which truncates the body and answers 400 — the
  hazard this file's own header warns about. The payloads are variables now.
- Scene ordering in smoke: the range scene clears the engine's list wholesale,
  which took the expired scanner row a later scene asserts on. It runs after
  those scenes now, and says why in the file.
- Test-side, worth keeping: 203.0.113.37/28 is not the network 203.0.113.16/28
  names, so an assertion that writes one and expects the other is testing the
  mask, not the match.

build 0 warnings / 0 errors, unit 334/334, integration 312/312 in 31 s, console
105 assertions 0 failed, smoke passed 137 failed 0, compose 285 passed 0 failed
against the built image at 262 MB.

Refs OPEN-66.
2026-10-05 07:22:40 +02:00
Pavlo Ratushnyi 575ef88afe an operator can ask what the edge would answer, before it answers anyone
OPEN-59. Every other admin surface answers what the edge already did, so the only test for a path rule, an exemption or a country rule is a real visitor getting the real refusal. GET /admin-api/decide?ip=&path=&country= runs the same DecisionEngine over the same snapshot the wire reads — there is no second decision to drift — and narrates the order.

The trace is the product: a verdict says what would happen, the pillar list says which pillar to change, and it keeps four silences apart (did_not_match, not_reached, not_enforced_in_this_mode, not_evaluated). In Observe mode the engine line says whether a live ban for that source exists, because 'nothing was known about this address' and 'something was known and the mode chose not to act' are the two answers operators read as one. What a preview cannot honestly answer — the live rate counter and a streak that depends on responses the upstream has not produced — is named in the body rather than left out.

Three things the run caught. IPAddress.TryParse accepts abbreviated IPv4, so '203.0.113' parses as 203.0.113.0 and a missing octet was answered 'pass' for an address the operator did not mean; the guard now requires a full dotted quad. The preview read state.Current while the guard calls GetOrRefresh(), so it could answer from a snapshot the wire had already replaced — the whole claim of the feature is that the two agree. And a Pass carries no source key, so the Observe note claimed 'no live ban' for a source that had one; the key is now computed for the question rather than read off the answer.

Gates on this tree: build 0 warnings / 0 errors, unit 256/256, integration 245/245, smoke 65/0, compose 229/0 against the built image (261 MB), console 90/0.
2026-10-05 01:36:29 +02:00
Pavlo Ratushnyi f1715e4b7c a refused visitor gets the answer in sentences, and the status never moves
Every refusal this edge makes was written for the operator and read by a person. The audience that can actually act on a refusal — the office whose address tripped a streak, the visitor who followed a link into a path a rule refuses, the customer a geo policy misattributed — cannot do anything with {"error":"blocked_by_policy","reason":"3 consecutive refusals…"}. The guard now negotiates the body by Accept: a client that names text/html or application/xhtml+xml with q>0 gets a page, everything else gets the JSON it has always got. Accept: */* is deliberately not HTML: it means "I did not think about it", and it is what curl, monitors and SDKs send, which are exactly the clients that parse the body.

BlockPage is a pure function in the domain (no HttpContext, no I/O) so the wording is testable without a pipeline; it landed there rather than in Edge/Pipeline because the unit project references Domain and Infrastructure only. Three rules it exists to keep: the status never changes (a 429 that became 200 because a browser looked at it would be a defence that switches itself off when observed); nothing is fetched (inline CSS, no script/font/image/link, robots=noindex — the page goes to anonymous visitors and the runtime image is distroless); and the operator's own note is never rendered, because an operator block's reason is free text typed during an incident about a source, not a message to this visitor, so that branch shows the fact and no reference. What the page does carry is the machine reference the JSON already carried — rule_12, country_denied_DE, rate_3_of_2 — plus Retry-After and the expiry in UTC: the string the visitor quotes and the string the operator searches the listings for.

EdgeVerdict gained BlockRate so the rate branch logs the same verdict line the other four do instead of being the one refusal with no log, and the same helper now writes all five.

Gates on this tree: build 0 warnings / 0 errors, unit 227/227 (+20 BlockPage cases), integration 225/225 in 20 s (+6 wire cases asking what a browser and what curl get for the same refusal), smoke passed 52 failed 0 (+4), compose 209 passed 0 failed against the image at 261 MB, console 90 assertions 0 failed — unchanged, because this feature changes what a visitor sees and nothing the console shows.

The smoke count also had to be re-derived rather than trusted: a python replace whose replacement omitted its anchor deleted the line check 'the path is refused rather than proxied' 403 and left its command dangling as a continuation of the rule-add check above it, so the gate reported 51 and one assertion had silently vanished while still looking green. Same failure mode as the PolicyBounds edit earlier in this session — replace(a, b) where b does not contain a is a delete, not an insert.
2026-10-04 21:53:06 +02:00
Pavlo Ratushnyi 5cf93ef0fd a source that asks too often is stopped, even when the origin keeps answering
Every defence this edge had reads something that already happened: the status the
application answered, the country the address sits in, a list a human wrote. A
source asking for a cheap path two hundred times a minute produces no refusal, so
no streak matures, no path rule names it, and the origin serves all two hundred.
The only signal is the count, and a count has to be kept while the requests are
arriving — which is why this pillar is the one piece of live state on the request
path, and why it runs after the ordered decision instead of inside it.

`rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds`
(policy_settings, so no schema change). Off is the default: a limit nobody wrote
is a defence nobody asked for, and a false positive here locks out a whole office
behind one address. `observe` counts and raises one `rate_breach` alert per
source per window. `enforce` answers the request that crosses with 429 +
Retry-After — the surplus never reaches the origin — and writes an engine ban, so
the stop outlives the window, is shared with the other edges and survives a
restart; from then on the answer is the ban's own 403. One breach, one alert, one
ban write per source per window: a flood is exactly the traffic that turns a
per-request durable write into the thing that takes the database down.

Exempt by construction rather than by a second copy of the precedence rules: the
counter runs only on a plain Pass, so an always-pass prefix, an allowlisted
address, a matched rule, a block or a geo refusal never reaches it. The budget
counts exactly the requests that would have cost the origin.

Costs, stated rather than hidden: the counter is per process, so N edges allow N
times the budget (the same trade `SharedStreaks` made for the streak, at a round
trip per request instead of per observed response); the window is fixed, not
sliding, so the worst sustained rate is twice the limit across one boundary — a
sliding counter needs one entry per request, which is a map that grows at attack
rate.

Two things the run caught rather than the design assumed:

 * The guard wrote the 429 and then called next() anyway, so YARP answered
   "the request cannot be forwarded, the response has already started". The
   pillar now says whether the request may go through.
 * `StreakTracker.Configure` was called by nobody outside its own tests, so
   `maxTrackedSources` bounded nothing in a running edge — the map grew to the
   built-in 10000 whatever the operator had asked for. Both maps are configured
   at warm-up and on a policy write now.

And the smoke gate was not testing what its first line says. The edge was started
from the repository root, where there is no appsettings.json, so it loaded no
ReverseProxy section at all, logged "Request reached the end of the middleware
pipeline without being handled by application code" for every request, and
answered 404 for a path the upstream was serving with 200. Every assertion in the
file expects a 404 or a refusal, so the gate kept passing on an edge that never
proxied anything. Naming the content root fixes it; the streak scene also waits
for the ban row to exist before asking the wire whether it is enforced, because
the ban is written out of band after the response that proved it.

Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219
in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209
passed 0 failed, image 261 MB.

OPEN-56
2026-10-04 21:00:33 +02:00
Pavlo Ratushnyi 5e6a840731 a path rule refuses the request itself, before the upstream ever sees it
Every pillar this edge had until now judged the response or the source: a streak
of refusals the upstream produced, a country, an operator's list of addresses.
The request itself was never looked at. A known-bad request therefore always
reached the origin and cost it something, and became a defence only if the
origin's answer happened to fall in the refusal range three times in a row.

A request rule is a path pattern an operator writes: `GET/POST/DELETE
/admin-api/rules`, listed in the order they are enforced, with an action.
`observe` counts matches (one alert per rule per 15 minutes, the tally on the
listing) and lets the request through, which is how an operator learns what a
rule would have blocked before it blocks anything; `block` answers 403 naming the
rule id — the id, not the pattern, because a 403 body that quotes the pattern
tells the visitor which payload to change. It fires in Observe mode too: the mode
switches off what the edge decides by itself, not what a human wrote down. It
sits below the allowlist and above the two source-level lists, because "this path
is refused" is the more specific claim about this request.

The pattern language is a glob — `*` and `?`, anchored, case-insensitive, `*`
crossing `/` — and deliberately not a regex: the operator writes the pattern and
an anonymous visitor writes the path, and `(a+)+$` against 400 a's is a ReDoS
with the edge's CPU. A pattern that can only silently do nothing (no leading
`/`, `/*`, a control character, over 256 characters) is refused with the reason,
and at most 500 live rules exist because every request is checked against each.

Two things the run caught rather than the design assumed:

 * The rules read shared one statement block with the rest of the snapshot.
   `request_rules` is the newest table in the schema, and the default schema step
   is EnsureCreated, which creates a missing database and changes nothing about
   an existing one — so every database created before this feature has every
   table except that one, and the first refresh after startup would have thrown,
   frozen the operator's block list at its old contents, and looked healthy. The
   rules read is a statement of its own now: a missing table costs the rules
   pillar and says so (`requestRulesAvailable`, `requestRulesError`, a NOT READ
   line over the rules table) while every other pillar keeps enforcing. The
   migration set was stale in the same direction — it never had `source_streaks`
   either, so the `migrate` path could not create the table OPEN-52 added;
   `AddRequestRules` adds both.
 * The console gate banned its own probe address. The seed sets the streak
   threshold to 3 and the gate probes 404 paths, so the last assertion in the new
   scene read a `blocked_by_policy` as "the rule is still in force" — and the
   ban, unlike the rule, outlives `compose down` in the data volume. The scene
   probes its own address now and the cleanup clears engine bans.

Measured on this tree: build 0 warnings / 0 errors, unit 195/195 (44 new: the
glob's semantics and rejections, and where the new pillar sits in the order),
integration 208/208 in 25 s (14 new, including a fixture that drops the rules
table and asserts the operator block is still enforced), smoke 36/0 (7 new
against a running edge), console 85 assertions 0 failed (6 new, driving the rule
form in a real browser), compose 209/0 against the built image at 261 MB.
2026-10-04 19:48:52 +02:00
Pavlo Ratushnyi 8ee6570458 the streak map can live in the database, so N edges mature one streak
The multi-instance research measured the gap rather than guessing it: four
refusals from one address, two per edge, at a threshold of 3, produced no ban
anywhere, because the block list was shared through the database and the streak
map was not (research/2026-10-01-multi-instance/, D1). OpenWaf:Policy:
SharedStreaks=true moves the counters onto a row in source_streaks; the default
stays the in-process map, because that is the deployment that loses nothing.

The rules were extracted into StreakRules.Apply and both stores call it — the
in-process map against a StreakState, the shared one against a row. A second
copy of the streak semantics would put the drift back where this removes it.
Version is a concurrency token, so two edges writing one source produce a retry
against the winner's row rather than a silently dropped refusal; a clean answer
on any edge ends the run on every edge, in one statement. The rows age out on
the same ObservationRetentionDays window as observations. Both surfaces say
which store answered: /admin-api/streaks scope is this-process or
shared-database, /admin-api/state answers streakScope, and the console's streak
note stops claiming "this edge process only" when it is not true.

Found by running it for real rather than in-process: two edge processes on one
SQLite file both create the schema on startup, and the loser of that race died
in StartAsync with 'table "allow_entries" already exists' — hosting failed to
start and the process never listened. The schema step now re-checks existence
and continues, because what has to be true is that the schema exists, not that
this process made it.

Measured on this tree: build 0 warnings / 0 errors, unit 132/132, integration
191/191 in 32 s (6 new, two real edge instances on one SQLite file each), smoke
28/0, console 78 assertions 0 failed. Out of process, two edge binaries on one
file at a 5 s TTL: A answered 404, 404; B answered 404 on the third refusal and
403 after it; both edges then reported consecutiveRefusals: 3 with
scope: shared-database, and A started enforcing 4 s later. Before the schema fix
the second process aborted on startup, which is how that fix was found.
2026-10-04 17:13:21 +02:00
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