Commit Graph
8 Commits
Author SHA1 Message Date
Pavlo Ratushnyi dcf8a733a9 A healed storage failure returned the edge to ready without waiting for traffic
OPEN-34, measured on the shipped image before this change. With writes to
block_entries aborted, five refusals produced counted write failures and
/readyz 503. The triggers were then REMOVED — write path healthy, zero triggers
left — and no further request was sent from that source:

  t+30 s  /readyz 503   /state: banWriteFailures 3, bansNotWritten 3
  t+60 s  /readyz 503   unchanged
  t+90 s  /readyz 503   unchanged
  t+120 s /readyz 503   unchanged

The ban pillar clears only on a successful ban write, and the only thing that
produced one was the source crossing the threshold again. Readiness — the
signal an orchestrator uses to keep an edge in rotation — was therefore coupled
to attack traffic: the quieter the site, the longer a repaired edge sat out of
service, enforcing everything except one ban nobody had written.

The fix is on the write side, not on the gate. A ban the engine decided and
could not write is kept as a PendingBan and re-attempted by a hosted loop on the
same 15 s cadence the other writers use; the sentence still runs from the moment
the ban was decided, so a retry that lands late cannot quietly lengthen it, and a
pending ban whose sentence expired before it could be written is counted
(bansNeverEnforced) and reported rather than rewritten as a fresh, longer ban.
/state gained bansPendingRetry and bansNeverEnforced, because without the first
a healed storage failure is indistinguishable from a quiet site.

Teeth: PendingBanRetryTests (3) — the retry landing with no further request, the
hosted loop doing it on its own (nobody calls it in that test), and an expired
pending ban reported rather than written late. Compose gate gained a 5-assertion
scene against the shipped image: the failed ban is queued, readiness returns
after the repair with no traffic from that source, the ban reaches storage, the
queue empties, and the source that was never banned during the break answers 403
afterwards.

Gates at this commit — macOS host: unit 128/128, integration 141/141, smoke
28/0, compose 86/0, console 58/0, 0 containers left behind. Linux rehearsal,
all three stages: PASS — source (128/128, 141/141, 28/0), compose 86/0 with
enforcement lag 13 ms, console 58/0, 0 containers left behind.
2026-10-02 11:34:44 +02:00
Pavlo Ratushnyi 3f24c5d31c A ban that could not be written was logged as a concurrency race, and nothing was in force
Measured on the shipped image with writes to block_entries aborted by SQLite
triggers while reads kept working: five refusals from one source at a threshold
of 3 answered 404 five times, no ban reached storage or /state, /readyz answered
200, and the log said "BlockStore: concurrent ban on 203.0.113.12; keeping the
winner" four times over an inner "SQLite Error 19: 'gate: ban write blocked'".
Enforcement reads the snapshot and the snapshot is built from storage, so a ban
that cannot be written is a ban that exists nowhere - and the only sentence the
log offered said the opposite.

BlockStore now asks storage which case it is: re-read the row. A live engine ban
for that source means somebody won the unique-index race and nothing is wrong;
no row, or a read that cannot run either, means the write never happened. The
second case is counted (DurabilityHealth.Bans), logged with its real reason and
its consequence, and gates /readyz - the enforcement path is the path that
gates.

That also moved the boundary drawn last cycle. Observations, alerts and retention
are reporting pillars: counted, shown on /state and on the console, and no longer
gating readiness. The measurement that forced it: with the gate in place, one
lost alert left alertWriteFailures at 3 and /readyz at 503; the triggers were
removed and the stand left idle for 120 s, and it answered 503 the whole time
with the write path healthy. An alert pillar writes only when an alert happens to
be raised, so "not yet proven healthy" had become "unready forever".

ObservationWriter now retries every tracked source while it has an outstanding
failure: the write-amplification bound protects against load, not against
retries, and without this the lost rows waited for each source to be due again a
full interval later.

Teeth: BanWriteFailureTests (3) - 3 failed / 0 passed before the fix; two
WriteFailureVisibilityTests assertions re-drawn for the new boundary. Gates:
compose-smoke 63 -> 72 (the ban scene asserts 404x5, no row in storage, 503
naming bans, race lines 0/0 and the honest line present, then the ban landing on
a later refusal), smoke.sh counters now include bans, console-check 57 -> 58.
2026-10-02 09:24:43 +02:00
Pavlo Ratushnyi 2b0163aa80 A pillar that could not write kept answering with the count it had before the break
The read side got its counters last cycle; the write side was still catching
everything, logging one line and keeping the process alive. A failed write is
worse than a failed read - the row never existed and no later request brings it
back - and the surface hid it better. Measured on the shipped image with SQLite
triggers aborting every INSERT/UPDATE on source_observations and edge_alerts
while reads kept working: three new sources refused and a six-request 5xx storm
later, GET /admin-api/observations answered 200 with the same X-Total-Count it
had before the break (46), GET /admin-api/alerts still showed its one row,
/healthz and /readyz were 200, /admin-api/state had no write-side field at all,
and the log carried "flush failed, 4 entries dropped" plus two "could not
persist".

