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.
openwaf
An edge that sits in front of an application it knows nothing about, proxies to it, and bans a source because of what the application answered — a run of refusals from one address — while the operator's own block list stays exactly as it was.
Blocking is usually manual: a human notices abuse and adds an IP. That never fires at 3am. openwaf turns the block list from a record of past incidents into a live defence, without inventing a rule language nobody will maintain.
.NET 10, YARP reverse proxy, EF Core, one deployable.
The three pillars, and the one place they meet
There is exactly one middleware that may refuse a request
(EdgeGuardMiddleware). Everything else observes. Precedence is a property of
the design, not a side effect of registration order:
| # | Pillar | Answer | Lifetime |
|---|---|---|---|
| 1 | always-pass prefixes — /admin-api, /admin, /healthz, /readyz, /openapi |
pass | the recovery hatch for an operator who blocked themselves |
| 2 | allowlist (address or CIDR, matched on the raw peer address) | pass | wins over everything, including a geo deny |
| 3 | operator block (source=operator) |
301 to RedirectTo, else a honey-pot list |
never expires |
| 4 | engine ban (source=engine) |
403 + Retry-After + a reason |
expires on its own |
| 5 | geo policy (deny list / allow list) | 451 + a note that says the inference is probabilistic | policy, not data |
A second middleware, ResponseObservationMiddleware, sits inside the guard:
it awaits the upstream, classifies the status the application actually returned,
and feeds a streak counter. Being inside the guard is load-bearing — a refusal
the edge generated itself must never feed the streak that produced the ban.
The streak
N consecutive refusals inside a window of M minutes ⇒ ban for
BanDuration. Consecutive means what it says:
- a
2xx/3xxresets the streak to zero; - a gap longer than
Mrestarts it at one; 4xx(default400-499, inclusive of 400) counts toward a ban;5xx(default500-599) never bans — it raises an alert instead, because a broken deploy would otherwise take the site down twice: once by being broken, once by banning its own honest visitors.
The ban takes effect on the request after the one that matured the streak, because the edge decides from the response it has already served.
The reset is done by the observer, not only by the counter: a 2xx/3xx calls
StreakTracker.ResetIfTracked, which costs one dictionary lookup for a source
the map has never seen and no MMDB read for anyone. Before that, the sentence
above was true in the domain object and false on the wire — a visitor
alternating a 404 with a normal page view accumulated refusals across every
honest request and still matured a ban. A_clean_answer_between_refusals_ends_the_run…
in the integration suite is the test for that sentence.
Alerts speak per escalation, not per request
Both alert kinds are edge-triggered: one row when the streak crosses N, then
one more each time the count doubles. Twelve 502s at N=3 cost three rows
(at 3, 6 and 12).
They used to be level-triggered, which meant one alert row per request for as
long as the condition lasted — and neither condition ends on its own. A 5xx
never bans, so the source is observed on every request; in Observe mode
nothing bans at all, so the same is true of a refusal streak. At N=3 a source
hammering a broken upstream for 10,000 requests cost 9,998 rows, 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. The
safest mode was also the cheapest way to grow the operator's tables.
Silencing once was not the fix: an alert that fires once per source per process
and never again hides an outage that got ten times worse while nobody was
looking. So the count keeps escalating, and a gap longer than M or a clean
answer ends the episode, which lets the next outage announce itself again.
A_storm_of_server_errors_alerts_on_the_crossing_and_then_only_as_it_doubles
(9 rows for 1,000 responses) and
A_dry_run_announces_each_candidate_ban_twice_at_most_rather_than_once_per_request
are the tests; both fail with the edge detection removed.
The toggle
Automatic banning is a mode, not a replacement:
| mode | observes | records | blocks |
|---|---|---|---|
Off |
yes | yes | no |
Observe |
yes | yes, as candidate_ban alerts |
no |
Enforce |
yes | yes | yes |
Switching it off touches no rows. DELETE /admin-api/blocks?source=engine
clears engine bans and cannot reach an operator's entries — provenance lives on
the row, so "clear the automatic ones" is a filter, not a table operation.
Quickstart
# tests
dotnet test dotnet/OpenWaf.slnx
# end-to-end against a real upstream, with curl assertions
./scripts/smoke.sh
# the whole thing behind a proxy
OPENWAF_ADMIN_TOKEN=change-me docker compose up --build
# the assertions above, against the built image rather than the source tree:
# image HEALTHCHECK, streak ban over a socket, per-source isolation, operator
# block, allowlist precedence, country deny
OPENWAF_ADMIN_TOKEN=change-me ./scripts/compose-smoke.sh
Point one probe at it and watch the ban:
for i in 1 2 3 4; do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/wp-admin; done
# 404 404 404 403
curl -s -H "X-Admin-Token: change-me" 'http://localhost:8080/admin-api/blocks?source=engine'
Configuration
Everything under OpenWaf:Policy (env: OpenWaf__Policy__…), overridable at
runtime through PUT /admin-api/policy, which persists to policy_settings.
| key | default | meaning |
|---|---|---|
Mode |
Observe |
Off / Observe / Enforce |
StreakThreshold |
10 |
N |
StreakWindow |
00:05:00 |
M — the gap that still counts as one streak |
BanDuration |
01:00:00 |
how long a ban stays live |
RefusalRange |
400-499 |
statuses that count toward a ban |
ServerErrorRange |
500-599 |
statuses that raise an alert |
Geo |
Off |
Off / DenyList / AllowList |
TrustProxyHeaders |
false |
may X-Forwarded-For define the source? |
MaxTrackedSources |
10000 |
hard bound on the in-memory streak map |
Ipv4KeyPrefixLength / Ipv6KeyPrefixLength |
32 / 64 |
source-key granularity |
EngineBlockStatus / OperatorBlockStatus |
403 / 301 |
what a block answers |
DefaultRedirectTargets |
iana example | honey-pot targets for operator blocks |
One key is not policy and cannot be changed at runtime, because it decides how long this process may keep enforcing a list that is already out of date:
| key | default | meaning |
|---|---|---|
OpenWaf:State:RefreshTtlSeconds |
30 |
how stale the in-memory block list may get. On a single edge this is invisible; behind a load balancer it is the propagation delay — 23.7 s measured at ~36 req/s in research/2026-10-01-multi-instance/. Anything outside 1–300 aborts startup: the process exits non-zero and the log names the key. In Docker the container stays Up with nothing listening until the image HEALTHCHECK marks it unhealthy — that is what any startup failure in this image looks like, not a special case. /healthz reports the value an operator actually got, as snapshotTtlSeconds. |
Database: Database:Provider = sqlite (default) or postgres,
ConnectionStrings__OpenWaf. GeoIP: GEOIP_MAXMIND_DB_PATH.
The geo database ages on purpose, and a rebuild does not replace it
The image bakes a dbip-country-lite MMDB pinned by ARG DBIP_VERSION
(currently 2026-10, moved by hand on 2026-10-01). /healthz reports
geoBuiltAt, geoDatabase and geoStale (over 90 days), and /admin-api/geo
reports the age in days.
The 90-day flag is an alarm, not the policy, and the gap is measurable: with the
named volume holding dbip-country-lite-2026-09 while the Dockerfile pinned
2026-10, /healthz said geoBuiltAt: 2026-09-01T01:32:45+00:00 and
geoStale: false, and every geo assertion in the smoke test still passed — the
country deny list still refused 8.8.8.8 with 451. A month behind is a policy
nobody chose, reported as healthy.
Three things close it:
scripts/geo-db-freshness.shcompares the pin with the newest release the vendor actually serves and answers with three codes, not two: 0 current, 1 the vendor has something newer (it prints the bump), 2 could not tell — no network, or a pin the vendor has never served, which would make the image build fail on a 404. "Could not check" is never printed as ok.scripts/geo-db-bump.shrewrites the ARG and prints the two commands that make the new database actually land. It refuses to write anything when the check could not run: a pin moved on the strength of a check that did not run is worse than a pin left alone..github/workflows/geo-freshness.ymlruns the check on the 1st and the 8th, and deliberately does not open a pull request — a bot that cannot run the geo assertions bumping a data dependency is a worse default than a red job.
scripts/compose-smoke.sh asserts the pin against the running container
(the loaded geo database is the pinned one). Its teeth were checked, not
assumed: against the stale volume above it printed Dockerfile pins 2026-10, the container loaded 2026-09 plus the docker volume rm line, 27 passed, 1
failed, and after removing the volume 28 passed, 0 failed.
docker-compose.yml mounts a named volume at /app/geoip so a redeploy does
not re-download 8 MB. Docker seeds a named volume from the image only the first
time the volume is created, so an existing deployment keeps the old database
after a rebuild. Measured on 2026-10-01: the same rebuilt image reported
geoBuiltAt: 2026-09-01 against the existing volume and 2026-10-01 after
docker volume rm openwaf_openwaf-geoip. That is the command to reach for when
the pin moves.
Schema
Migrations are the schema of record for PostgreSQL, which is the provider a real deployment runs:
cd dotnet
dotnet ef migrations add <Name> --project OpenWaf.Infrastructure --startup-project OpenWaf.Infrastructure
A migration set is provider-shaped SQL, so it is not applied to the SQLite
default — there the schema is created from the model at startup. OPENWAF_SCHEMA
overrides the choice: migrate, ensurecreated, or none when an operator
manages the schema themselves.
Admin API
Requires X-Admin-Token (or ?token=). No token configured means the admin
API is closed, not open.
GET /admin-api/blocks?source=operator|engine&live=true
POST /admin-api/blocks {"ip","reason","redirectTo"}
DELETE /admin-api/blocks?source=engine[&key=…]
GET /admin-api/allow POST {"match","note","expiresInMinutes"} DELETE /admin-api/allow/{id}
GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…}
GET /admin-api/observations per-source streaks, durable — the maximum ever seen
GET /admin-api/streaks the streak standing right now, in this process, with the threshold
GET /admin-api/alerts server_error_streak | candidate_ban
GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false
GET /admin-api/countries/summary sources and refusals per country, from the aggregates
GET /admin-api/geo which database is loaded and how old it is
GET /admin-api/state snapshot age, tracked sources, counts
Console
GET /admin serves a single page over those endpoints — mode and snapshot age,
live bans with their reasons, the streak standing in this process right now
(current count against the threshold, not the historical maximum), the sources
being watched, and the countries seen — counted per ISO code, with a bar per
country sized against the busiest one. That bar is the honest limit of the word
"map" here: the admin API exposes counts per country code, not coordinates, and
the runtime image is distroless with no external assets, so there is no world
outline and no tile server. A geographic map would be a decoration this page
could not load at the moment it is wanted.
It also writes, with the two controls an incident actually reaches for: block
one address with a reason, and allowlist an address or CIDR with a note and an
optional expiry (the "my customer is locked out" control — an allow entry
outranks every ban). Each ban row has a delete that removes that row, each allow
row a remove, and each country row a rule toggle. There is no DELETE for a
country rule, so the toggle back is PUT ?allowed=true: the row stays behind
and means "not denied".
The summary line states which geo database this edge is enforcing on, when it was
built and how old it is (marked past the 90-day runtime alarm), and the snapshot
age against the TTL it is measured against — because on a single edge the TTL is
invisible, and behind a load balancer it is the delay a ban has.
It shows the alerts the edge raises — server_error_streak (your upstream is
failing, and the edge will not ban the visitor who saw it) and candidate_ban
(the rule would have banned, but the mode is Observe). That table is the whole
point of the alerting pillar: an alert nobody reads is a log line.
It decides nothing: every control on it is one call to the API above. It is on
the always-pass list, so an operator who is themselves blocked can still reach
the page that clears it, and it is never observed, so fumbling it cannot build a
streak. The token is typed into the page and sent as a header; it is never in a
URL, because a token in a query string ends up in proxy logs and browser
history. No external assets — a page that needs a CDN fails at the moment it is
wanted.
Gates
scripts/ci-gates.sh is the single definition of every gate; the CI workflow
calls the same script one gate per step, so a local green run and a CI green run
cannot mean different things.
scripts/ci-gates.sh all # restore, build, unit, integration, smoke, image, compose-smoke
scripts/ci-gates.sh unit # or any one gate on its own
scripts/ci-gates.sh console # the page, in a real Chromium (not part of `all`)
OPENWAF_ADMIN_TOKEN defaults inside ci-gates.sh to a throwaway for the stack
the gate starts itself and tears down on exit; the standalone scripts still
refuse to invent one, because run by hand they can be pointed at a real
deployment.
The console gate starts the stack, seeds a source sitting at 2 of a threshold of
3 and an operator block with a reason, four 502s from an address chosen for this
run (/boom, see the alerting note above), drives /admin in a real Chromium,
and asserts 33 things. The read side: it authenticated, listed the streak as
current-over-threshold rather than as a historical maximum, listed the operator
block with its reason, listed observations and countries with bars that have
real pixel widths, listed the alert this run's seeding wrote (by source and
count, not just "a row exists"), said in words that a server error is never a
reason to ban, kept the token out of the markup, and threw no javascript.
The write side, checked on the wire and not just in the table: an address
reaches the upstream (404), the page writes a ban for it, the same address is
then refused (301 with the policy's redirect Location — the probe uses
redirect: 'manual', because following it walks out to the public internet and
comes back 200, which is how this assertion first read as a failure while the
edge was refusing the client the whole time), the per-row delete removes that one
ban and the address reaches the upstream again, an allow entry appears with an
expiry and can be removed, and a country rule can be set and put back. The quiet
failure mode is asserted too: typing not-an-ip into the block form has to come
back as the API's own error (not an IP address: not-an-ip) with no new row,
because an operator who believes they blocked an address and did not is worse
than an operator with no console at all. Then the pass repeats at 375 px in dark
mode, where the document must not scroll sideways
and the status line must clear WCAG AA (measured 11.85:1). It needs playwright-core
(PLAYWRIGHT_CORE=/path/to/it) and exits 2 when that is missing — a gate that
reports success having asserted nothing is worse than no gate. Its negative
control (a wrong token) exits 1. SCREENSHOT=console-evidence.png writes the
desktop and phone screenshots the CI job publishes as artifacts.
The same gates on the runner's operating system
Every green number above was produced on darwin; the workflow runs on
ubuntu-latest. scripts/ci-linux-rehearsal.sh runs the gates in containers.
The source gates (restore, build, unit, integration, smoke) run against a copy of
the tree — no .git, no host build output, because Linux binaries landing in a
macOS working tree make the next --no-build try to exec an ELF file — inside
mcr.microsoft.com/dotnet/sdk:10.0. The compose gate runs in docker:cli
against the host daemon, so the image build and the stack are Linux.
Rehearsed 2026-10-01, most recently at the alert-edge commit. Source gates:
Ubuntu 24.04.5, SDK 10.0.401 resolving dotnet/global.json (pinned
10.0.100, rollForward: latestFeature — which is also the answer to
whether setup-dotnet with 10.0.x satisfies the pin), unit 58/58,
integration 32/32, smoke 19/19, first try, nothing to fix. The first
rehearsal of this pipeline timed a cold container and a cold NuGet cache at
1:02.81; the runs after it were not re-timed, so that is the only wall clock
measured here, and the source job's 25-minute timeout is not close either way.
Compose gate on Linux: 43 passed, 0 failed (27 before the geo-pin and
alerting assertions, 41 before the alert-edge ones), enforcement lag 0 ms, 12 ms
and 36 ms in three runs. Console gate on Linux: 33 assertions, 0 failed —
described below. scripts/geo-db-freshness.sh was run
in mcr.microsoft.com/dotnet/sdk:10.0 too: current pin answers 0, and a forced
PIN=2026-05 answers 1 with the bump command, so the gate that decides whether
the geo database is current behaves the same on the runner's OS.
Getting the compose stage green surfaced two things about the harness rather than
the product, both now written into the script. The gate asserts over JSON with
python3: a bare container failed 23 of 27 assertions for nothing else. And
the stack the host daemon publishes lives in the host's network namespace, so
without EDGE=http://host.docker.internal:8080 every HTTP assertion returns curl
code 000 while the image's own HEALTHCHECK says healthy — a green stack with
red assertions, the most confusing failure this gate can produce.
The console gate needs a real Chromium, so it runs in
mcr.microsoft.com/playwright:v1.63.0-noble: scripts/console-smoke.sh with
SEED_ONLY=1 starts and seeds the stack from docker:cli, the browser image
drives scripts/console-check.cjs against EDGE=http://host.docker.internal:8080,
and the stack is torn down afterwards. That image ships the browsers but not the
npm package, so the script installs playwright-core into /tmp and points
PLAYWRIGHT_CORE at it, mounting the repository read-only so the install never
lands in the working tree. Rehearsed the same day on Linux 7.0.12-linuxkit
aarch64, node v24.20.0, chromium-1243: 33 assertions, 0 failed, including
the round-trip the page alone cannot fake — a ban drawn on the page answers 301
on the next request from that address. All three scenes in one cold run:
2:14.33.
Honest status of the workflow itself: it has never executed on a runner, because the repository has no remote. Everything above was run on a laptop, on the commit that claims it.
What this deliberately costs
Stated, because a defence that hides its failure modes is not a defence.
- One shared IPv4 egress is one source. An office behind one address can accumulate a ban. Mitigations: the streak is consecutive (one honest click resets it), the allowlist outranks every pillar, and the ban explains itself so an operator can undo it in one call.
- IPv6 is grouped to
/64. A subscriber holds a whole/64, so a bot rotating addresses inside one allocation is one source; a per-address v6 rule is unenforceable. A wider prefix over-blocks, which is worse. - Geo is a probabilistic claim about an address, not a fact about a person.
The 451 body says so. The database is pinned by a build argument and ages with
the image, so
/healthzreports its build date andgeoStale. - Streak state is per process, and that is measured, not assumed. Round-robin
over two edges multiplies the effective threshold by the instance count: four
refusals from one address, two per edge, at a threshold of 3, produced no ban
at all. A block issued by one edge is enforced by the other after up to
OpenWaf:State:RefreshTtlSeconds(23.7 s measured at ~36 req/s). The block list is already shared through the database; the streak map is not. Numbers, method and caveats:research/2026-10-01-multi-instance/RESULTS.md. - Aggregates, not a request log.
source_observationskeeps counters and the last-seen evidence per source, and ages out afterObservationRetention. Raw IPs are not logged.
Shape
dotnet/
OpenWaf.Domain/ pure decision core: source key, streak, ordered decision
OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo
OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode
OpenWaf.Tests.Unit/ 54 tests over the decision logic
OpenWaf.Tests.Integration/ 30 tests driving the real pipeline against a fake upstream
scripts/smoke.sh 19 assertions against a running edge + a real upstream
scripts/compose-smoke.sh 41 assertions against the built image (compose + nginx)
scripts/console-check.cjs 33 assertions against the page, in a real Chromium
scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2)
.github/workflows/ci.yml runs the gates on every push
.github/workflows/geo-freshness.yml the same check on a schedule
docs/ARCHITECTURE.md the design authority and its rulings
Two protections are inherited from the reference deployment rather than rediscovered, and both are load-bearing: at most one durable write per source per 30 s, and a hard LRU bound on the in-memory map, so a scanner farm cannot grow the process or tax the database.