DurabilityHealth counts each writer separately; /state reports
observationWriteFailures/observationsLost/observationLastWriteError,
alertWriteFailures/alertsLost and retentionPruneFailures; /readyz answers 503
naming the pillar, the rows lost and the innermost error rather than EF's
wrapper. A counter clears only on a successful write of its own pillar, and
retention is reported without being a readiness failure - stated in code, with
the reason.

Teeth: WriteFailureVisibilityTests (5) - 5 failed / 0 passed before the fix.
Gates: compose-smoke 53 -> 63 (blocks writes with triggers, asserts the
unchanged X-Total-Count as the lie, and heals per pillar), smoke.sh 25 -> 28,
console-check 53 -> 57.
2026-10-02 08:26:45 +02:00
Pavlo Ratushnyi 39d08eca51 A pillar that stopped reading its table kept answering, and nothing on the surface said so
Measured on the shipped image (openwaf:ci, the head tree), one stand with a real
upstream:

  PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200
  404 404 from 203.0.113.79, third request -> 403   (the threshold is in force)
  04:44:43  DROP TABLE policy_settings, from outside the process
  04:45:2x  GET /admin-api/policy -> still "streakThreshold": 2, answered plainly
            GET /admin-api/state  -> "snapshotAgeSeconds":0 — the refresh "succeeded",
                                     because the tables it also reads were still there
            /healthz 200, /readyz 200, and exactly 1 line in the log
  docker restart -> GET /admin-api/policy -> "streakThreshold": 10,
                                          "trustProxyHeaders": false
  four 404s from 203.0.113.81, fifth -> 404: nothing banned

Both pillars — the policy provider and the guard's snapshot store — catch
everything their read throws, keep the last value they had, and log one line.
Keeping the last good value is the right failure posture: a database restart must
not open the gate. Keeping it unmentioned is not: for a minute the operator's page
showed a threshold that no longer existed anywhere in storage, readiness said
ready, and after a restart the defence silently came back at the default N=10.

Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep
the last error; /admin-api/state answers snapshotStale (age against the TTL the
process refuses to start without), snapshotRefreshFailures,
snapshotLastRefreshError, policyReloadFailures and policyLastReadAt;
/admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read
alongside the policy it is enforcing, the same way a capped listing carries its
completeness in headers; /readyz answers 503 while either counter is non-zero,
naming the pillar and the age of the snapshot it is running on; and the console's
summary line goes warn and says "older than the ttl", "snapshot refresh failing
xN", "policy not re-read from storage xN".

Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4
failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the
point: the numbers did not exist. The refresh test drops country_rules rather than
block_entries on purpose — only one of them is what /readyz probes, so before the
fix that test saw the refresh failing and readiness still answering 200.

Gates: compose-smoke now drops policy_settings from the running stand through a
--volumes-from sidecar, waits for the failure to be counted, asserts the counters,
the 503 and the header, puts the table back and asserts the recovery (+6
assertions; the counters are consecutive, not cumulative, so recovery is part of
the claim). smoke.sh asserts the healthy case with numbers rather than silence
(+3). console-check drives the page against that state answer and requires the
summary line to be marked and to name both pillars (+3); the state body is served
through a route because the guard refreshes the snapshot on every request — a live
stand cannot be left to age — while the contract being rendered is the one
compose-smoke measures end to end against the shipped image.

Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117,
smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions /
0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in
mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128,
117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in
mcr.microsoft.com/playwright:v1.63.0-noble: 53/0.
2026-10-02 07:07:25 +02:00
Pavlo Ratushnyi a77ab53ea8 A storage failure was reported to the operator as success, as their own bad request, and as ready
Measured on two shipped images of the same stand — openwaf:prefix built from
72d37ad and openwaf:ci built from this tree — with the block table and the
policy table dropped out from under a running edge that held 3 blocks and 1
policy row:

  DELETE /admin-api/blocks?source=operator   200 {"deleted":0}      -> 503 "NOTHING was deleted"
  DELETE /admin-api/blocks?key=203.0.113.201 200 {"deleted":0}      -> 503 "NOTHING was deleted"
  POST   /admin-api/blocks                   400 database error     -> 503 "the block is NOT in effect"
  PUT    /admin-api/policy {"mode":"Enforce"} 200, body mode=Observe -> 503 "the change is NOT in effect"
  GET    /admin-api/blocks                   500                    -> 500 (unchanged)
  GET    /readyz                             200 ready              -> 503
  GET    /healthz                            200                    -> 200 (unchanged: the recovery hatch)

Four separate lies, one class:

* BlockStore.DeleteAsync caught everything, logged a warning and returned 0, so
  the endpoint answered {"deleted":0} — the same bytes an empty list produces.
  A destructive command that could not run told the operator there was nothing
  to remove.
* BlockStore.AddOperatorAsync returned the string "database error" and the
  endpoint mapped it to 400, next to the real validation errors. A storage
  failure arrived as "your request is wrong", which invites a retry of the
  request while no block is in effect.
* PUT /admin-api/policy threw away SaveAsync's false and answered 200 with the
  policy body — showing the mode that had NOT been saved.
* /readyz used CanConnectAsync, which only proves the file opens. It kept
  answering 200 through all of the above.

The same stand, six concurrent POSTs for one address (no broken storage):
4x 204 and 2x 400 {"error":"database error"} before; 6x 204 after. The unique
index on (source key, provenance) made the loser of a race the API itself
started look like a caller who sent a bad request — which is what a double-click
on "block" in the console is. The write now retries against the winner's row.

The console had its own copy of the bug: every destructive row button wrote its
green note whatever came back, so a refused delete read as "deleted ? block(s)",
and load() — which runs after every action and on a 5 s interval — replaced the
error line with "refreshed" inside a second. The note now waits for an answer
that did not carry an error, and the refresh that follows a failed action holds
it. An empty 5xx body is now reported as an empty 5xx body instead of throwing
inside apiRaw and being swallowed.

Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 106/106 (7 new in StorageFailureHonestyTests), smoke 19/0,
compose 43/0, image 261 MB, console 45/45 (1 new assertion).
Dents: delete answers deleted:0 -> 2 fail; POST answers 400 -> 1; readyz trusts
CanConnectAsync -> 1; no retry after the unique-index loser -> 1; delete
swallows into a bare 0 -> 2; PUT /policy discards the save answer -> 1; console
writes the note whatever came back -> the console gate fails that assertion.
2026-10-02 04:22:07 +02:00
Pavlo Ratushnyi 12a0f49d0c Make the snapshot TTL a setting, and say what it is for
OPEN-12's option (b) — share the block list and shorten the TTL — was not a
deployment decision, it was a rebuild: EdgeStateStore.RefreshTtl was a
property initialised to 30 s with no configuration binding anywhere in the
tree. The measurement in research/2026-10-01-multi-instance/ showed why that
matters: the TTL is not a tuning knob, it is the propagation delay between
edges (23.7 s under ~36 req/s, 1.7 s on an idle one), so an operator who
runs more than one instance is choosing a staleness bound they cannot set
and cannot see.

The key is OpenWaf:State:RefreshTtlSeconds, default 30, and the default is
unchanged so nothing moves for anyone who does not touch it. A value outside
1-300 aborts startup instead of falling back silently, because a typo in the
staleness bound is a security setting failing quietly. /healthz now reports
snapshotTtlSeconds, so an operator can read the TTL they actually got.

Verified on this commit: 49 unit and 23 integration tests pass (13 new unit
cases on the parser; 3 new integration tests that write a ban the way another
instance would — straight into the database, no InvalidateAsync — and show a
1 s TTL closing the window inside 5 s while a 300 s TTL keeps serving a
source the database has already banned); scripts/smoke.sh 19/19;
scripts/compose-smoke.sh 27/27 against the rebuilt image; in a container
RefreshTtlSeconds=5 reports snapshotTtlSeconds:5 on /healthz, and =0 aborts
the process with the key named in the log.

One thing the check taught and the README now says instead of hiding: when
startup aborts inside the image, the container stays Up with nothing
listening until the HEALTHCHECK goes unhealthy. That is how every startup
failure in this image looks, not something this change introduces.
2026-10-01 12:57:24 +02:00
Pavlo Ratushnyi 0a8d0e7695 Operator console at /admin, over the endpoints that already exist
The admin API has been complete since a3d0777 and an operator still has to
drive it with curl. GET /admin now serves one page: mode and snapshot age, live
bans with their reasons, the sources being watched, and the countries seen.
Every control on it is one call to an existing endpoint — the page decides
nothing, which is the only reason it is safe to put on an edge.

Inherited properties, tested rather than asserted in a comment:
 * /admin is on the always-pass list, so a blocked operator can still reach the
   page that unblocks them (integration test + compose-smoke assertion);
 * the always-pass surface is never observed, so fumbling it builds no streak;
 * the token is typed into the page and sent as a header — never in a URL, where
   it would sit in proxy logs, history and Referer — and the markup is checked
   not to contain it, in the fixture and against the built image.
No external assets: a console that needs a CDN fails exactly when the site
behind the edge is under attack.

One new read endpoint, /admin-api/countries/summary, counting sources and
refusals per country from the observation aggregates — there is no request log
to count, by design.

Two bugs the new tests caught before this was true:
 * "/admin" and "/admin/" are the same route to the matcher — registering both
   is an AmbiguousMatchException, i.e. a 500 on the page; now one endpoint with
   a catch-all, so a mistyped subpath shows the page instead of being proxied to
   an upstream that has never heard of it.
 * the country query compiled and failed at translation time with a record
   constructor; an anonymous projection translates.

Gates on this commit: 36 unit + 19 integration, 0 failed; scripts/smoke.sh
19/19; docker build ok (261 MB); scripts/compose-smoke.sh 27/27, the three new
assertions included.
2026-10-01 11:32:52 +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