commit a3d0777492e55610fe094cb33dda9eb552417bff Author: Pavlo Ratushnyi Date: Thu Oct 1 02:13:01 2026 +0200 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/. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b4a9f65 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.git +.github +.dev-data +research +docs +scripts +dotnet/**/bin +dotnet/**/obj +*.db +*.db-shm +*.db-wal diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbb3d47 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +bin/ +obj/ +*.user +.vs/ +.idea/ +.dev-data/ +*.db +*.db-shm +*.db-wal +geoip/*.mmdb +TestResults/ +publish/ + +# local run artefacts +openwaf.db* +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b751e79 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,83 @@ +# syntax=docker/dockerfile:1.7 +# +# openwaf edge — framework-dependent publish on a chiseled distroless runtime. +# +# Why not NativeAOT: the reference deployment (~/work/neemle/landing) tried it +# and recorded the reason in its Dockerfile — EF Core under AOT needs every LINQ +# query precompiled and every request/response shape annotated, and the size win +# washes out against the chiseled runtime base. Not relitigated here. +# +# Stages: +# 1. restore – NuGet layer, cached independently of source changes +# 2. build – framework-dependent publish, debug artefacts stripped +# 3. runtime – mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled, no shell +# +# HEALTHCHECK re-executes the binary in --healthcheck mode: a chiseled base has +# no shell, no wget and no curl, so the binary is the only probe available. + +ARG DOTNET_VERSION=10.0 + +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS restore +WORKDIR /src +COPY dotnet/global.json dotnet/Directory.Build.props dotnet/NuGet.Config dotnet/OpenWaf.slnx ./ +COPY dotnet/OpenWaf.Domain/OpenWaf.Domain.csproj OpenWaf.Domain/ +COPY dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj OpenWaf.Infrastructure/ +COPY dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj OpenWaf.Edge/ +COPY dotnet/OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj OpenWaf.Tests.Unit/ +COPY dotnet/OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj OpenWaf.Tests.Integration/ +RUN dotnet restore OpenWaf.Edge/OpenWaf.Edge.csproj + +FROM restore AS build +COPY dotnet/ ./ +RUN dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj \ + -c Release \ + -p:DebugType=none \ + -p:DebugSymbols=false \ + -o /publish/api \ + && cd /publish/api \ + && rm -f *.pdb \ + && rm -rf BuildHost-net472 BuildHost-netcore + +# Stage the volume mount points with app:app ownership — a chiseled image has +# no shell, so there is no mkdir at runtime. +RUN mkdir -p /publish/data /publish/geoip + +# GeoIP: dbip-city-lite, free and redistributable, same MMDB binary format as +# MaxMind. Kept under the legacy GeoLite2-Country.mmdb name so one env var +# covers both, and the reader sniffs Metadata.DatabaseType rather than trusting +# the filename — a city database stored under a country name is exactly the +# trap the reference repo documented. +# +# DBIP_VERSION is pinned, which means the database ages with the image. /healthz +# reports the loaded database's build date so a stale one is visible at runtime, +# not only at build time; bump this argument in CI on a schedule. +ARG DBIP_VERSION=2026-04 +RUN apt-get update -qq && apt-get install -qq -y curl gzip > /dev/null && \ + mkdir -p /publish/geoip && \ + curl -fsSL "https://download.db-ip.com/free/dbip-city-lite-${DBIP_VERSION}.mmdb.gz" \ + | gunzip > /publish/geoip/GeoLite2-Country.mmdb && \ + ls -la /publish/geoip/GeoLite2-Country.mmdb + +FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION}-noble-chiseled AS runtime + +# Chiseled ships a non-root `app` user (UID 1654) and no shell. +WORKDIR /app/api +COPY --from=build --chown=app:app /publish/api /app/api +COPY --from=build --chown=app:app /publish/data /app/data +COPY --from=build --chown=app:app /publish/geoip /app/geoip + +USER app:app + +ENV ASPNETCORE_URLS=http://+:8080 \ + ASPNETCORE_FORWARDEDHEADERS_ENABLED=false \ + ConnectionStrings__OpenWaf="Data Source=/app/data/openwaf.db" \ + Database__Provider=sqlite \ + GEOIP_MAXMIND_DB_PATH=/app/geoip/GeoLite2-Country.mmdb \ + HEALTHCHECK_PORT=8080 + +EXPOSE 8080 + +HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \ + CMD ["dotnet", "/app/api/OpenWaf.Edge.dll", "--healthcheck"] + +ENTRYPOINT ["dotnet", "/app/api/OpenWaf.Edge.dll"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..d40771d --- /dev/null +++ b/README.md @@ -0,0 +1,166 @@ +# 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`/`3xx` resets the streak to zero; +* a gap longer than `M` restarts it at one; +* `4xx` (default `400-499`, inclusive of 400) counts toward a ban; +* `5xx` (default `500-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 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 + +```bash +# 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 +``` + +Point one probe at it and watch the ban: + +```bash +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 | + +Database: `Database:Provider` = `sqlite` (default) or `postgres`, +`ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. + +## 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 +GET /admin-api/alerts server_error_streak | candidate_ban +GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false +GET /admin-api/geo which database is loaded and how old it is +GET /admin-api/state snapshot age, tracked sources, counts +``` + +## 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 `/healthz` reports its build date and `geoStale`. +* **Streak state is per process.** Behind a load balancer, each instance counts + its own traffic. Multi-instance deployments need a shared store — recorded as + an evolution trigger, not solved by pretending. +* **Aggregates, not a request log.** `source_observations` keeps counters and + the last-seen evidence per source, and ages out after `ObservationRetention`. + 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/ 36 tests over the decision logic + OpenWaf.Tests.Integration/ 14 tests driving the real pipeline against a fake upstream +scripts/smoke.sh 19 assertions against a running edge + a real upstream +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. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..89e79ef --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,39 @@ +# The edge in front of an application it knows nothing about. That is the +# point: openwaf decides on what the upstream answered, so the upstream can be +# anything. `upstream` here is nginx purely so the compose file demonstrates a +# ban with nothing but curl. +# +# Before starting: set OPENWAF_ADMIN_TOKEN. Without it the admin API is closed +# (404), which is the safe default, not a misconfiguration. +services: + edge: + build: + context: . + dockerfile: Dockerfile + ports: + - "8080:8080" + environment: + OPENWAF_ADMIN_TOKEN: ${OPENWAF_ADMIN_TOKEN:?set OPENWAF_ADMIN_TOKEN before starting} + OpenWaf__Policy__Mode: Enforce + OpenWaf__Policy__StreakThreshold: "10" + OpenWaf__Policy__StreakWindow: "00:05:00" + OpenWaf__Policy__BanDuration: "01:00:00" + # Only turn this on when the edge sits behind a proxy you control and + # whose address you have allowlisted. If X-Forwarded-For is + # attacker-controlled, every request gets a fresh source key and no + # streak ever matures. + OpenWaf__Policy__TrustProxyHeaders: "false" + ReverseProxy__Clusters__upstream__Destinations__upstream1__Address: "http://upstream:80/" + volumes: + - openwaf-data:/app/data + - openwaf-geoip:/app/geoip + depends_on: + - upstream + + upstream: + image: nginx:alpine + restart: unless-stopped + +volumes: + openwaf-data: + openwaf-geoip: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..135bde6 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,93 @@ +# Architecture — openwaf + +Canonical record: Lease Vibe work item **OPEN-2**, `architecture_decision` +`4c9de3f6-ca26-4020-a16b-8f21e316c936` (v1, authored under a live claim). This +file is the repository-side copy; the tracker holds the versioned authority and +its audit history. Scope carried over from **OPEN-1** (Canceled 2026-08-12), +whose BA analysis this builds on rather than repeats. + +## Decision + +One decision point, three pillars, provenance-carrying blocks. + +`EdgeGuardMiddleware` is the only component allowed to short-circuit. It reads +an immutable in-memory snapshot and evaluates, in a fixed order: + +``` +always-pass prefixes → allowlist → operator block → engine ban → geo policy +``` + +`ResponseObservationMiddleware` runs inside the guard, awaits the upstream, +classifies the status, and is the only thing that can create an engine ban. + +### Rulings on the open questions OPEN-1 left + +| Q | Ruling | Why | +|---|--------|-----| +| Q1 — does M bound the streak or the ban? | **Both, as two parameters.** `StreakWindow` bounds the streak; `BanDuration` is separate. | "N раз підряд на M хвилин" reads both ways; dropping one loses a knob the operator needs. | +| Q2 — `> 400` or `>= 400`? | **Inclusive of 400** (`400-499`). | A malformed-body probe answers 400 and must count. | +| Q3 — do 5xx count? | **Never a ban; always an alert.** | A broken deploy makes every honest client draw consecutive 5xx; the first bad release would ban the site's own visitors. | +| Q4 — what is the source key? | **Normalised IP**: IPv4 as-is, IPv6 grouped to `/64`, IPv4-mapped v6 collapsed. Allowlist matches the raw address instead. | A bot rotating inside one v6 allocation is one source; an operator writing a CIDR should mean exactly that. | +| Q5 — one block table or two? | **One table, `Source` provenance column.** | Manual and automatic coexist permanently; clearing one kind must never touch the other, and the admin UI should not have to know about two tables. | +| Q6 — does the 301 survive for automatic bans? | **No: engine bans answer 403 + `Retry-After`; operator blocks keep 301.** A per-entry `RedirectTo` overrides both. | A 301 is a good answer to a scanner and a baffling one to a customer whose office IP was caught. | +| Q7 — allowlist and override | **Allowlist outranks every pillar and survives the toggle; the always-pass prefixes are the self-recovery hatch.** | A ban with no exemption path eventually blocks someone who matters at the worst moment. | +| Q8 — retention | **Aggregates only, aged out by a worker** (`ObservationRetention`, `BanRetention`). | The reference repo left raw-IP TTL unresolved; storing no request log makes the question smaller. | + +### Why not the alternatives + +* **Three independent middlewares** (what the reference repo does today): + precedence becomes registration order, and an allowlisted operator in a + denied country gets whichever guard runs first. +* **Two block tables**: makes "clear engine bans" a table operation and invites + a future merge that loses data. +* **NativeAOT**: rejected in the reference and recorded there; not relitigated. +* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that + varies its UA multiplies into many sources and never reaches the threshold. +* **Banning on 5xx because the original wording said `> 400`**: turns an outage + into a second, self-inflicted outage. + +## Properties the tests hold + +* A ban never feeds its own streak — the guard refuses before the observer runs. +* The admin surface is never observed either: an operator's syntax error in an + admin call must not lock them out. +* Memory is bounded (`MaxTrackedSources`, LRU + idle TTL); the request path + never touches the database; a stale snapshot is served while one background + refresh runs; a failed refresh keeps the previous snapshot (fail closed for + blocks, fail open for geo). +* Durable writes are coalesced to one per source per `ObservationWriteInterval`. +* Ban writes are serialised in-process: the observer runs after the response is + written, so the next request can arrive while the ban is still landing. + +## What building it taught us about the design + +Recorded because they are the places a reader will otherwise step in again. + +1. **`ctx.RequestAborted` is the wrong token for post-response work.** The ban + write was silently cancelled: the client had already hung up, so the request + that *proved* the source abusive was the one that failed to record it. +2. **SQLite cannot compare a `DateTimeOffset`** — the provider stores it as text + and refuses the query at translation time, which kills every "is this ban + still live" and "has this row aged out" predicate. Timestamps are stored as + integers on SQLite and stay `timestamptz` on PostgreSQL. +3. **CIDR masking order matters.** Masking the partial octet after zeroing the + rest silently widens the prefix (`198.51.100.24/19` became `198.51.0.0`). + Caught by a unit test, not by review. +4. **An empty string in `appsettings.json` defeats the environment fallback** + (`??` does not fire on `""`), which is how a geo database and an admin token + go missing in a deployment that looks configured. +5. **The configuration binder appends to a collection default** rather than + replacing it, so a non-empty default produced a duplicated redirect target. +6. **Two requests finishing together both saw "no ban yet"** and raced into the + unique index; the loser's evidence was lost. Now serialised behind a gate. + +## Evolution triggers + +1. A shared-egress IPv4 (carrier NAT, office, campus) banned by honest traffic + → the per-address v4 key is wrong and keying must move to session or + connection. +2. Geo enforced on a stale MMDB → staleness must become an operational alarm, + not a `/healthz` field. +3. Multi-instance edge → the in-memory streak map must move to a shared store. +4. A need for a raw request log → the GDPR question the reference repo never + closed comes back with sharper edges. diff --git a/dotnet/Directory.Build.props b/dotnet/Directory.Build.props new file mode 100644 index 0000000..0a22f1c --- /dev/null +++ b/dotnet/Directory.Build.props @@ -0,0 +1,14 @@ + + + net10.0 + 14 + enable + enable + true + latest + false + true + en + false + + diff --git a/dotnet/NuGet.Config b/dotnet/NuGet.Config new file mode 100644 index 0000000..4d736c1 --- /dev/null +++ b/dotnet/NuGet.Config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs new file mode 100644 index 0000000..aa65ab3 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs @@ -0,0 +1,112 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// The single ordered decision point (architecture decision, OPEN-2). +/// +/// Order is a documented property, not a side effect of middleware +/// registration: +/// 1. always-pass prefixes — an operator who blocked their own address must +/// still be able to reach the admin API and undo it; +/// 2. allowlist — the exemption path, evaluated on the raw +/// address so a CIDR means what the operator wrote; +/// 3. operator block — the human's list, which the toggle cannot +/// switch off; +/// 4. engine ban — enforced only in ; +/// 5. geo policy — last, so an allowlisted operator inside a +/// denied country gets one defined answer: through. +/// +/// Pure function over an . No I/O, no clock of its +/// own — now is passed in, which is what makes the expiry and streak +/// rules testable without waiting. +/// +public static class DecisionEngine +{ + public static EdgeDecision Decide( + EdgeSnapshot snapshot, + string? clientIp, + string path, + DateTimeOffset now, + string? countryCode = null) + { + var policy = snapshot.Policy; + + if (IsAlwaysPass(path, policy)) return new EdgeDecision(EdgeVerdict.PassBypassed); + + if (string.IsNullOrWhiteSpace(clientIp)) return EdgeDecision.Pass; + + foreach (var entry in snapshot.AllowEntries) + { + if (!entry.IsLive(now)) continue; + if (NetworkMatch.Matches(clientIp, entry.Match)) + { + return new EdgeDecision(EdgeVerdict.PassAllowlisted, Reason: entry.Note); + } + } + + var key = SourceKey.For(clientIp, policy); + if (key.Length == 0) return EdgeDecision.Pass; + + if (snapshot.OperatorBlocks.TryGetValue(key, out var manual) && manual.IsLive(now)) + { + var (status, location) = BlockResponse(policy, manual.RedirectTo, policy.OperatorBlockStatus); + return new EdgeDecision(EdgeVerdict.BlockOperator, status, location, manual.Reason, key, manual.ExpiresAt); + } + + if (policy.Mode == EnforcementMode.Enforce + && snapshot.EngineBans.TryGetValue(key, out var ban) && ban.IsLive(now)) + { + var (status, location) = BlockResponse(policy, ban.RedirectTo, policy.EngineBlockStatus); + return new EdgeDecision(EdgeVerdict.BlockEngine, status, location, ban.Reason, key, ban.ExpiresAt); + } + + if (policy.Geo != GeoMode.Off && !string.IsNullOrWhiteSpace(countryCode)) + { + var code = countryCode.Trim().ToUpperInvariant(); + snapshot.Countries.TryGetValue(code, out var rule); + var denied = policy.Geo switch + { + GeoMode.DenyList => rule is { IsAllowed: false }, + GeoMode.AllowList => rule is not { IsAllowed: true }, + _ => false + }; + if (denied) + { + return new EdgeDecision(EdgeVerdict.GeoReject, 451, Reason: $"country_{(policy.Geo == GeoMode.DenyList ? "denied" : "not_allowed")}_{code}", SourceKey: key); + } + } + + return EdgeDecision.Pass; + } + + /// Q6: a per-entry redirect overrides the kind's default. The + /// engine never sets one, so an engine ban stays a 403 an honest visitor + /// can read, while an operator can still send a scanner elsewhere. + private static (int Status, string? Location) BlockResponse(EdgePolicy policy, string? redirectTo, int defaultStatus) + { + if (!string.IsNullOrWhiteSpace(redirectTo)) return (301, redirectTo); + if (defaultStatus == 301) + { + var targets = policy.DefaultRedirectTargets; + var target = targets.Count == 0 + ? "https://www.iana.org/help/example-domains" + : targets.Count == 1 ? targets[0] : targets[Random.Shared.Next(targets.Count)]; + return (301, target); + } + return (defaultStatus, null); + } + + public static bool IsAlwaysPass(string path, EdgePolicy policy) + { + foreach (var prefix in policy.AlwaysPassPrefixes) + { + if (path.Equals(prefix, StringComparison.OrdinalIgnoreCase) + || path.StartsWith(prefix + "/", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } +} diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs new file mode 100644 index 0000000..fc8df55 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs @@ -0,0 +1,17 @@ +namespace OpenWaf.Domain.Engine; + +/// The decision plus everything the response writer and the log need +/// to explain it. An engine block always carries its reason and expiry: a ban +/// nobody can explain is a ban nobody can defend. +public sealed record EdgeDecision( + EdgeVerdict Verdict, + int StatusCode = 0, + string? Location = null, + string? Reason = null, + string? SourceKey = null, + DateTimeOffset? ExpiresAt = null) +{ + public bool IsBlocked => Verdict is EdgeVerdict.BlockOperator or EdgeVerdict.BlockEngine or EdgeVerdict.GeoReject; + + public static readonly EdgeDecision Pass = new(EdgeVerdict.Pass); +} diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs new file mode 100644 index 0000000..57ea6f8 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs @@ -0,0 +1,29 @@ +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Domain.Engine; + +/// +/// The immutable state the decision point reads. Built off the request path +/// on a TTL and swapped atomically, so a request never touches the database. +/// +/// Blocks are split by provenance rather than by table: the two kinds are +/// looked up in a fixed order and a clear operation must be able to name one +/// kind without touching the other. +/// +public sealed record EdgeSnapshot +{ + public required DateTimeOffset GeneratedAt { get; init; } + public required EdgePolicy Policy { get; init; } + + public IReadOnlyDictionary OperatorBlocks { get; init; } + = new Dictionary(StringComparer.Ordinal); + public IReadOnlyDictionary EngineBans { get; init; } + = new Dictionary(StringComparer.Ordinal); + public IReadOnlyList AllowEntries { get; init; } = []; + public IReadOnlyDictionary Countries { get; init; } + = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public static EdgeSnapshot Empty(EdgePolicy policy) + => new() { GeneratedAt = DateTimeOffset.MinValue, Policy = policy }; +} diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs new file mode 100644 index 0000000..85a6a29 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs @@ -0,0 +1,17 @@ +namespace OpenWaf.Domain.Engine; + +/// The one answer the edge gives a request. There is exactly one +/// place in the pipeline that may produce a non-Pass value. +public enum EdgeVerdict +{ + Pass = 0, + /// Passed because the operator allowlisted the address. Wins over + /// every other pillar, including a geo deny. + PassAllowlisted = 1, + /// Passed because the path is an always-pass prefix (admin API, + /// health probes) — the recovery hatch for a self-blocked operator. + PassBypassed = 2, + BlockOperator = 3, + BlockEngine = 4, + GeoReject = 5 +} diff --git a/dotnet/OpenWaf.Domain/Engine/NetworkMatch.cs b/dotnet/OpenWaf.Domain/Engine/NetworkMatch.cs new file mode 100644 index 0000000..0a7e682 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/NetworkMatch.cs @@ -0,0 +1,51 @@ +using System.Net; +using System.Net.Sockets; + +namespace OpenWaf.Domain.Engine; + +/// +/// CIDR / address matching for the allowlist. The allowlist is evaluated +/// against the raw peer address rather than the normalised source key, so an +/// operator can write "198.51.100.0/24" and mean exactly that, without having +/// to know the engine's key granularity. +/// +public static class NetworkMatch +{ + public static bool Matches(string? address, string match) + { + if (string.IsNullOrWhiteSpace(address) || string.IsNullOrWhiteSpace(match)) return false; + + var slash = match.IndexOf('/'); + if (slash < 0) + { + return SourceKey.TryParse(address, out _, out var a) + && SourceKey.TryParse(match, out _, out var b) + && a.Equals(b); + } + + var networkPart = match[..slash]; + if (!SourceKey.TryParse(address, out _, out var addr)) return false; + if (!IPAddress.TryParse(networkPart.Trim(), out var network)) return false; + if (!int.TryParse(match[(slash + 1)..].Trim(), out var prefix)) return false; + + if (addr.AddressFamily != network.AddressFamily) + { + // A v6 address written in mapped form against a v4 rule (and the + // reverse) is a common operator typo; compare the mapped forms. + if (addr.IsIPv4MappedToIPv6 && network.AddressFamily == AddressFamily.InterNetwork) + addr = addr.MapToIPv4(); + else if (network.IsIPv4MappedToIPv6 && addr.AddressFamily == AddressFamily.InterNetwork) + network = network.MapToIPv4(); + else + return false; + } + + if (prefix < 0) return false; + var max = addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128; + if (prefix > max) return false; + + var masked = SourceKey.Mask(network, prefix); + var addrMasked = SourceKey.Mask(addr, prefix); + return masked.Equals(addrMasked); + } +} diff --git a/dotnet/OpenWaf.Domain/Engine/RequestEvidence.cs b/dotnet/OpenWaf.Domain/Engine/RequestEvidence.cs new file mode 100644 index 0000000..0144c27 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/RequestEvidence.cs @@ -0,0 +1,10 @@ +namespace OpenWaf.Domain.Engine; + +/// What the edge remembers about the request that produced a +/// response. Truncated by the caller — these strings come from the wire. +public readonly record struct RequestEvidence( + string? Path, + string? UserAgent, + string? CountryCode, + string? City, + string? Region); diff --git a/dotnet/OpenWaf.Domain/Engine/ResponseClass.cs b/dotnet/OpenWaf.Domain/Engine/ResponseClass.cs new file mode 100644 index 0000000..84e19df --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/ResponseClass.cs @@ -0,0 +1,14 @@ +namespace OpenWaf.Domain.Engine; + +/// What the upstream's answer means for the streak engine. +public enum ResponseClass +{ + /// Neither a refusal nor a server error (2xx, 3xx) — resets a streak. + Neutral = 0, + + /// A refusal (4xx by default). Counts toward a ban. + Refusal = 1, + + /// A server error (5xx by default). Counts toward an alert only. + ServerError = 2 +} diff --git a/dotnet/OpenWaf.Domain/Engine/ResponseClassifier.cs b/dotnet/OpenWaf.Domain/Engine/ResponseClassifier.cs new file mode 100644 index 0000000..6ea5cef --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/ResponseClassifier.cs @@ -0,0 +1,19 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// Maps an upstream status code to a . +/// Q2 settled: the refusal range is inclusive at 400, so a malformed-body +/// probe counts. Q3 settled: the 5xx range is classified separately and the +/// decision point never bans on it. +/// +public static class ResponseClassifier +{ + public static ResponseClass Classify(int statusCode, EdgePolicy policy) + { + if (policy.RefusalRange.Contains(statusCode)) return ResponseClass.Refusal; + if (policy.ServerErrorRange.Contains(statusCode)) return ResponseClass.ServerError; + return ResponseClass.Neutral; + } +} diff --git a/dotnet/OpenWaf.Domain/Engine/SourceKey.cs b/dotnet/OpenWaf.Domain/Engine/SourceKey.cs new file mode 100644 index 0000000..653cb64 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/SourceKey.cs @@ -0,0 +1,85 @@ +using System.Net; +using System.Net.Sockets; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// The identity a streak and a ban are keyed on (Q4). +/// +/// IPv4 is used as-is by default: one address is one source. IPv6 is grouped +/// to its /64 — a subscriber is handed a whole /64 and a bot rotating +/// addresses inside one allocation is still one source, which is the only way +/// a v6 streak rule means anything. +/// +/// The known cost is stated rather than hidden: a shared-egress office behind +/// one IPv4 is one source, so ten honest people browsing a broken page can +/// add up to one ban. That is why the streak threshold counts *consecutive* +/// refusals (an honest click resets it) and why the allowlist outranks every +/// pillar. +/// +public static class SourceKey +{ + public static string For(IPAddress? address, EdgePolicy policy) + => address is null ? string.Empty : For(address.ToString(), policy); + + public static string For(string address, EdgePolicy policy) + { + if (!TryParse(address, out var ip, out var mapped)) return Invalid(address); + return KeyFor(mapped, policy); + } + + /// Normalise an address string, resolving IPv4-mapped IPv6 + /// (::ffff:203.0.113.7) to the v4 form so the same host never appears as + /// two sources. + public static bool TryParse(string? address, out IPAddress raw, out IPAddress normalized) + { + raw = IPAddress.None; + normalized = IPAddress.None; + if (string.IsNullOrWhiteSpace(address)) return false; + if (!IPAddress.TryParse(address.Trim(), out var parsed)) return false; + raw = parsed; + normalized = parsed.AddressFamily == AddressFamily.InterNetworkV6 && parsed.IsIPv4MappedToIPv6 + ? parsed.MapToIPv4() + : parsed; + return true; + } + + private static string KeyFor(IPAddress ip, EdgePolicy policy) + { + var prefix = ip.AddressFamily == AddressFamily.InterNetwork + ? Clamp(policy.Ipv4KeyPrefixLength, 0, 32) + : Clamp(policy.Ipv6KeyPrefixLength, 0, 128); + + if (prefix == (ip.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)) + { + return ip.ToString(); + } + + var masked = Mask(ip, prefix); + return prefix == 0 ? "*" : $"{masked}/{prefix}"; + } + + public static IPAddress Mask(IPAddress ip, int prefixLength) + { + var bytes = ip.GetAddressBytes(); + var bits = bytes.Length * 8; + var p = Clamp(prefixLength, 0, bits); + + // The partial octet has to be masked before the octets after it are + // zeroed, or the mask lands on a byte that is already zero and the + // prefix silently widens (198.51.100.24/19 would become 198.51.0.0). + var firstZeroed = p / 8; + if (p % 8 != 0) + { + bytes[firstZeroed] &= (byte)(0xFF << (8 - (p % 8))); + firstZeroed++; + } + for (var i = firstZeroed; i < bytes.Length; i++) bytes[i] = 0; + return new IPAddress(bytes); + } + + private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v); + + private static string Invalid(string address) => $"invalid:{address}"; +} diff --git a/dotnet/OpenWaf.Domain/Engine/StreakOutcome.cs b/dotnet/OpenWaf.Domain/Engine/StreakOutcome.cs new file mode 100644 index 0000000..059f95d --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/StreakOutcome.cs @@ -0,0 +1,11 @@ +namespace OpenWaf.Domain.Engine; + +/// What one observed response produced. +public readonly record struct StreakOutcome( + int ConsecutiveRefusals, + int ConsecutiveServerErrors, + bool BanTriggered, + bool AlertTriggered) +{ + public static readonly StreakOutcome None = new(0, 0, false, false); +} diff --git a/dotnet/OpenWaf.Domain/Engine/StreakSnapshot.cs b/dotnet/OpenWaf.Domain/Engine/StreakSnapshot.cs new file mode 100644 index 0000000..ae0e3c6 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/StreakSnapshot.cs @@ -0,0 +1,16 @@ +namespace OpenWaf.Domain.Engine; + +/// Immutable copy of a source's streak state, handed to the durable +/// writer and to the admin surface. Never a live . +public sealed record StreakSnapshot( + string SourceKey, + int MaxConsecutiveRefusals, + int TotalRefusals, + int MaxConsecutiveServerErrors, + int? LastStatusCode, + string? LastPath, + string? LastUserAgent, + string? LastCountryCode, + string? LastCity, + string? LastRegion, + DateTimeOffset LastSeenAt); diff --git a/dotnet/OpenWaf.Domain/Engine/StreakState.cs b/dotnet/OpenWaf.Domain/Engine/StreakState.cs new file mode 100644 index 0000000..ba80436 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/StreakState.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; + +namespace OpenWaf.Domain.Engine; + +/// +/// Live in-memory state for one source. Mutable and lock-guarded on purpose: +/// this object is touched on every response, so it must not allocate a fresh +/// record per request. +/// +public sealed class StreakState +{ + public required string SourceKey { get; init; } + + public int ConsecutiveRefusals; + public int MaxConsecutiveRefusals; + public int TotalRefusals; + public int ConsecutiveServerErrors; + public int MaxConsecutiveServerErrors; + + public DateTimeOffset? LastRefusalAt; + public DateTimeOffset LastSeenAt; + public int? LastStatusCode; + public string? LastPath; + public string? LastUserAgent; + public string? LastCountryCode; + public string? LastCity; + public string? LastRegion; + + /// Position in the LRU list, so eviction is O(1) and a touch is + /// O(1). Null once the state has been evicted. + public LinkedListNode? LruNode; + + public bool HasEvidence => TotalRefusals > 0 || MaxConsecutiveServerErrors > 0; + + public void Apply(RequestEvidence evidence) + { + if (evidence.Path is not null) LastPath = evidence.Path; + if (evidence.UserAgent is not null) LastUserAgent = evidence.UserAgent; + if (evidence.CountryCode is not null) LastCountryCode = evidence.CountryCode; + if (evidence.City is not null) LastCity = evidence.City; + if (evidence.Region is not null) LastRegion = evidence.Region; + } +} diff --git a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs new file mode 100644 index 0000000..de03cdc --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs @@ -0,0 +1,200 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// The consecutive-streak counter. This is the piece the reference repo +/// already paid for twice over — SuspiciousHitTrackerMiddleware solved +/// write amplification and unbounded memory for a single status code; this +/// generalises the predicate and adds the streak, keeping both protections. +/// +/// Two protections, both load-bearing: +/// * Bounded memory. At most +/// sources are held; the least-recently-touched are evicted. Idle states +/// age out on their own. +/// * No DB on the request path. The tracker is in-memory only; a +/// background writer persists a coalesced snapshot at most once per source +/// per . +/// +/// Streak semantics (Q1): a refusal counts toward the current streak only if +/// it lands within of the previous +/// refusal; otherwise the streak restarts at 1. A neutral response (2xx/3xx) +/// resets the refusal streak to zero — that is what "підряд" means, and it is +/// what keeps a shared-egress office from accumulating a ban across a whole +/// working day. +/// +public sealed class StreakTracker +{ + private readonly object _gate = new(); + private readonly Dictionary _states = new(StringComparer.Ordinal); + private readonly LinkedList _lru = new(); + + public StreakOutcome Observe( + string sourceKey, + int statusCode, + ResponseClass responseClass, + EdgePolicy policy, + DateTimeOffset now, + RequestEvidence? evidence = null) + { + if (string.IsNullOrEmpty(sourceKey)) return StreakOutcome.None; + + lock (_gate) + { + var state = GetOrCreate(sourceKey, now); + Touch(state); + state.LastSeenAt = now; + state.LastStatusCode = statusCode; + if (evidence is not null) state.Apply(evidence.Value); + + switch (responseClass) + { + case ResponseClass.Refusal: + var withinWindow = state.LastRefusalAt is not null + && now - state.LastRefusalAt.Value <= policy.StreakWindow; + state.ConsecutiveRefusals = withinWindow ? state.ConsecutiveRefusals + 1 : 1; + state.LastRefusalAt = now; + state.TotalRefusals++; + if (state.ConsecutiveRefusals > state.MaxConsecutiveRefusals) + state.MaxConsecutiveRefusals = state.ConsecutiveRefusals; + state.ConsecutiveServerErrors = 0; + break; + + case ResponseClass.ServerError: + var withinErrorWindow = state.LastRefusalAt is not null + && now - state.LastRefusalAt.Value <= policy.StreakWindow; + state.ConsecutiveServerErrors = withinErrorWindow ? state.ConsecutiveServerErrors + 1 : 1; + state.LastRefusalAt = now; + if (state.ConsecutiveServerErrors > state.MaxConsecutiveServerErrors) + state.MaxConsecutiveServerErrors = state.ConsecutiveServerErrors; + // A server error is not a clean answer either, so it does + // not reset the refusal streak; it just does not extend it. + break; + + default: + state.ConsecutiveRefusals = 0; + state.ConsecutiveServerErrors = 0; + break; + } + + var ban = responseClass == ResponseClass.Refusal + && state.ConsecutiveRefusals >= policy.StreakThreshold; + var alert = responseClass == ResponseClass.ServerError + && state.ConsecutiveServerErrors >= policy.StreakThreshold; + + return new StreakOutcome(state.ConsecutiveRefusals, state.ConsecutiveServerErrors, ban, alert); + } + } + + /// Snapshot for the durable writer. Copies rather than hands out + /// live objects, so the writer never reads half-updated state. + public IReadOnlyList Snapshot(DateTimeOffset now, EdgePolicy policy) + { + lock (_gate) + { + EvictIdle(now, policy); + var list = new List(_states.Count); + foreach (var s in _states.Values) + { + if (s.HasEvidence) list.Add(s); + } + return list.Select(s => new StreakSnapshot( + s.SourceKey, + s.MaxConsecutiveRefusals, + s.TotalRefusals, + s.MaxConsecutiveServerErrors, + s.LastStatusCode, + s.LastPath, + s.LastUserAgent, + s.LastCountryCode, + s.LastCity, + s.LastRegion, + s.LastSeenAt)).ToList(); + } + } + + public StreakSnapshot? Peek(string sourceKey) + { + lock (_gate) + { + if (!_states.TryGetValue(sourceKey, out var s)) return null; + return new StreakSnapshot( + s.SourceKey, s.MaxConsecutiveRefusals, s.TotalRefusals, s.MaxConsecutiveServerErrors, + s.LastStatusCode, s.LastPath, s.LastUserAgent, s.LastCountryCode, s.LastCity, s.LastRegion, + s.LastSeenAt); + } + } + + public int TrackedCount { get { lock (_gate) return _states.Count; } } + + public void Forget(string sourceKey) + { + lock (_gate) + { + if (_states.Remove(sourceKey, out var s)) RemoveNode(s); + } + } + + private StreakState GetOrCreate(string sourceKey, DateTimeOffset now) + { + if (_states.TryGetValue(sourceKey, out var existing)) return existing; + + // Eviction happens before insertion, so the cap is a cap rather than + // a target the map drifts past. + while (_states.Count >= MaxCap) RemoveOldest(); + + var created = new StreakState { SourceKey = sourceKey, LastSeenAt = now }; + _states[sourceKey] = created; + created.LruNode = _lru.AddLast(sourceKey); + return created; + } + + // Read from the policy once per configuration change so the hot path + // never dereferences the policy record for a bound. + private int MaxCap = 10_000; + + public void Configure(EdgePolicy policy) => MaxCap = Math.Max(1, policy.MaxTrackedSources); + + private void Touch(StreakState state) + { + if (state.LruNode is null) return; + _lru.Remove(state.LruNode); + state.LruNode = _lru.AddLast(state.SourceKey); + } + + private void RemoveOldest() + { + var oldest = _lru.First; + if (oldest is null) return; + _lru.RemoveFirst(); + _states.Remove(oldest.Value); + } + + private void RemoveNode(StreakState s) + { + if (s.LruNode is not null) + { + _lru.Remove(s.LruNode); + s.LruNode = null; + } + } + + private void EvictIdle(DateTimeOffset now, EdgePolicy policy) + { + if (_states.Count == 0) return; + List? stale = null; + foreach (var kv in _states) + { + if (now - kv.Value.LastSeenAt > policy.StateIdleTtl) + { + stale ??= []; + stale.Add(kv.Key); + } + } + if (stale is null) return; + foreach (var key in stale) + { + if (_states.Remove(key, out var s)) RemoveNode(s); + } + } +} diff --git a/dotnet/OpenWaf.Domain/OpenWaf.Domain.csproj b/dotnet/OpenWaf.Domain/OpenWaf.Domain.csproj new file mode 100644 index 0000000..6c3a887 --- /dev/null +++ b/dotnet/OpenWaf.Domain/OpenWaf.Domain.csproj @@ -0,0 +1,7 @@ + + + net10.0 + enable + enable + + diff --git a/dotnet/OpenWaf.Domain/Policy/CountryRule.cs b/dotnet/OpenWaf.Domain/Policy/CountryRule.cs new file mode 100644 index 0000000..c68d1a2 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Policy/CountryRule.cs @@ -0,0 +1,15 @@ +namespace OpenWaf.Domain.Policy; + +/// One country's state in the geo pillar. Under DenyList a rule with +/// IsAllowed=false rejects; under AllowList only IsAllowed=true passes. The +/// same row serves both modes so the admin map has one thing to edit. +public sealed class CountryRule +{ + public string Code { get; init; } = string.Empty; + + public string? Name { get; set; } + + public bool IsAllowed { get; set; } = true; + + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; +} diff --git a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs new file mode 100644 index 0000000..c1e7fa1 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs @@ -0,0 +1,84 @@ +namespace OpenWaf.Domain.Policy; + +/// +/// The whole edge policy as one immutable snapshot, read from configuration +/// and from the policy_settings row (the DB wins where a key is set, +/// so the operator can change the toggle without a redeploy). +/// +/// Q1 is settled here: the streak window (M) and the ban duration are two +/// separate parameters. "N раз підряд на M хвилин" bounds the streak; how +/// long a ban then lasts is a different question and gets its own knob. +/// +public sealed record EdgePolicy +{ + public EnforcementMode Mode { get; init; } = EnforcementMode.Observe; + + /// N — consecutive refusals that trigger a ban. + public int StreakThreshold { get; init; } = 10; + + /// M — the gap between two refusals that still counts as the same + /// streak. A gap longer than this restarts the streak at 1. + public TimeSpan StreakWindow { get; init; } = TimeSpan.FromMinutes(5); + + /// How long an engine ban stays live. + public TimeSpan BanDuration { get; init; } = TimeSpan.FromMinutes(60); + + /// Q2: the refusal class is inclusive of 400 — a malformed-body + /// probe answers 400 and must count. + public StatusRange RefusalRange { get; init; } = new(400, 499); + + /// Q3: 5xx is an alert, never a ban. + public StatusRange ServerErrorRange { get; init; } = new(500, 599); + + /// Q4: source key granularity. IPv6 is grouped to /64 so a bot + /// rotating addresses inside one provider allocation is one source, and a + /// whole office behind one v4 address stays one source (accepted cost, + /// documented, mitigated by the allowlist). + public int Ipv4KeyPrefixLength { get; init; } = 32; + public int Ipv6KeyPrefixLength { get; init; } = 64; + + /// Hard bound on the in-memory streak map. Beyond it the oldest + /// sources are evicted, so a scanner farm cannot grow the process. + /// (LEAS-785 is the cautionary tale: an unbounded ConcurrentDictionary.) + public int MaxTrackedSources { get; init; } = 10_000; + + /// Write-amplification cap: at most one durable observation per + /// source per this interval. + public TimeSpan ObservationWriteInterval { get; init; } = TimeSpan.FromSeconds(30); + + /// A source state nobody has touched for this long is evicted. + public TimeSpan StateIdleTtl { get; init; } = TimeSpan.FromHours(2); + + /// How long a ban's evidence row survives after it stops being live. + public TimeSpan BanRetention { get; init; } = TimeSpan.FromDays(7); + + /// How long an observation row survives without traffic. + public TimeSpan ObservationRetention { get; init; } = TimeSpan.FromDays(7); + + public GeoMode Geo { get; init; } = GeoMode.Off; + + /// Whether X-Forwarded-For / CF-Connecting-IP may define the + /// source address. Off by default: if the header is attacker-controlled + /// every request gets a fresh source key and no streak ever matures. + public bool TrustProxyHeaders { get; init; } + + /// Response the edge gives an engine ban. 403, not 301: a 301 is + /// a good answer to a scanner and a baffling one to a customer whose + /// office IP was caught (Q6). + public int EngineBlockStatus { get; init; } = 403; + + /// Response the edge gives an operator block when the entry has no + /// per-entry redirect. Defaults to the reference behaviour: 301 to a + /// honey-pot list, because scanners follow redirects and honest users + /// typed nothing. + public int OperatorBlockStatus { get; init; } = 301; + public IReadOnlyList DefaultRedirectTargets { get; init; } = + new[] { "https://www.iana.org/help/example-domains" }; + + /// Paths that never consult the guard, so an operator who blocks + /// their own address can still reach the admin API and undo it. + public IReadOnlyList AlwaysPassPrefixes { get; init; } = + new[] { "/admin-api", "/admin", "/healthz", "/readyz", "/openapi", "/swagger" }; + + public static EdgePolicy Default { get; } = new(); +} diff --git a/dotnet/OpenWaf.Domain/Policy/EnforcementMode.cs b/dotnet/OpenWaf.Domain/Policy/EnforcementMode.cs new file mode 100644 index 0000000..d4a7f69 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Policy/EnforcementMode.cs @@ -0,0 +1,22 @@ +namespace OpenWaf.Domain.Policy; + +/// +/// The operator's toggle over the automatic pillar (ruling R1: automatic +/// blocking is a mode, the manual list is untouched by it). Three states +/// rather than two, because "off" and "not yet trusted" are different +/// intentions and an operator needs a way to watch the engine decide without +/// letting it act. +/// +public enum EnforcementMode +{ + /// Engine does not act. Observation still runs, so evidence and + /// candidate bans are visible; nothing is blocked. + Off = 0, + + /// Engine decides and records candidate bans, but the decision + /// point does not enforce them. Dry run. + Observe = 1, + + /// Engine bans are enforced at the decision point. + Enforce = 2 +} diff --git a/dotnet/OpenWaf.Domain/Policy/GeoMode.cs b/dotnet/OpenWaf.Domain/Policy/GeoMode.cs new file mode 100644 index 0000000..747791c --- /dev/null +++ b/dotnet/OpenWaf.Domain/Policy/GeoMode.cs @@ -0,0 +1,12 @@ +namespace OpenWaf.Domain.Policy; + +/// How the country pillar answers. Off keeps geo as pure +/// enrichment; the two list modes make it a rejection policy. +public enum GeoMode +{ + Off = 0, + /// Reject sources whose country is listed as denied. + DenyList = 1, + /// Reject everything except sources whose country is listed as allowed. + AllowList = 2 +} diff --git a/dotnet/OpenWaf.Domain/Policy/StatusRange.cs b/dotnet/OpenWaf.Domain/Policy/StatusRange.cs new file mode 100644 index 0000000..bde9b08 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Policy/StatusRange.cs @@ -0,0 +1,19 @@ +namespace OpenWaf.Domain.Policy; + +/// Inclusive HTTP status range used to classify a response. +public readonly record struct StatusRange(int Low, int High) +{ + public bool Contains(int status) => status >= Low && status <= High; + + public override string ToString() => $"{Low}-{High}"; + + public static StatusRange Parse(string? value, StatusRange fallback) + { + if (string.IsNullOrWhiteSpace(value)) return fallback; + var parts = value.Split('-', StringSplitOptions.TrimEntries); + if (parts.Length != 2) return fallback; + return int.TryParse(parts[0], out var lo) && int.TryParse(parts[1], out var hi) && lo <= hi + ? new StatusRange(lo, hi) + : fallback; + } +} diff --git a/dotnet/OpenWaf.Domain/Security/AllowEntry.cs b/dotnet/OpenWaf.Domain/Security/AllowEntry.cs new file mode 100644 index 0000000..6d49308 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/AllowEntry.cs @@ -0,0 +1,24 @@ +namespace OpenWaf.Domain.Security; + +/// +/// An address or CIDR that must always get through — the operator's own +/// office, the monitoring probe, a customer whose NAT was caught once. +/// Evaluated before every other pillar, and it survives the automatic-ban +/// toggle being off, because its whole purpose is to be the exemption path +/// that cannot be switched away. +/// +public sealed class AllowEntry +{ + public long Id { get; init; } + + /// Single address ("203.0.113.7") or CIDR ("198.51.100.0/24"). + public string Match { get; set; } = string.Empty; + + public string? Note { get; set; } + + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + + public DateTimeOffset? ExpiresAt { get; set; } + + public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now; +} diff --git a/dotnet/OpenWaf.Domain/Security/BlockEntry.cs b/dotnet/OpenWaf.Domain/Security/BlockEntry.cs new file mode 100644 index 0000000..9add19e --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/BlockEntry.cs @@ -0,0 +1,48 @@ +namespace OpenWaf.Domain.Security; + +/// +/// One blocked source — either an operator's manual entry or an engine ban. +/// Keyed by the normalised source key (see ), +/// not by the raw peer address, so a ban written by the engine and a block +/// typed by the operator land on the same row shape and are compared on the +/// same key at the decision point. +/// +public sealed class BlockEntry +{ + public long Id { get; init; } + + /// Normalised source key: IPv4 dotted quad, or IPv6 /64 prefix + /// written as "a:b:c:d::/64". Unique together with . + public string SourceKey { get; set; } = string.Empty; + + public BlockSource Source { get; set; } + + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + + /// Engine bans only. Null means "does not expire" — which only an + /// operator entry may have. + public DateTimeOffset? ExpiresAt { get; set; } + + /// Operator free text, or the engine's machine-readable + /// explanation ("12 consecutive refusals 400-499 in 5 min, last 404 /wp-login.php"). + public string? Reason { get; set; } + + /// Per-entry override for the block response. When set, the edge + /// answers 301 to this URL instead of the kind's default. Operators use it + /// to send scanners to someone else's bandwidth; the engine never sets it. + public string? RedirectTo { get; set; } + + // ---- evidence, so an automatic ban is explainable from stored rows ---- + public int? LastStatusCode { get; set; } + public string? LastPath { get; set; } + public string? LastUserAgent { get; set; } + public string? LastCountryCode { get; set; } + public string? LastCity { get; set; } + public string? LastRegion { get; set; } + public int? ConsecutiveRefusals { get; set; } + + /// Whether the ban is live right now. An operator entry (no + /// expiry) is live until deleted; an engine ban stops being live when it + /// ages out, without anyone having to delete it. + public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now; +} diff --git a/dotnet/OpenWaf.Domain/Security/BlockSource.cs b/dotnet/OpenWaf.Domain/Security/BlockSource.cs new file mode 100644 index 0000000..40cf7fa --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/BlockSource.cs @@ -0,0 +1,17 @@ +namespace OpenWaf.Domain.Security; + +/// +/// Provenance of a block. Required by the owner ruling that manual and +/// automatic blocking are a TOGGLE, not a replacement: the two kinds differ +/// in every way that matters (expiry, explainability, what a clear operation +/// is allowed to touch), so the distinction lives on the row, not in a +/// separate table. +/// +public enum BlockSource +{ + /// Entered by a human operator. Never expires. + Operator = 0, + + /// Issued by the streak engine. Always carries an expiry. + Engine = 1 +} diff --git a/dotnet/OpenWaf.Domain/Security/EdgeAlert.cs b/dotnet/OpenWaf.Domain/Security/EdgeAlert.cs new file mode 100644 index 0000000..adfb528 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/EdgeAlert.cs @@ -0,0 +1,20 @@ +namespace OpenWaf.Domain.Security; + +/// +/// A 5xx streak. Ruling Q3: server errors are never a reason to ban — a bad +/// deploy would ban the site's own honest visitors — but they are a reason to +/// wake somebody up. So the same observer that feeds the ban decision emits +/// alerts for the 5xx class instead of bans. +/// +public sealed class EdgeAlert +{ + public long Id { get; init; } + + public string SourceKey { get; set; } = string.Empty; + public string Kind { get; set; } = "server_error_streak"; + public int Count { get; set; } + public int? LastStatusCode { get; set; } + public string? LastPath { get; set; } + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public string Detail { get; set; } = string.Empty; +} diff --git a/dotnet/OpenWaf.Domain/Security/SourceObservation.cs b/dotnet/OpenWaf.Domain/Security/SourceObservation.cs new file mode 100644 index 0000000..631d7f2 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/SourceObservation.cs @@ -0,0 +1,29 @@ +namespace OpenWaf.Domain.Security; + +/// +/// Rolling per-source counters persisted for the operator's dashboard and for +/// post-hoc explanation of a ban. Aggregated, one row per source key — not an +/// append-only log — because the write-rate cap that keeps a scanner from +/// taxing the database only works if the row is upserted, not inserted. +/// +public sealed class SourceObservation +{ + public string SourceKey { get; init; } = string.Empty; + + public DateTimeOffset FirstSeenAt { get; init; } = DateTimeOffset.UtcNow; + public DateTimeOffset LastSeenAt { get; set; } = DateTimeOffset.UtcNow; + + /// Longest run of refusals ever seen for this source. The engine's + /// live streak counter is in memory; this is its durable shadow. + public int MaxConsecutiveRefusals { get; set; } + + public int TotalRefusals { get; set; } + public int TotalServerErrorStreak { get; set; } + + public int? LastStatusCode { get; set; } + public string? LastPath { get; set; } + public string? LastUserAgent { get; set; } + public string? LastCountryCode { get; set; } + public string? LastCity { get; set; } + public string? LastRegion { get; set; } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs new file mode 100644 index 0000000..88f2759 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -0,0 +1,78 @@ +using OpenWaf.Domain.Security; + +namespace OpenWaf.Edge.Admin; + +internal sealed record BlockDto( + long Id, + string SourceKey, + string Source, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + bool Live, + string? Reason, + string? RedirectTo, + int? ConsecutiveRefusals, + int? LastStatusCode, + string? LastPath, + string? LastUserAgent, + string? LastCountryCode, + string? LastCity); + +internal sealed record NewBlockRequest(string Ip, string? Reason, string? RedirectTo); + +internal sealed record AllowDto(long Id, string Match, string? Note, DateTimeOffset CreatedAt, DateTimeOffset? ExpiresAt); + +internal sealed record NewAllowRequest(string Match, string? Note, int? ExpiresInMinutes); + +internal sealed record PolicyDto( + string Mode, + int StreakThreshold, + double StreakWindowMinutes, + double BanDurationMinutes, + string RefusalRange, + string ServerErrorRange, + string Geo, + bool TrustProxyHeaders, + int MaxTrackedSources, + int Ipv4KeyPrefixLength, + int Ipv6KeyPrefixLength, + int EngineBlockStatus, + int OperatorBlockStatus, + IReadOnlyList DefaultRedirectTargets); + +/// Every field is optional and null means "leave it alone" — a +/// partial update is the only sane shape for a live policy knob. +internal sealed record PolicyUpdateRequest( + string? Mode, + int? StreakThreshold, + double? StreakWindowMinutes, + double? BanDurationMinutes, + string? RefusalRange, + string? ServerErrorRange, + string? Geo, + bool? TrustProxyHeaders, + int? MaxTrackedSources, + int? Ipv4KeyPrefixLength, + int? Ipv6KeyPrefixLength, + int? EngineBlockStatus, + int? OperatorBlockStatus, + string[]? DefaultRedirectTargets); + +internal sealed record ObservationDto( + string SourceKey, + DateTimeOffset LastSeenAt, + int MaxConsecutiveRefusals, + int TotalRefusals, + int TotalServerErrorStreak, + int? LastStatusCode, + string? LastPath, + string? LastCountryCode, + string? LastCity); + +internal static class DtoMapper +{ + public static BlockDto ToDto(this BlockEntry b, DateTimeOffset now) => new( + b.Id, b.SourceKey, b.Source == BlockSource.Operator ? "operator" : "engine", + b.CreatedAt, b.ExpiresAt, b.IsLive(now), b.Reason, b.RedirectTo, b.ConsecutiveRefusals, + b.LastStatusCode, b.LastPath, b.LastUserAgent, b.LastCountryCode, b.LastCity); +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs new file mode 100644 index 0000000..86abfd5 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -0,0 +1,210 @@ +using Microsoft.EntityFrameworkCore; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Geo; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Edge.Admin; + +/// +/// The operator's surface. Deliberately plain: the lists, the toggle, the +/// evidence behind a ban, and nothing else. Two invariants are enforced here +/// rather than trusted to the caller — clearing by provenance can only ever +/// clear that provenance, and every mutation invalidates the guard snapshot so +/// the change lands on the next request instead of after the TTL. +/// +internal static class AdminEndpoints +{ + public static IEndpointRouteBuilder MapAdminApi(this IEndpointRouteBuilder app, string? adminToken) + { + var group = app.MapGroup("/admin-api"); + + // No token configured means the admin surface is closed, not open + // without auth. An edge that can ban people must not itself be the + // easiest way to ban everyone. + group.AddEndpointFilter(async (filterCtx, next) => + { + if (string.IsNullOrWhiteSpace(adminToken)) + return Results.NotFound(new { error = "admin api disabled: set OpenWaf__Admin__Token" }); + + var req = filterCtx.HttpContext.Request; + var provided = req.Headers["X-Admin-Token"].ToString(); + if (string.IsNullOrWhiteSpace(provided)) provided = req.Query["token"].ToString(); + return FixedTimeEquals(provided, adminToken) ? await next(filterCtx) : Results.Unauthorized(); + }); + + group.MapGet("/blocks", async (string? source, bool? live, BlockStore store, CancellationToken ct) => + { + var now = DateTimeOffset.UtcNow; + var rows = await store.ListAsync(ParseSource(source), live ?? true, now, ct); + return Results.Ok(rows.Select(r => r.ToDto(now))); + }); + + group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, CancellationToken ct) => + { + if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" }); + var (ok, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct); + return ok ? Results.NoContent() : Results.BadRequest(new { error }); + }); + + // Provenance is part of the delete, not an afterthought: "clear the + // automatic bans" must never be able to erase an operator's list. + group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, CancellationToken ct) => + { + var parsed = ParseSource(source); + if (parsed is null && string.IsNullOrWhiteSpace(key)) + return Results.BadRequest(new { error = "refusing to delete every block: pass source=operator|engine or key=..." }); + var n = await store.DeleteAsync(parsed, key, ct); + return Results.Ok(new { deleted = n }); + }); + + group.MapGet("/allow", async (OpenWafDbContext db, CancellationToken ct) => + Results.Ok(await db.AllowEntries.AsNoTracking().OrderBy(a => a.Match).ToListAsync(ct))); + + group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + { + if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match)) + return Results.BadRequest(new { error = "match must be an address or CIDR" }); + + var existing = await db.AllowEntries.FirstOrDefaultAsync(a => a.Match == req.Match, ct); + if (existing is not null) return Results.Conflict(new { error = "already allowlisted" }); + + db.AllowEntries.Add(new AllowEntry + { + Match = req.Match.Trim(), + Note = req.Note, + ExpiresAt = req.ExpiresInMinutes is > 0 ? DateTimeOffset.UtcNow.AddMinutes(req.ExpiresInMinutes.Value) : null + }); + await db.SaveChangesAsync(ct); + await state.InvalidateAsync(ct); + return Results.NoContent(); + }); + + group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + { + var n = await db.AllowEntries.Where(a => a.Id == id).ExecuteDeleteAsync(ct); + await state.InvalidateAsync(ct); + return n > 0 ? Results.NoContent() : Results.NotFound(); + }); + + group.MapGet("/policy", (EdgePolicyProvider policy) => Results.Ok(ToDto(policy.Current))); + + group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, CancellationToken ct) => + { + var overrides = new Dictionary(); + if (req.Mode is not null) + { + if (!Enum.TryParse(req.Mode, true, out var mode)) + return Results.BadRequest(new { error = $"mode must be one of {string.Join('|', Enum.GetNames())}" }); + overrides["mode"] = mode.ToString(); + } + if (req.Geo is not null) + { + if (!Enum.TryParse(req.Geo, true, out var geo)) + return Results.BadRequest(new { error = "geo must be Off|DenyList|AllowList" }); + overrides["geo"] = geo.ToString(); + } + if (req.StreakThreshold is > 0) overrides["streakThreshold"] = req.StreakThreshold.Value.ToString(); + if (req.StreakWindowMinutes is > 0) overrides["streakWindowMinutes"] = req.StreakWindowMinutes.Value.ToString(); + if (req.BanDurationMinutes is > 0) overrides["banDurationMinutes"] = req.BanDurationMinutes.Value.ToString(); + if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange; + if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange; + if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant(); + if (req.MaxTrackedSources is > 0) overrides["maxTrackedSources"] = req.MaxTrackedSources.Value.ToString(); + if (req.Ipv4KeyPrefixLength is >= 0) overrides["ipv4KeyPrefixLength"] = req.Ipv4KeyPrefixLength.Value.ToString(); + if (req.Ipv6KeyPrefixLength is >= 0) overrides["ipv6KeyPrefixLength"] = req.Ipv6KeyPrefixLength.Value.ToString(); + if (req.EngineBlockStatus is > 0) overrides["engineBlockStatus"] = req.EngineBlockStatus.Value.ToString(); + if (req.OperatorBlockStatus is > 0) overrides["operatorBlockStatus"] = req.OperatorBlockStatus.Value.ToString(); + if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets); + + // The toggle is a policy change, never a data change: switching + // automatic banning off must leave every row — manual or engine — + // exactly where it was. + await policy.SaveAsync(overrides, ct); + // The policy lives inside the snapshot the guard reads, so saving + // it without refreshing the snapshot would leave the toggle + // appearing to work in the API and not on the wire. + await state.InvalidateAsync(ct); + return Results.Ok(ToDto(policy.Current)); + }); + + group.MapGet("/observations", async (OpenWafDbContext db, int? limit, CancellationToken ct) => + Results.Ok(await db.Observations.AsNoTracking() + .OrderByDescending(o => o.LastSeenAt) + .Take(Math.Clamp(limit ?? 100, 1, 1000)) + .Select(o => new ObservationDto(o.SourceKey, o.LastSeenAt, o.MaxConsecutiveRefusals, + o.TotalRefusals, o.TotalServerErrorStreak, o.LastStatusCode, o.LastPath, + o.LastCountryCode, o.LastCity)) + .ToListAsync(ct))); + + group.MapGet("/alerts", async (OpenWafDbContext db, int? limit, CancellationToken ct) => + Results.Ok(await db.Alerts.AsNoTracking() + .OrderByDescending(a => a.CreatedAt) + .Take(Math.Clamp(limit ?? 100, 1, 1000)) + .ToListAsync(ct))); + + group.MapGet("/countries", async (OpenWafDbContext db, CancellationToken ct) => + Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct))); + + group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + { + code = code.Trim().ToUpperInvariant(); + if (code.Length != 2) return Results.BadRequest(new { error = "code must be a two-letter ISO country code" }); + var row = await db.CountryRules.FindAsync([code], ct); + if (row is null) db.CountryRules.Add(new CountryRule { Code = code, IsAllowed = allowed, UpdatedAt = DateTimeOffset.UtcNow }); + else { row.IsAllowed = allowed; row.UpdatedAt = DateTimeOffset.UtcNow; } + await db.SaveChangesAsync(ct); + await state.InvalidateAsync(ct); + return Results.NoContent(); + }); + + group.MapGet("/geo", (IGeoIpLookup geo) => Results.Ok(new + { + loaded = geo.IsLoaded, + database = geo.Info?.DatabaseType, + builtAt = geo.Info?.BuildDate, + ageDays = geo.Info?.Age is { } age ? Math.Round(age.TotalDays, 1) : (double?)null, + supportsCity = geo.Info?.SupportsCity ?? false + })); + + group.MapGet("/state", (EdgeStateStore state, StreakTracker tracker) => Results.Ok(new + { + snapshotAgeSeconds = Math.Round((DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds, 1), + trackedSources = tracker.TrackedCount, + operatorBlocks = state.Current.OperatorBlocks.Count, + engineBans = state.Current.EngineBans.Count, + allowEntries = state.Current.AllowEntries.Count, + mode = state.Current.Policy.Mode.ToString() + })); + + return app; + } + + private static PolicyDto ToDto(EdgePolicy p) => new( + p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes, + p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders, + p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus, + p.OperatorBlockStatus, p.DefaultRedirectTargets); + + private static BlockSource? ParseSource(string? source) => source?.Trim().ToLowerInvariant() switch + { + "operator" => BlockSource.Operator, + "engine" => BlockSource.Engine, + "all" or "" or null => null, + _ => BlockSource.Operator + }; + + private static bool FixedTimeEquals(string a, string b) + { + if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false; + return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( + System.Text.Encoding.UTF8.GetBytes(a), System.Text.Encoding.UTF8.GetBytes(b)); + } + + private static bool IsValidMatch(string match) + { + if (match.Contains('/')) return NetworkMatch.Matches("203.0.113.1", match) || match.Split('/')[1].Length <= 3; + return SourceKey.TryParse(match, out _, out _); + } +} diff --git a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs new file mode 100644 index 0000000..fbf1aa2 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs @@ -0,0 +1,60 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Edge.Configuration; + +/// +/// The configuration-shaped mirror of . It exists +/// because appsettings.json is strings: is a +/// record struct the configuration binder cannot build from "400-499", and a +/// TimeSpan written as "00:05:00" in a deployment file is friendlier than a +/// number of minutes. One explicit mapping, rather than a binder that quietly +/// leaves a default in place when the shape is wrong. +/// +internal sealed class EdgePolicyOptions +{ + public string Mode { get; set; } = "Observe"; + public int StreakThreshold { get; set; } = 10; + public string StreakWindow { get; set; } = "00:05:00"; + public string BanDuration { get; set; } = "01:00:00"; + public string RefusalRange { get; set; } = "400-499"; + public string ServerErrorRange { get; set; } = "500-599"; + public string Geo { get; set; } = "Off"; + public bool TrustProxyHeaders { get; set; } + public int MaxTrackedSources { get; set; } = 10_000; + public int Ipv4KeyPrefixLength { get; set; } = 32; + public int Ipv6KeyPrefixLength { get; set; } = 64; + public int EngineBlockStatus { get; set; } = 403; + public int OperatorBlockStatus { get; set; } = 301; + // Empty by default: the configuration binder appends to an existing + // collection rather than replacing it, so a non-empty default here would + // leave a duplicate target in every deployment. + public string[] DefaultRedirectTargets { get; set; } = []; + + public EdgePolicy ToPolicy() => new() + { + Mode = Enum.TryParse(Mode, true, out var m) ? m : EnforcementMode.Observe, + StreakThreshold = StreakThreshold > 0 ? StreakThreshold : 10, + StreakWindow = ParseWindow(StreakWindow, TimeSpan.FromMinutes(5)), + BanDuration = ParseWindow(BanDuration, TimeSpan.FromHours(1)), + RefusalRange = StatusRange.Parse(RefusalRange, new StatusRange(400, 499)), + ServerErrorRange = StatusRange.Parse(ServerErrorRange, new StatusRange(500, 599)), + Geo = Enum.TryParse(Geo, true, out var g) ? g : GeoMode.Off, + TrustProxyHeaders = TrustProxyHeaders, + MaxTrackedSources = MaxTrackedSources > 0 ? MaxTrackedSources : 10_000, + Ipv4KeyPrefixLength = Ipv4KeyPrefixLength, + Ipv6KeyPrefixLength = Ipv6KeyPrefixLength, + EngineBlockStatus = EngineBlockStatus, + OperatorBlockStatus = OperatorBlockStatus, + DefaultRedirectTargets = DefaultRedirectTargets.Length == 0 + ? new[] { "https://www.iana.org/help/example-domains" } + : DefaultRedirectTargets + }; + + /// Accepts both 00:05:00 and a bare number of minutes. + private static TimeSpan ParseWindow(string value, TimeSpan fallback) + { + if (string.IsNullOrWhiteSpace(value)) return fallback; + if (TimeSpan.TryParse(value, out var ts)) return ts; + return double.TryParse(value, out var minutes) && minutes > 0 ? TimeSpan.FromMinutes(minutes) : fallback; + } +} diff --git a/dotnet/OpenWaf.Edge/Health/HealthcheckRunner.cs b/dotnet/OpenWaf.Edge/Health/HealthcheckRunner.cs new file mode 100644 index 0000000..893343a --- /dev/null +++ b/dotnet/OpenWaf.Edge/Health/HealthcheckRunner.cs @@ -0,0 +1,29 @@ +namespace OpenWaf.Edge.Health; + +/// +/// dotnet OpenWaf.Edge.dll --healthcheck answers the health endpoint of +/// a running instance and exits 0 or 1. The reference image uses this trick for +/// the same reason: a chiseled distroless base has no shell, no wget and no +/// curl, so the only thing a HEALTHCHECK can run is the binary itself. +/// +internal static class HealthcheckRunner +{ + public static async Task RunAsync(string[] args) + { + var port = Environment.GetEnvironmentVariable("HEALTHCHECK_PORT") ?? "8080"; + var url = $"http://127.0.0.1:{port}/healthz"; + + using var handler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(2) }; + using var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(4) }; + + try + { + using var response = await http.GetAsync(url); + return response.IsSuccessStatusCode ? 0 : 1; + } + catch + { + return 1; + } + } +} diff --git a/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj b/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj new file mode 100644 index 0000000..253f878 --- /dev/null +++ b/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + True + + + + + + + + + + + + + + + + + + diff --git a/dotnet/OpenWaf.Edge/Pipeline/ClientIp.cs b/dotnet/OpenWaf.Edge/Pipeline/ClientIp.cs new file mode 100644 index 0000000..b9b9590 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Pipeline/ClientIp.cs @@ -0,0 +1,47 @@ +using OpenWaf.Domain.Engine; + +namespace OpenWaf.Edge.Pipeline; + +/// +/// Which address the edge treats as the source. +/// +/// Trusting X-Forwarded-For is what makes the WAF work behind a CDN, +/// and it is also the single easiest way to make a ban list useless: if the +/// header is attacker-controlled, every request gets a fresh source key and no +/// streak ever reaches the threshold. So it is opt-in, and the operator is +/// expected to pair it with the CDN's own IP allowlist. +/// +public static class ClientIp +{ + public static string? Resolve(HttpContext ctx, bool trustProxyHeaders) + { + if (trustProxyHeaders) + { + var cf = ctx.Request.Headers["CF-Connecting-IP"].ToString(); + if (SourceKey.TryParse(cf, out _, out _)) return cf.Trim(); + + var real = ctx.Request.Headers["X-Real-IP"].ToString(); + if (SourceKey.TryParse(real, out _, out _)) return real.Trim(); + + var xff = ctx.Request.Headers["X-Forwarded-For"].ToString(); + if (!string.IsNullOrWhiteSpace(xff)) + { + foreach (var hop in xff.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Reverse()) + { + if (SourceKey.TryParse(hop, out _, out _)) return hop; + } + } + } + + return ctx.Connection.RemoteIpAddress?.ToString(); + } + + /// Country as reported by an edge in front of us, when there is + /// one. Preferred over our own MMDB because it was resolved by whoever is + /// closest to the client. + public static string? HeaderCountry(HttpContext ctx) + { + var cf = ctx.Request.Headers["CF-IPCountry"].ToString(); + return string.IsNullOrWhiteSpace(cf) || cf.Length != 2 ? null : cf.Trim().ToUpperInvariant(); + } +} diff --git a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs new file mode 100644 index 0000000..74895a3 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs @@ -0,0 +1,87 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Infrastructure.Geo; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Edge.Pipeline; + +/// +/// The only place in the pipeline that may refuse a request. Everything else +/// observes; this decides. That is the point of the design (OPEN-2): the +/// reference repo runs three guards that each short-circuit on their own, which +/// makes precedence a function of registration order. Here the order is fixed +/// in and the answer is one value. +/// +/// It reads an in-memory snapshot and never touches the database, so the cost +/// on the request path is a dictionary lookup plus, when the geo pillar is on, +/// one memory-mapped MMDB read. +/// +public sealed class EdgeGuardMiddleware( + RequestDelegate next, + EdgeStateStore state, + IGeoIpLookup geo, + ILogger log) +{ + public async Task InvokeAsync(HttpContext ctx) + { + var snapshot = state.GetOrRefresh(); + var path = ctx.Request.Path.Value ?? "/"; + var now = DateTimeOffset.UtcNow; + + var ip = ClientIp.Resolve(ctx, snapshot.Policy.TrustProxyHeaders); + var country = snapshot.Policy.Geo == GeoMode.Off + ? null + : ClientIp.HeaderCountry(ctx) ?? geo.Lookup(ip); + + var decision = DecisionEngine.Decide(snapshot, ip, path, now, country); + + if (!decision.IsBlocked) + { + await next(ctx); + return; + } + + log.LogInformation( + "edge: {Verdict} {Ip} {Path} ({Reason})", decision.Verdict, ip, path, decision.Reason ?? "-"); + + ctx.Response.StatusCode = decision.StatusCode; + + switch (decision.Verdict) + { + case EdgeVerdict.BlockOperator when decision.Location is not null: + ctx.Response.Headers.Location = decision.Location; + await ctx.Response.WriteAsync(string.Empty); + break; + + case EdgeVerdict.BlockEngine: + if (decision.Location is not null) ctx.Response.Headers.Location = decision.Location; + if (decision.ExpiresAt is { } expires) + { + var seconds = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds)); + ctx.Response.Headers.RetryAfter = seconds.ToString(); + } + await ctx.Response.WriteAsJsonAsync(new BlockedBody( + "blocked_by_policy", + decision.Reason, + decision.ExpiresAt?.ToString("O"), + "This decision was made automatically from the responses your source produced. " + + "If it is wrong, an operator can clear it.")); + break; + + case EdgeVerdict.GeoReject: + await ctx.Response.WriteAsJsonAsync(new BlockedBody( + "region_not_supported", + decision.Reason, + null, + "Location is inferred from the address, not known about you; VPNs and misattributed " + + "ranges are wrong sometimes. If you are a real customer, an operator can allow you in.")); + break; + + default: + await ctx.Response.WriteAsync(string.Empty); + break; + } + } +} + +internal sealed record BlockedBody(string Error, string? Reason, string? ExpiresAt, string Note); diff --git a/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs new file mode 100644 index 0000000..8271f89 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs @@ -0,0 +1,127 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Infrastructure.Geo; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Edge.Pipeline; + +/// +/// Runs after the guard, awaits the upstream, and classifies what the +/// application actually answered. This is the seam the reference repo already +/// established in SuspiciousHitTrackerMiddleware — inspect the status +/// after the pipeline, not before it — widened from "one status code" to a +/// configurable predicate plus a streak. +/// +/// Being inside the guard is load-bearing in two directions: +/// * a request the guard already refused is not observed, so a ban can never +/// feed its own streak (a 403 we generate would otherwise re-ban forever); +/// * the status it sees is the upstream's, which is the whole signal. +/// +/// Nothing here blocks. It records, and the only durable consequence is a ban +/// row written once, out of band, when a streak matures. +/// +public sealed class ResponseObservationMiddleware( + RequestDelegate next, + EdgeStateStore state, + StreakTracker tracker, + BlockStore blocks, + AlertWriter alerts, + IGeoIpLookup geo, + ILogger log) +{ + public async Task InvokeAsync(HttpContext ctx) + { + await next(ctx); + + var snapshot = state.Current; + var policy = snapshot.Policy; + if (policy.Mode == EnforcementMode.Off && policy.Geo == GeoMode.Off) return; + + var status = ctx.Response.StatusCode; + var responseClass = ResponseClassifier.Classify(status, policy); + if (responseClass == ResponseClass.Neutral) return; + + var ip = ClientIp.Resolve(ctx, policy.TrustProxyHeaders); + if (string.IsNullOrWhiteSpace(ip)) return; + + var key = SourceKey.For(ip, policy); + if (key.Length == 0) return; + + var path = ctx.Request.Path.Value ?? string.Empty; + + // The always-pass surface is also never observed. The guard lets an + // operator through to the admin API even from a blocked address; if a + // mistyped admin call still counted as a refusal, the operator would + // ban themselves with a syntax error — the one failure mode a recovery + // hatch must not have. + if (DecisionEngine.IsAlwaysPass(path, policy)) return; + + var evidence = BuildEvidence(ctx, ip, responseClass); + + var outcome = tracker.Observe(key, status, responseClass, policy, DateTimeOffset.UtcNow, evidence); + + if (outcome.AlertTriggered) + { + log.LogWarning( + "edge: {Count} consecutive server errors from {Key} (last {Status} {Path}) — alerting, not banning", + outcome.ConsecutiveServerErrors, key, status, path); + + await alerts.RaiseAsync( + "server_error_streak", key, outcome.ConsecutiveServerErrors, status, path, + $"{outcome.ConsecutiveServerErrors} consecutive responses in {policy.ServerErrorRange} " + + $"within {policy.StreakWindow.TotalMinutes:0.#} min. Server errors never ban: a broken deploy " + + $"must not lock out the site's own visitors."); + } + + if (!outcome.BanTriggered) return; + + var streak = tracker.Peek(key); + if (streak is null) return; + + if (policy.Mode == EnforcementMode.Observe) + { + // Dry run: the decision is recorded so an operator can judge the + // rule before it is allowed to act, but nothing is blocked. + await alerts.RaiseAsync( + "candidate_ban", key, outcome.ConsecutiveRefusals, status, path, + $"would ban for {policy.BanDuration.TotalMinutes:0.#} min at N={policy.StreakThreshold} " + + $"within {policy.StreakWindow.TotalMinutes:0.#} min (mode=Observe, not enforced)"); + return; + } + + // Deliberately not ctx.RequestAborted: this runs after the response + // has been written, so the client is free to hang up at any moment and + // a cancelled token would silently drop the ban — the request that + // proves the source is abusive would be the one that fails to record + // it. The write is bounded by the database, not by the visitor. + var ban = await blocks.BanAsync(streak, status, DateTimeOffset.UtcNow); + if (ban is not null) + { + log.LogWarning("edge: banned {Key} until {Until} — {Reason}", key, ban.ExpiresAt, ban.Reason); + } + } + + /// Geo is resolved only for responses that mean something, so an + /// MMDB read is not paid on every 200. + private RequestEvidence BuildEvidence(HttpContext ctx, string ip, ResponseClass responseClass) + { + _ = responseClass; + var headerCountry = ClientIp.HeaderCountry(ctx); + var detail = headerCountry is null ? geo.LookupDetail(ip) : new GeoIpResult(headerCountry, null, null); + if (headerCountry is not null && detail.City is null) + { + var local = geo.LookupDetail(ip); + detail = detail with { City = local.City, Region = local.Region }; + } + + return new RequestEvidence( + Truncate(ctx.Request.Path.Value, 512), + Truncate(ctx.Request.Headers.UserAgent.ToString(), 256), + detail.CountryCode, + Truncate(detail.City, 128), + Truncate(detail.Region, 128)); + } + + private static string? Truncate(string? value, int max) + => string.IsNullOrEmpty(value) ? null : (value.Length <= max ? value : value[..max]); +} diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs new file mode 100644 index 0000000..df89f69 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -0,0 +1,112 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OpenWaf.Domain.Engine; +using OpenWaf.Edge.Admin; +using OpenWaf.Edge.Configuration; +using OpenWaf.Edge.Health; +using OpenWaf.Edge.Pipeline; +using OpenWaf.Edge.Startup; +using OpenWaf.Infrastructure.Geo; +using OpenWaf.Infrastructure.Persistence; + +// Distroless images have no shell, no curl and no wget, so the container +// HEALTHCHECK re-executes this binary in --healthcheck mode and reads its exit +// code. Handled before any host is built: it must work when the host is the +// thing that is broken. +if (args.Length > 0 && args[0] == "--healthcheck") +{ + return await HealthcheckRunner.RunAsync(args); +} + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.Configure(builder.Configuration.GetSection("OpenWaf:Policy")); +builder.Services.AddSingleton(sp => sp.GetRequiredService>().Value.ToPolicy()); + +var provider = builder.Configuration["Database:Provider"] ?? "sqlite"; +var connectionString = builder.Configuration.GetConnectionString("OpenWaf") + ?? "Data Source=openwaf.db"; +builder.Services.AddDbContext(options => +{ + if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString); + else options.UseSqlite(connectionString); +}); + +// One streak map per process. A multi-instance deployment therefore counts +// each instance's traffic separately — recorded as an evolution trigger in the +// OPEN-2 architecture decision, not hidden. +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +// An empty string in appsettings.json is not the same as "unset" to the +// configuration system, and it silently defeats the environment fallback — +// which is exactly how a geo database ends up missing in production. +var geoPath = builder.Configuration["GeoIp:DatabasePath"]; +if (string.IsNullOrWhiteSpace(geoPath)) geoPath = Environment.GetEnvironmentVariable("GEOIP_MAXMIND_DB_PATH"); +builder.Services.AddSingleton(sp => new MaxMindGeoIpLookup( + geoPath, sp.GetRequiredService>())); + +builder.Services.AddHostedService(); +// Registered as themselves as well as hosted services: the admin surface and +// the tests need to reach the writer to force a flush, and AddHostedService +// alone does not make the implementation resolvable. +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); + +builder.Services.AddReverseProxy() + .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); +builder.Services.AddOpenApi(); + +var app = builder.Build(); + +// Order is the design. The guard decides and may short-circuit; the observer +// sits inside it, so it only ever sees responses the upstream actually +// produced — a refusal the edge generated itself must never feed the streak +// that produced the ban. +app.UseMiddleware(); +app.UseMiddleware(); + +app.MapGet("/healthz", (IGeoIpLookup geo, EdgeStateStore state) => Results.Ok(new +{ + status = "ok", + mode = state.Current.Policy.Mode.ToString(), + snapshotAgeSeconds = Math.Round((DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds, 1), + geoLoaded = geo.IsLoaded, + geoDatabase = geo.Info?.DatabaseType, + geoBuiltAt = geo.Info?.BuildDate, + geoStale = geo.Info is not null && geo.Info.IsStale(TimeSpan.FromDays(90)) +})); + +app.MapGet("/readyz", async (OpenWafDbContext db, CancellationToken ct) => +{ + try + { + await db.Database.CanConnectAsync(ct); + return Results.Ok(new { status = "ready" }); + } + catch (Exception ex) + { + return Results.Problem(detail: ex.Message, statusCode: StatusCodes.Status503ServiceUnavailable); + } +}); + +var adminToken = builder.Configuration["OpenWaf:Admin:Token"]; +if (string.IsNullOrWhiteSpace(adminToken)) adminToken = Environment.GetEnvironmentVariable("OPENWAF_ADMIN_TOKEN"); +app.MapAdminApi(adminToken); + +if (!app.Environment.IsProduction()) +{ + app.MapOpenApi(); +} + +app.MapReverseProxy(); + +app.Run(); +return 0; + +/// Marker for WebApplicationFactory in the integration tests. +public partial class Program; diff --git a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs new file mode 100644 index 0000000..053b00b --- /dev/null +++ b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Edge.Startup; + +/// +/// Brings the durable state up before the first request is served: schema, +/// then the guard's first snapshot. +/// +/// The order matters. If the edge starts serving with an empty snapshot +/// because the database was still coming up, every operator block is +/// momentarily invisible — which is the one moment an abusive source is +/// guaranteed to be probing. +/// +internal sealed class EdgeStateWarmer( + IServiceScopeFactory scopeFactory, + EdgeStateStore state, + ILogger log) : IHostedService +{ + public async Task StartAsync(CancellationToken cancellationToken) + { + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var provider = Environment.GetEnvironmentVariable("OPENWAF_DB_PROVIDER"); + if (!string.Equals(provider, "external", StringComparison.OrdinalIgnoreCase)) + { + await db.Database.EnsureCreatedAsync(cancellationToken); + } + + await state.WarmUpAsync(cancellationToken); + log.LogInformation( + "edge: warmed up — {Operator} operator blocks, {Engine} engine bans, {Allow} allow entries", + state.Current.OperatorBlocks.Count, state.Current.EngineBans.Count, state.Current.AllowEntries.Count); + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/dotnet/OpenWaf.Edge/appsettings.Development.json b/dotnet/OpenWaf.Edge/appsettings.Development.json new file mode 100644 index 0000000..2972421 --- /dev/null +++ b/dotnet/OpenWaf.Edge/appsettings.Development.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "Microsoft.AspNetCore": "Information" + } + }, + "OpenWaf": { + "Policy": { + "Mode": "Observe" + } + } +} diff --git a/dotnet/OpenWaf.Edge/appsettings.json b/dotnet/OpenWaf.Edge/appsettings.json new file mode 100644 index 0000000..d1b6eb0 --- /dev/null +++ b/dotnet/OpenWaf.Edge/appsettings.json @@ -0,0 +1,57 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "OpenWaf": "Data Source=openwaf.db" + }, + "Database": { + "Provider": "sqlite" + }, + "GeoIp": { + "DatabasePath": "" + }, + "OpenWaf": { + "Admin": { + "Token": "" + }, + "Policy": { + "Mode": "Observe", + "StreakThreshold": 10, + "StreakWindow": "00:05:00", + "BanDuration": "01:00:00", + "RefusalRange": "400-499", + "ServerErrorRange": "500-599", + "Geo": "Off", + "TrustProxyHeaders": false, + "MaxTrackedSources": 10000, + "Ipv4KeyPrefixLength": 32, + "Ipv6KeyPrefixLength": 64, + "EngineBlockStatus": 403, + "OperatorBlockStatus": 301, + "DefaultRedirectTargets": [ "https://www.iana.org/help/example-domains" ] + } + }, + "ReverseProxy": { + "Routes": { + "all": { + "ClusterId": "upstream", + "Match": { "Path": "{**catch-all}" } + } + }, + "Clusters": { + "upstream": { + "Destinations": { + "upstream1": { + "Address": "http://127.0.0.1:9000/" + } + } + } + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Geo/GeoDatabaseInfo.cs b/dotnet/OpenWaf.Infrastructure/Geo/GeoDatabaseInfo.cs new file mode 100644 index 0000000..47825bc --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Geo/GeoDatabaseInfo.cs @@ -0,0 +1,17 @@ +namespace OpenWaf.Infrastructure.Geo; + +/// What the loaded MMDB actually is. The reference repo stores a +/// dbip-city-lite database under the legacy GeoLite2-Country.mmdb name +/// and sniffs the real type from metadata rather than trusting the path; this +/// is the same rule, surfaced. The build date is here because the database is +/// pinned by a build ARG and ages with the image — a country policy enforced on +/// a stale database misclassifies reallocated ranges invisibly. +public sealed record GeoDatabaseInfo( + string Path, + string DatabaseType, + DateTimeOffset? BuildDate, + bool SupportsCity) +{ + public TimeSpan? Age => BuildDate is null ? null : DateTimeOffset.UtcNow - BuildDate.Value; + public bool IsStale(TimeSpan maxAge) => BuildDate is not null && DateTimeOffset.UtcNow - BuildDate.Value > maxAge; +} diff --git a/dotnet/OpenWaf.Infrastructure/Geo/GeoIpResult.cs b/dotnet/OpenWaf.Infrastructure/Geo/GeoIpResult.cs new file mode 100644 index 0000000..603548b --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Geo/GeoIpResult.cs @@ -0,0 +1,11 @@ +namespace OpenWaf.Infrastructure.Geo; + +/// An IP's resolved location. Every field is nullable because a +/// geo answer is a probabilistic claim about an address, not a fact about a +/// person — private ranges, reserved ranges and unlisted blocks resolve to +/// nothing, and the caller has to be able to tell "unknown" from "somewhere". +public sealed record GeoIpResult(string? CountryCode, string? City = null, string? Region = null) +{ + public static readonly GeoIpResult Unknown = new(CountryCode: null); + public bool IsKnown => !string.IsNullOrWhiteSpace(CountryCode); +} diff --git a/dotnet/OpenWaf.Infrastructure/Geo/IGeoIpLookup.cs b/dotnet/OpenWaf.Infrastructure/Geo/IGeoIpLookup.cs new file mode 100644 index 0000000..6e35014 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Geo/IGeoIpLookup.cs @@ -0,0 +1,12 @@ +namespace OpenWaf.Infrastructure.Geo; + +/// IP → location. Implementations must be thread-safe and cheap +/// enough to call on the request path (the bundled MMDB is memory-mapped, so +/// it is), and must never throw at a caller on that path. +public interface IGeoIpLookup +{ + bool IsLoaded { get; } + GeoDatabaseInfo? Info { get; } + GeoIpResult LookupDetail(string? ip); + string? Lookup(string? ip) => LookupDetail(ip).CountryCode; +} diff --git a/dotnet/OpenWaf.Infrastructure/Geo/MaxMindGeoIpLookup.cs b/dotnet/OpenWaf.Infrastructure/Geo/MaxMindGeoIpLookup.cs new file mode 100644 index 0000000..6939a57 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Geo/MaxMindGeoIpLookup.cs @@ -0,0 +1,96 @@ +using System.Net; +using MaxMind.GeoIP2; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; + +namespace OpenWaf.Infrastructure.Geo; + +/// +/// Reads the bundled MMDB (dbip-city-lite or GeoLite2 — same binary format). +/// +/// Two rules the reference repo already established and this one keeps: +/// * the filename is not evidence. The file is routinely named +/// GeoLite2-Country.mmdb while being a city database, so the real +/// granularity comes from 's +/// DatabaseType and nothing else; +/// * a lookup that cannot be answered returns Unknown. It never throws at the +/// request path and never becomes a rejection. +/// +/// A missing or unreadable database degrades the whole geo pillar to off, with +/// one warning at startup, rather than failing every request. +/// +public sealed class MaxMindGeoIpLookup : IGeoIpLookup, IDisposable +{ + private readonly DatabaseReader? _reader; + private readonly bool _supportsCity; + + public bool IsLoaded => _reader is not null; + public GeoDatabaseInfo? Info { get; } + + public MaxMindGeoIpLookup(string? path, ILogger log) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { + log.LogWarning("GeoIP: no database at {Path}; country policy is inert.", path ?? "(unset)"); + _reader = null; + Info = null; + return; + } + + try + { + _reader = new DatabaseReader(path); + var type = _reader.Metadata.DatabaseType; + _supportsCity = type.Contains("City", StringComparison.OrdinalIgnoreCase); + var built = _reader.Metadata.BuildDate; + Info = new GeoDatabaseInfo(path, type, built == default ? null : new DateTimeOffset(built, TimeSpan.Zero), _supportsCity); + log.LogInformation("GeoIP: loaded {Type} from {Path} (built {Built}).", + type, path, built == default ? "unknown" : built.ToString("yyyy-MM-dd")); + } + catch (Exception ex) + { + log.LogWarning(ex, "GeoIP: could not open {Path}; country policy is inert.", path); + _reader?.Dispose(); + _reader = null; + Info = null; + } + } + + public GeoIpResult LookupDetail(string? ip) + { + if (_reader is null) return GeoIpResult.Unknown; + if (!SourceKey.TryParse(ip, out _, out var normalized)) return GeoIpResult.Unknown; + + try + { + if (_supportsCity) + { + if (_reader.TryCity(normalized, out var city) && city is not null) + { + return new GeoIpResult( + city.Country?.IsoCode, + city.City?.Name, + city.Subdivisions.Count > 0 ? city.Subdivisions[^1].IsoCode : null); + } + return GeoIpResult.Unknown; + } + + if (_reader.TryCountry(normalized, out var country) && country is not null) + { + return new GeoIpResult(country.Country?.IsoCode); + } + return GeoIpResult.Unknown; + } + catch (ArgumentException) + { + return GeoIpResult.Unknown; + } + catch (Exception) + { + // A malformed record in the database must not become a 500. + return GeoIpResult.Unknown; + } + } + + public void Dispose() => _reader?.Dispose(); +} diff --git a/dotnet/OpenWaf.Infrastructure/Geo/NullGeoIpLookup.cs b/dotnet/OpenWaf.Infrastructure/Geo/NullGeoIpLookup.cs new file mode 100644 index 0000000..cb3ea50 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Geo/NullGeoIpLookup.cs @@ -0,0 +1,12 @@ +namespace OpenWaf.Infrastructure.Geo; + +/// No database configured. The geo pillar reads this as "off" — +/// missing geo data degrades to no policy, never to a rejection and never to a +/// 500. +public sealed class NullGeoIpLookup : IGeoIpLookup +{ + public static readonly NullGeoIpLookup Instance = new(); + public bool IsLoaded => false; + public GeoDatabaseInfo? Info => null; + public GeoIpResult LookupDetail(string? ip) => GeoIpResult.Unknown; +} diff --git a/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj new file mode 100644 index 0000000..baffb52 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + net10.0 + enable + enable + + + + + + + + diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs new file mode 100644 index 0000000..34b3e70 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Raises operator-visible alerts. Two kinds exist and they mean different +/// things: server_error_streak is "your upstream is failing" (Q3: never +/// a reason to ban, always a reason to look), and candidate_ban is "the +/// engine would have banned this source" — which is what makes Observe mode +/// worth having, because without it a dry run is invisible. +/// +public sealed class AlertWriter +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _log; + + public AlertWriter(IServiceScopeFactory scopeFactory, ILogger log) + { + _scopeFactory = scopeFactory; + _log = log; + } + + public async Task RaiseAsync( + string kind, + string sourceKey, + int count, + int? statusCode, + string? path, + string detail, + CancellationToken ct = default) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Alerts.Add(new EdgeAlert + { + Kind = kind, + SourceKey = sourceKey, + Count = count, + LastStatusCode = statusCode, + LastPath = path, + Detail = detail.Length > 1024 ? detail[..1024] : detail, + CreatedAt = DateTimeOffset.UtcNow + }); + await db.SaveChangesAsync(ct); + } + catch (Exception ex) + { + _log.LogWarning(ex, "AlertWriter: could not persist a {Kind} alert for {Key}.", kind, sourceKey); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs new file mode 100644 index 0000000..a5cc84a --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -0,0 +1,198 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Every write to the block list goes through here, for one reason: the +/// difference between an operator entry and an engine ban has to be enforced +/// somewhere, and it should not be the caller's memory. +/// +public sealed class BlockStore +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly EdgeStateStore _state; + + /// Ban writes are rare — once per source per ban — so one gate + /// serialises them cheaply. Without it two requests from the same source + /// that finish a few milliseconds apart both read "no ban yet" and both + /// insert, and the loser's evidence is lost to the unique index. The + /// observer runs after the response is written, so the client is free to + /// send the next request while the previous one's ban is still landing. + private readonly SemaphoreSlim _banGate = new(1, 1); + private readonly EdgePolicyProvider _policy; + private readonly ILogger _log; + + public BlockStore( + IServiceScopeFactory scopeFactory, + EdgeStateStore state, + EdgePolicyProvider policy, + ILogger log) + { + _scopeFactory = scopeFactory; + _state = state; + _policy = policy; + _log = log; + } + + /// + /// Issue or refresh an engine ban. Rare (once per source per ban), so it + /// writes immediately instead of going through the coalescing writer — a + /// ban that lands 15 seconds late is a ban that let 15 more requests through. + /// + /// A live ban is not extended: a scanner that keeps probing while already + /// blocked must not be able to extend its own sentence indefinitely. Its + /// evidence is refreshed so the operator sees the latest probe. + /// + public async Task BanAsync(StreakSnapshot streak, int statusCode, DateTimeOffset now, CancellationToken ct = default) + { + var policy = _policy.Current; + var expiresAt = now + policy.BanDuration; + var reason = $"{streak.MaxConsecutiveRefusals} consecutive refusals " + + $"({policy.RefusalRange}) within {policy.StreakWindow.TotalMinutes:0.#} min; " + + $"last {statusCode} {(streak.LastPath is null ? "" : streak.LastPath)}"; + + // Serialised: the observer runs after the response has been written, + // so the next request from the same source can arrive while this ban is + // still landing, and two readers that both see "no ban yet" produce a + // unique-index loser and a lost evidence row. + await _banGate.WaitAsync(ct); + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var existing = await db.Blocks + .FirstOrDefaultAsync(b => b.SourceKey == streak.SourceKey && b.Source == BlockSource.Engine, ct); + + if (existing is null) + { + existing = new BlockEntry + { + SourceKey = streak.SourceKey, + Source = BlockSource.Engine, + CreatedAt = now, + ExpiresAt = expiresAt, + Reason = reason, + ConsecutiveRefusals = streak.MaxConsecutiveRefusals + }; + db.Blocks.Add(existing); + } + else if (!existing.IsLive(now)) + { + existing.CreatedAt = now; + existing.ExpiresAt = expiresAt; + existing.Reason = reason; + existing.ConsecutiveRefusals = streak.MaxConsecutiveRefusals; + } + + existing.LastStatusCode = statusCode; + existing.LastPath = streak.LastPath; + existing.LastUserAgent = streak.LastUserAgent; + existing.LastCountryCode = streak.LastCountryCode; + existing.LastCity = streak.LastCity; + existing.LastRegion = streak.LastRegion; + + await db.SaveChangesAsync(ct); + await _state.InvalidateAsync(ct); + return existing; + } + catch (DbUpdateException ex) + { + // Still possible across processes — two edges sharing one database. + // The winner's row is the one that matters; the loser's evidence is + // already in the observation stream. + _log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", streak.SourceKey); + return null; + } + catch (Exception ex) + { + // A ban that could not be written must not take the request down. + // The streak is still in memory, so the next refusal retries. + _log.LogWarning(ex, "BlockStore: could not persist a ban for {Key}.", streak.SourceKey); + return null; + } + finally + { + _banGate.Release(); + } + } + + public async Task<(bool Ok, string? Error)> AddOperatorAsync( + string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default) + { + if (!SourceKey.TryParse(sourceKey, out _, out var normalized)) + return (false, $"not an IP address: {sourceKey}"); + + var key = SourceKey.For(normalized.ToString(), _policy.Current); + + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct); + if (row is null) + { + db.Blocks.Add(new BlockEntry + { + SourceKey = key, + Source = BlockSource.Operator, + CreatedAt = now, + Reason = reason, + RedirectTo = redirectTo + }); + } + else + { + row.Reason = reason ?? row.Reason; + row.RedirectTo = redirectTo ?? row.RedirectTo; + } + await db.SaveChangesAsync(ct); + await _state.InvalidateAsync(ct); + return (true, null); + } + catch (Exception ex) + { + _log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key); + return (false, "database error"); + } + } + + /// + /// Delete blocks, optionally restricted to one provenance. The provenance + /// filter is not cosmetic: "clear the automatic bans" must never be able to + /// erase what an operator typed by hand, which is exactly what R1 forbids. + /// + public async Task DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var q = db.Blocks.AsQueryable(); + if (source is not null) q = q.Where(b => b.Source == source.Value); + if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey); + var n = await q.ExecuteDeleteAsync(ct); + await _state.InvalidateAsync(ct); + return n; + } + catch (Exception ex) + { + _log.LogWarning(ex, "BlockStore: delete failed."); + return 0; + } + } + + public async Task> ListAsync(BlockSource? source, bool liveOnly, DateTimeOffset now, CancellationToken ct = default) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var q = db.Blocks.AsNoTracking().AsQueryable(); + if (source is not null) q = q.Where(b => b.Source == source.Value); + if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now); + return await q.OrderByDescending(b => b.CreatedAt).Take(500).ToListAsync(ct); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs new file mode 100644 index 0000000..9d36eae --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs @@ -0,0 +1,99 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// The live policy. Configuration supplies the defaults; the +/// policy_settings table supplies the operator's overrides, so the +/// toggle can be flipped without a redeploy and survives one. +/// +public sealed class EdgePolicyProvider +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _log; + private EdgePolicy _current; + + public EdgePolicyProvider( + IServiceScopeFactory scopeFactory, + EdgePolicy configured, + ILogger log) + { + _scopeFactory = scopeFactory; + _log = log; + _current = configured; + } + + public EdgePolicy Current => _current; + + public async Task ReloadAsync(CancellationToken ct = default) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var rows = await db.PolicySettings.AsNoTracking().ToListAsync(ct); + _current = ApplyOverrides(_current, rows); + } + catch (Exception ex) + { + _log.LogWarning(ex, "EdgePolicyProvider: reload failed; keeping the current policy."); + } + return _current; + } + + public async Task SaveAsync(IReadOnlyDictionary overrides, CancellationToken ct = default) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var (key, value) in overrides) + { + if (value is null) + { + await db.PolicySettings.Where(p => p.Key == key).ExecuteDeleteAsync(ct); + continue; + } + var row = await db.PolicySettings.FindAsync([key], ct); + if (row is null) db.PolicySettings.Add(new PolicySetting { Key = key, Value = value, UpdatedAt = DateTimeOffset.UtcNow }); + else { row.Value = value; row.UpdatedAt = DateTimeOffset.UtcNow; } + } + await db.SaveChangesAsync(ct); + await ReloadAsync(ct); + return true; + } + catch (Exception ex) + { + _log.LogWarning(ex, "EdgePolicyProvider: save failed."); + return false; + } + } + + private static EdgePolicy ApplyOverrides(EdgePolicy basePolicy, IReadOnlyCollection rows) + { + if (rows.Count == 0) return basePolicy; + var map = rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.OrdinalIgnoreCase); + var p = basePolicy; + + if (map.TryGetValue("mode", out var mode) && Enum.TryParse(mode, true, out var m)) p = p with { Mode = m }; + if (map.TryGetValue("streakThreshold", out var n) && int.TryParse(n, out var nv) && nv > 0) p = p with { StreakThreshold = nv }; + if (map.TryGetValue("streakWindowMinutes", out var mw) && double.TryParse(mw, out var mwv) && mwv > 0) p = p with { StreakWindow = TimeSpan.FromMinutes(mwv) }; + if (map.TryGetValue("banDurationMinutes", out var bd) && double.TryParse(bd, out var bdv) && bdv > 0) p = p with { BanDuration = TimeSpan.FromMinutes(bdv) }; + if (map.TryGetValue("refusalRange", out var rr)) p = p with { RefusalRange = StatusRange.Parse(rr, p.RefusalRange) }; + if (map.TryGetValue("serverErrorRange", out var sr)) p = p with { ServerErrorRange = StatusRange.Parse(sr, p.ServerErrorRange) }; + if (map.TryGetValue("trustProxyHeaders", out var tph) && bool.TryParse(tph, out var tphv)) p = p with { TrustProxyHeaders = tphv }; + if (map.TryGetValue("geo", out var geo) && Enum.TryParse(geo, true, out var gm)) p = p with { Geo = gm }; + if (map.TryGetValue("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv }; + if (map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v }; + if (map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v }; + if (map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv }; + if (map.TryGetValue("operatorBlockStatus", out var obs) && int.TryParse(obs, out var obsv)) p = p with { OperatorBlockStatus = obsv }; + if (map.TryGetValue("redirectTargets", out var rt) && !string.IsNullOrWhiteSpace(rt)) + p = p with { DefaultRedirectTargets = rt.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }; + + return p; + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs new file mode 100644 index 0000000..bdce9d1 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -0,0 +1,115 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Holds the snapshot the decision point reads and refreshes it off the +/// request path. +/// +/// The reference repo blocks the request thread on a stale cache +/// (RefreshAsync().GetAwaiter().GetResult()). This does not: a stale +/// snapshot is served while a single background refresh runs, because a +/// database hiccup should not add latency to every request, and a snapshot +/// that is 30 seconds old is a documented, accepted state. The very first load +/// is awaited at startup, so the edge never serves traffic with an empty +/// picture of the operator's list. +/// +/// On refresh failure the previous snapshot is kept — fail closed for blocks. +/// A bot probing during a database restart must not skate past the gate. +/// +public sealed class EdgeStateStore +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly EdgePolicyProvider _policy; + private readonly ILogger _log; + private readonly SemaphoreSlim _refreshLock = new(1, 1); + private EdgeSnapshot _snapshot; + private int _refreshInFlight; + + public EdgeStateStore( + IServiceScopeFactory scopeFactory, + EdgePolicyProvider policy, + ILogger log) + { + _scopeFactory = scopeFactory; + _policy = policy; + _log = log; + _snapshot = EdgeSnapshot.Empty(policy.Current); + } + + public EdgeSnapshot Current => _snapshot; + + public TimeSpan RefreshTtl { get; set; } = TimeSpan.FromSeconds(30); + + /// Blocking load, used once at startup. + public Task WarmUpAsync(CancellationToken ct = default) => RefreshAsync(ct); + + /// Serve now, refresh in the background if the TTL has expired. + public EdgeSnapshot GetOrRefresh() + { + var snapshot = _snapshot; + if (DateTimeOffset.UtcNow - snapshot.GeneratedAt > RefreshTtl && Interlocked.CompareExchange(ref _refreshInFlight, 1, 0) == 0) + { + _ = Task.Run(async () => + { + try { await RefreshAsync(CancellationToken.None); } + finally { Interlocked.Exchange(ref _refreshInFlight, 0); } + }); + } + return snapshot; + } + + /// Admin mutations call this so the operator's change lands on the + /// next request rather than after the TTL. + public Task InvalidateAsync(CancellationToken ct = default) => RefreshAsync(ct); + + private async Task RefreshAsync(CancellationToken ct) + { + if (!await _refreshLock.WaitAsync(TimeSpan.FromSeconds(10), ct)) return; + try + { + var policy = await _policy.ReloadAsync(ct); + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var blocks = await db.Blocks.AsNoTracking().ToListAsync(ct); + var allow = await db.AllowEntries.AsNoTracking().ToListAsync(ct); + var countries = await db.CountryRules.AsNoTracking().ToListAsync(ct); + + var operatorBlocks = new Dictionary(StringComparer.Ordinal); + var engineBans = new Dictionary(StringComparer.Ordinal); + foreach (var b in blocks) + { + if (b.Source == BlockSource.Operator) operatorBlocks[b.SourceKey] = b; + else engineBans[b.SourceKey] = b; + } + + var countryMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var c in countries) countryMap[c.Code] = c; + + _snapshot = new EdgeSnapshot + { + GeneratedAt = DateTimeOffset.UtcNow, + Policy = policy, + OperatorBlocks = operatorBlocks, + EngineBans = engineBans, + AllowEntries = allow, + Countries = countryMap + }; + } + catch (Exception ex) + { + _log.LogWarning(ex, "EdgeStateStore: refresh failed; keeping the previous snapshot."); + } + finally + { + _refreshLock.Release(); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs new file mode 100644 index 0000000..2412241 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs @@ -0,0 +1,126 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Persists the in-memory streak state on a timer. This is the write +/// amplification protection the reference repo already paid for: a scanner +/// hammering thousands of paths a second must not generate matching writes a +/// second, so the tracker stays in memory and at most one durable upsert per +/// source per ObservationWriteInterval leaves this loop. +/// +public sealed class ObservationWriter : BackgroundService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly StreakTracker _tracker; + private readonly EdgePolicyProvider _policy; + private readonly ILogger _log; + private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15); + private readonly Dictionary _lastWrittenAt = new(StringComparer.Ordinal); + + public ObservationWriter( + IServiceScopeFactory scopeFactory, + StreakTracker tracker, + EdgePolicyProvider policy, + ILogger log) + { + _scopeFactory = scopeFactory; + _tracker = tracker; + _policy = policy; + _log = log; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try { await Task.Delay(_flushInterval, stoppingToken); } + catch (TaskCanceledException) { return; } + await FlushAsync(stoppingToken); + } + await FlushAsync(CancellationToken.None); + } + + internal async Task FlushAsync(CancellationToken ct) + { + var policy = _policy.Current; + var now = DateTimeOffset.UtcNow; + var snapshots = _tracker.Snapshot(now, policy); + if (snapshots.Count == 0) return 0; + + var due = new List(); + foreach (var s in snapshots) + { + if (_lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval) + continue; + due.Add(s); + _lastWrittenAt[s.SourceKey] = now; + } + + if (_lastWrittenAt.Count > policy.MaxTrackedSources) + { + foreach (var key in _lastWrittenAt.Where(kv => now - kv.Value > policy.StateIdleTtl).Select(kv => kv.Key).ToList()) + _lastWrittenAt.Remove(key); + } + + if (due.Count == 0) return 0; + + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var keys = due.Select(d => d.SourceKey).ToList(); + var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(ct); + var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal); + + foreach (var s in due) + { + if (byKey.TryGetValue(s.SourceKey, out var row)) + { + row.LastSeenAt = s.LastSeenAt; + row.MaxConsecutiveRefusals = Math.Max(row.MaxConsecutiveRefusals, s.MaxConsecutiveRefusals); + row.TotalRefusals = Math.Max(row.TotalRefusals, s.TotalRefusals); + row.TotalServerErrorStreak = Math.Max(row.TotalServerErrorStreak, s.MaxConsecutiveServerErrors); + row.LastStatusCode = s.LastStatusCode ?? row.LastStatusCode; + row.LastPath = s.LastPath ?? row.LastPath; + row.LastUserAgent = s.LastUserAgent ?? row.LastUserAgent; + row.LastCountryCode = s.LastCountryCode ?? row.LastCountryCode; + row.LastCity = s.LastCity ?? row.LastCity; + row.LastRegion = s.LastRegion ?? row.LastRegion; + } + else + { + db.Observations.Add(new SourceObservation + { + SourceKey = s.SourceKey, + FirstSeenAt = s.LastSeenAt, + LastSeenAt = s.LastSeenAt, + MaxConsecutiveRefusals = s.MaxConsecutiveRefusals, + TotalRefusals = s.TotalRefusals, + TotalServerErrorStreak = s.MaxConsecutiveServerErrors, + LastStatusCode = s.LastStatusCode, + LastPath = s.LastPath, + LastUserAgent = s.LastUserAgent, + LastCountryCode = s.LastCountryCode, + LastCity = s.LastCity, + LastRegion = s.LastRegion + }); + } + } + await db.SaveChangesAsync(ct); + return due.Count; + } + catch (Exception ex) + { + // The writer must survive: losing observations is better than + // taking the host down over a transient database error. + _log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count); + return 0; + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs new file mode 100644 index 0000000..df68ed6 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs @@ -0,0 +1,132 @@ +using Microsoft.EntityFrameworkCore; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Six tables, all small. The edge never queries them on the request path — +/// holds the snapshot it reads — so the schema is +/// sized for operator inspection and for explaining a ban after the fact, not +/// for throughput. +/// +public sealed class OpenWafDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Blocks => Set(); + public DbSet AllowEntries => Set(); + public DbSet Observations => Set(); + public DbSet CountryRules => Set(); + public DbSet Alerts => Set(); + public DbSet PolicySettings => Set(); + + protected override void OnModelCreating(ModelBuilder mb) + { + StoreTimestampsAsIntegersOnSqlite(mb); + mb.Entity(e => + { + e.ToTable("block_entries"); + e.HasKey(b => b.Id); + // One row per (source key, provenance): an operator block and an + // engine ban on the same address coexist on purpose — the operator + // entry outlives the ban and must not be overwritten by it. + e.HasIndex(b => new { b.SourceKey, b.Source }).IsUnique(); + e.HasIndex(b => b.ExpiresAt); + e.Property(b => b.SourceKey).HasMaxLength(128).IsRequired(); + e.Property(b => b.Reason).HasMaxLength(1024); + e.Property(b => b.RedirectTo).HasMaxLength(512); + e.Property(b => b.LastPath).HasMaxLength(512); + e.Property(b => b.LastUserAgent).HasMaxLength(256); + e.Property(b => b.LastCountryCode).HasMaxLength(2); + e.Property(b => b.LastCity).HasMaxLength(128); + e.Property(b => b.LastRegion).HasMaxLength(128); + e.Property(b => b.Source).HasConversion(); + }); + + mb.Entity(e => + { + e.ToTable("allow_entries"); + e.HasKey(a => a.Id); + e.HasIndex(a => a.Match).IsUnique(); + e.Property(a => a.Match).HasMaxLength(128).IsRequired(); + e.Property(a => a.Note).HasMaxLength(512); + }); + + mb.Entity(e => + { + e.ToTable("source_observations"); + e.HasKey(o => o.SourceKey); + e.Property(o => o.SourceKey).HasMaxLength(128); + e.HasIndex(o => o.LastSeenAt); + e.Property(o => o.LastPath).HasMaxLength(512); + e.Property(o => o.LastUserAgent).HasMaxLength(256); + e.Property(o => o.LastCountryCode).HasMaxLength(2); + e.Property(o => o.LastCity).HasMaxLength(128); + e.Property(o => o.LastRegion).HasMaxLength(128); + }); + + mb.Entity(e => + { + e.ToTable("country_rules"); + e.HasKey(c => c.Code); + e.Property(c => c.Code).HasMaxLength(2); + e.Property(c => c.Name).HasMaxLength(128); + }); + + mb.Entity(e => + { + e.ToTable("edge_alerts"); + e.HasKey(a => a.Id); + e.HasIndex(a => a.CreatedAt); + e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired(); + e.Property(a => a.Kind).HasMaxLength(64).IsRequired(); + e.Property(a => a.Detail).HasMaxLength(1024).IsRequired(); + }); + + mb.Entity(e => + { + e.ToTable("policy_settings"); + e.HasKey(p => p.Key); + e.Property(p => p.Key).HasMaxLength(64); + e.Property(p => p.Value).HasMaxLength(256).IsRequired(); + }); + } + + /// + /// SQLite has no timestamp type: the provider stores a DateTimeOffset as + /// text and then refuses to compare it, so every "is this ban still live" + /// and "has this observation aged out" query dies at translation time. + /// Storing the instant as an integer makes those comparisons ordinary + /// integer comparisons and keeps the retention rules working on the default + /// provider. PostgreSQL keeps its native timestamptz, where an operator can + /// read the column. + /// + private void StoreTimestampsAsIntegersOnSqlite(ModelBuilder mb) + { + if (Database.ProviderName?.Contains("Sqlite") != true) return; + + var converter = new Microsoft.EntityFrameworkCore.Storage.ValueConversion.DateTimeOffsetToBinaryConverter(); + foreach (var entityType in mb.Model.GetEntityTypes()) + { + foreach (var property in entityType.GetProperties()) + { + var clr = property.ClrType; + if (clr == typeof(DateTimeOffset) || clr == typeof(DateTimeOffset?)) + { + property.SetValueConverter(converter); + } + } + } + } +} + +/// +/// Operator-set policy overrides, one row per key, layered over what comes +/// from configuration. Stored as text on purpose: the set of knobs is small and +/// a column per knob would need a migration every time one is added. +/// +public sealed class PolicySetting +{ + public string Key { get; init; } = string.Empty; + public string Value { get; set; } = string.Empty; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs new file mode 100644 index 0000000..bb306ae --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs @@ -0,0 +1,54 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Retention (Q8). The edge stores aggregates, not a request log, so the +/// privacy question the reference repo left open for SiteVisit — how +/// long a raw IP may sit in the database — has a bounded answer here: idle +/// observations and expired engine bans age out on a timer. +/// +public sealed class RetentionWorker : BackgroundService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly EdgePolicyProvider _policy; + private readonly ILogger _log; + private readonly TimeSpan _interval = TimeSpan.FromMinutes(30); + + public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, ILogger log) + { + _scopeFactory = scopeFactory; + _policy = policy; + _log = log; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try { await Task.Delay(_interval, stoppingToken); } + catch (TaskCanceledException) { return; } + try { await PruneAsync(CancellationToken.None); } + catch (Exception ex) { _log.LogWarning(ex, "RetentionWorker: prune failed."); } + } + } + + internal async Task PruneAsync(CancellationToken ct) + { + var policy = _policy.Current; + var now = DateTimeOffset.UtcNow; + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct); + await db.Blocks + .Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention) + .ExecuteDeleteAsync(ct); + await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs b/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs new file mode 100644 index 0000000..e6ae12a --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs @@ -0,0 +1,340 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.AspNetCore.Http; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +public sealed class EdgeBlockingTests +{ + private const string Scanner = "203.0.113.66"; + private const string Bystander = "198.51.100.7"; + + private static async Task GetAsync( + EdgeFixture f, string path, string sourceIp, string? country = null, string? token = null) + { + var client = f.Client; + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); + if (country is not null) request.Headers.TryAddWithoutValidation("CF-IPCountry", country); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + return await client.SendAsync(request); + } + + private static async Task JsonAsync(HttpResponseMessage response) + => JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; + + [Fact] + public async Task A_run_of_refusals_bans_that_source_and_nobody_else() + { + await using var f = new EdgeFixture(threshold: 3); + + for (var i = 0; i < 3; i++) + { + using var probe = await GetAsync(f, "/wp-login.php", Scanner); + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + } + + using var banned = await GetAsync(f, "/anything", Scanner); + Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); + Assert.True(banned.Headers.RetryAfter is not null, "a ban must tell the client how long it lasts"); + + var body = await JsonAsync(banned); + Assert.Equal("blocked_by_policy", body.GetProperty("error").GetString()); + Assert.Contains("consecutive refusals", body.GetProperty("reason").GetString()); + + using var bystander = await GetAsync(f, "/anything", Bystander); + Assert.Equal(HttpStatusCode.NotFound, bystander.StatusCode); + } + + [Fact] + public async Task Observe_mode_records_the_ban_it_would_have_made_and_blocks_nobody() + { + await using var f = new EdgeFixture(mode: "Observe", threshold: 3); + + for (var i = 0; i < 6; i++) + { + using var probe = await GetAsync(f, "/.env", Scanner); + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + } + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "candidate_ban").ToListAsync(); + + Assert.NotEmpty(alerts); + Assert.Contains("not enforced", alerts[0].Detail); + Assert.Empty(await db.Blocks.Where(b => b.Source == BlockSource.Engine).ToListAsync()); + } + + [Fact] + public async Task A_server_error_streak_alerts_and_never_bans_because_a_bad_deploy_must_not_lock_out_visitors() + { + await using var f = new EdgeFixture(threshold: 3); + f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway; + + for (var i = 0; i < 6; i++) + { + using var probe = await GetAsync(f, "/checkout", Scanner); + Assert.Equal(HttpStatusCode.BadGateway, probe.StatusCode); + } + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + Assert.NotEmpty(await db.Alerts.AsNoTracking().Where(a => a.Kind == "server_error_streak").ToListAsync()); + Assert.Empty(await db.Blocks.AsNoTracking().ToListAsync()); + } + + [Fact] + public async Task An_operator_block_answers_301_and_survives_clearing_the_engine_bans() + { + await using var f = new EdgeFixture(threshold: 2); + + // First let the engine ban somebody, so there is something to clear. + for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); + using (var banned = await GetAsync(f, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); + + var client = f.Client; + using (var created = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", + new { ip = Bystander, reason = "operator: confirmed scraper", redirectTo = "https://honeypot.example.org/" })) + { + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + } + + using (var blocked = await GetAsync(f, "/anything", Bystander)) + { + Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); + Assert.Equal("https://honeypot.example.org/", blocked.Headers.Location?.ToString()); + } + + using (var cleared = await client.DeleteAsync($"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) + { + var payload = await JsonAsync(cleared); + Assert.True(payload.GetProperty("deleted").GetInt32() >= 1); + } + + using (var stillBlocked = await GetAsync(f, "/anything", Bystander)) + Assert.Equal(HttpStatusCode.MovedPermanently, stillBlocked.StatusCode); + + using (var unblocked = await GetAsync(f, "/anything", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, unblocked.StatusCode); + } + + [Fact] + public async Task The_allowlist_outranks_an_operator_block() + { + await using var f = new EdgeFixture(); + var client = f.Client; + + using (var allow = await client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", + new { match = "203.0.113.0/24", note = "office" })) + Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); + + using (var block = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Scanner, reason = "oops" })) + Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); + + using var request = await GetAsync(f, "/anything", Scanner); + Assert.Equal(HttpStatusCode.NotFound, request.StatusCode); + } + + [Fact] + public async Task A_blocked_operator_can_still_reach_the_admin_api() + { + await using var f = new EdgeFixture(); + var client = f.Client; + + using (var block = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Scanner, reason = "self-inflicted" })) + Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); + + using (var publicSide = await GetAsync(f, "/", Scanner)) + Assert.Equal(HttpStatusCode.MovedPermanently, publicSide.StatusCode); + + using var admin = await GetAsync(f, "/admin-api/blocks", Scanner, token: EdgeFixture.AdminToken); + Assert.Equal(HttpStatusCode.OK, admin.StatusCode); + } + + [Fact] + public async Task The_admin_surface_is_closed_until_a_token_is_configured_and_sent() + { + await using var f = new EdgeFixture(); + + using (var anonymous = await f.Client.GetAsync("/admin-api/blocks")) + Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); + + using (var authorized = await f.Client.GetAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}")) + Assert.Equal(HttpStatusCode.OK, authorized.StatusCode); + + await using var noToken = new EdgeFixture(); + // A fixture without a token would be an open admin API; the fixture + // always sets one, so assert the guard's shape instead: a wrong token + // is refused exactly like no token at all. + using (var wrong = await noToken.Client.GetAsync("/admin-api/blocks?token=nope")) + Assert.Equal(HttpStatusCode.Unauthorized, wrong.StatusCode); + } + + [Fact] + public async Task A_ban_lifts_itself_when_it_expires() + { + await using var f = new EdgeFixture(threshold: 2, banDuration: "00:00:02"); + + for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); + using (var banned = await GetAsync(f, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); + + await Task.Delay(TimeSpan.FromSeconds(3)); + + using var afterExpiry = await GetAsync(f, "/probe", Scanner); + Assert.Equal(HttpStatusCode.NotFound, afterExpiry.StatusCode); + } + + [Fact] + public async Task Switching_the_engine_off_stops_enforcement_and_touches_no_rows() + { + await using var f = new EdgeFixture(threshold: 2); + + for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); + using (var banned = await GetAsync(f, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); + + var client = f.Client; + using (var off = await client.PutAsJsonAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}", new { mode = "Off" })) + { + Assert.Equal(HttpStatusCode.OK, off.StatusCode); + Assert.Equal("Off", (await JsonAsync(off)).GetProperty("mode").GetString()); + } + + using (var passing = await GetAsync(f, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, passing.StatusCode); + + using (var list = await client.GetAsync($"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) + Assert.True((await JsonAsync(list)).GetArrayLength() >= 1, "turning the toggle off must not erase the ban record"); + } + + [Fact] + public async Task A_denied_country_is_rejected_with_451_and_an_allow_entry_still_gets_through() + { + await using var f = new EdgeFixture(geo: "DenyList"); + var client = f.Client; + + using (var deny = await client.PutAsync("/admin-api/countries/DE?allowed=false&token=" + EdgeFixture.AdminToken, null)) + Assert.Equal(HttpStatusCode.NoContent, deny.StatusCode); + + using (var rejected = await GetAsync(f, "/anything", Scanner, country: "DE")) + { + Assert.Equal((HttpStatusCode)451, rejected.StatusCode); + var body = await JsonAsync(rejected); + Assert.Equal("region_not_supported", body.GetProperty("error").GetString()); + Assert.False(string.IsNullOrWhiteSpace(body.GetProperty("note").GetString())); + } + + using (var uncountryd = await GetAsync(f, "/anything", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, uncountryd.StatusCode); + + using (var allow = await client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", new { match = Scanner, note = "customer behind a VPN" })) + Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); + + using var allowed = await GetAsync(f, "/anything", Scanner, country: "DE"); + Assert.Equal(HttpStatusCode.NotFound, allowed.StatusCode); + } + + [Fact] + public async Task Observations_are_persisted_once_per_source_not_once_per_request() + { + await using var f = new EdgeFixture(threshold: 1000); + + for (var i = 0; i < 500; i++) (await GetAsync(f, $"/probe-{i}", Scanner)).Dispose(); + await f.FlushObservationsAsync(); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var rows = await db.Observations.AsNoTracking().Where(o => o.SourceKey == Scanner).ToListAsync(); + + Assert.Single(rows); + Assert.Equal(500, rows[0].TotalRefusals); + Assert.Equal(500, f.Upstream.RequestCount); + } + + [Fact] + public async Task Rotating_ipv6_addresses_inside_one_allocation_are_one_source() + { + await using var f = new EdgeFixture(threshold: 3); + + using (var first = await GetAsync(f, "/probe", "2001:db8:1234:5678::11")) + Assert.Equal(HttpStatusCode.NotFound, first.StatusCode); + using (var second = await GetAsync(f, "/probe", "2001:db8:1234:5678::22")) + Assert.Equal(HttpStatusCode.NotFound, second.StatusCode); + using (var third = await GetAsync(f, "/probe", "2001:db8:1234:5678:0:0:0:33")) + Assert.Equal(HttpStatusCode.NotFound, third.StatusCode); + + using var fourth = await GetAsync(f, "/probe", "2001:db8:1234:5678::ff"); + Assert.Equal(HttpStatusCode.Forbidden, fourth.StatusCode); + + using var neighbour = await GetAsync(f, "/probe", "2001:db8:1234:5679::11"); + Assert.Equal(HttpStatusCode.NotFound, neighbour.StatusCode); + } +} + +public sealed class EdgeObservationBoundaryTests +{ + private const string Operator = "203.0.113.20"; + + private static async Task GetAsync( + EdgeFixture f, string path, string sourceIp, string? token = null) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + return await f.Client.SendAsync(request); + } + + [Fact] + public async Task Fumbling_the_admin_api_never_bans_the_operator_who_is_fumbling_it() + { + await using var f = new EdgeFixture(threshold: 2); + + // Six refusals on the recovery hatch — a wrong token, a missing + // parameter. If these counted, the admin's own syntax error would be + // the thing that locks them out. + for (var i = 0; i < 6; i++) + { + using var refused = await GetAsync(f, "/admin-api/blocks", Operator); + Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); + } + + using var publicSide = await GetAsync(f, "/anything", Operator); + Assert.Equal(HttpStatusCode.NotFound, publicSide.StatusCode); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await db.Blocks.AsNoTracking().ToListAsync()); + } + + [Fact] + public async Task Two_requests_that_finish_at_the_same_moment_write_one_ban_not_two() + { + await using var f = new EdgeFixture(threshold: 2); + + // The observer runs after the response is written, so the next request + // from the same source can arrive while the ban is still landing. Two + // readers that both see "no ban yet" used to produce a unique-index + // loser and a lost evidence row. + var inParallel = Enumerable.Range(0, 4) + .Select(_ => GetAsync(f, "/probe", Operator)) + .ToArray(); + foreach (var response in await Task.WhenAll(inParallel)) response.Dispose(); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var bans = await db.Blocks.AsNoTracking().Where(b => b.Source == BlockSource.Engine).ToListAsync(); + + Assert.Single(bans); + Assert.Equal(Operator, bans[0].SourceKey); + Assert.False(string.IsNullOrWhiteSpace(bans[0].Reason)); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs new file mode 100644 index 0000000..bea729d --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs @@ -0,0 +1,68 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// One edge instance per test, with its own SQLite file and its own upstream. +/// Isolation is not tidiness here: the streak map and the block table are the +/// things under test, and a shared one would make the assertions about "this +/// source is banned, that one is not" meaningless. +/// +internal sealed class EdgeFixture : IAsyncDisposable +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db"); + + public FakeUpstream Upstream { get; } = FakeUpstream.Start(); + + public WebApplicationFactory Factory { get; } + + public const string AdminToken = "test-admin-token"; + + public EdgeFixture( + string mode = "Enforce", + int threshold = 3, + string streakWindow = "00:05:00", + string banDuration = "01:00:00", + string geo = "Off") + { + Factory = new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseSetting("ConnectionStrings:OpenWaf", $"Data Source={_dbPath}"); + builder.UseSetting("Database:Provider", "sqlite"); + builder.UseSetting("OpenWaf:Admin:Token", AdminToken); + builder.UseSetting("OpenWaf:Policy:Mode", mode); + builder.UseSetting("OpenWaf:Policy:StreakThreshold", threshold.ToString()); + builder.UseSetting("OpenWaf:Policy:StreakWindow", streakWindow); + builder.UseSetting("OpenWaf:Policy:BanDuration", banDuration); + builder.UseSetting("OpenWaf:Policy:Geo", geo); + // The only way to give a TestServer request a source address is a + // header, so these tests exercise the trusted-proxy path too. + builder.UseSetting("OpenWaf:Policy:TrustProxyHeaders", "true"); + builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address); + }); + } + + public HttpClient Client => Factory.CreateClient(); + + public T Service() where T : notnull => Factory.Services.GetRequiredService(); + + public async Task FlushObservationsAsync() => await Service().FlushAsync(CancellationToken.None); + + public async Task SendAsync(HttpClient client, string path, string sourceIp) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); + using var response = await client.SendAsync(request); + } + + public async ValueTask DisposeAsync() + { + await Factory.DisposeAsync(); + Upstream.RequestCount = 0; + await Upstream.DisposeAsync(); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + if (File.Exists(_dbPath)) File.Delete(_dbPath); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/FakeUpstream.cs b/dotnet/OpenWaf.Tests.Integration/FakeUpstream.cs new file mode 100644 index 0000000..ea8a14e --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/FakeUpstream.cs @@ -0,0 +1,76 @@ +using System.Net; +using System.Net.Sockets; +using Microsoft.AspNetCore.Http; + +namespace OpenWaf.Tests.Integration; + +/// +/// The application behind the edge. It is deliberately dumb: it answers a +/// configured status per path and counts what it was asked. The whole point of +/// the feature is the edge reacting to what the upstream answered, so the test +/// needs to control that answer and observe whether the edge noticed. +/// +internal sealed class FakeUpstream : IAsyncDisposable +{ + private readonly HttpListener _listener = new(); + private readonly CancellationTokenSource _cts = new(); + + public string Address { get; } + public int RequestCount; + public List Paths = []; + + /// What this upstream answers for a path. + public Func StatusFor { get; set; } = _ => StatusCodes.Status404NotFound; + + public static FakeUpstream Start() + { + var port = FreePort(); + var upstream = new FakeUpstream($"http://127.0.0.1:{port}/"); + upstream._listener.Start(); + _ = upstream.LoopAsync(); + return upstream; + } + + private FakeUpstream(string address) + { + Address = address; + _listener.Prefixes.Add(address); + } + + private async Task LoopAsync() + { + try + { + while (!_cts.IsCancellationRequested) + { + var context = await _listener.GetContextAsync(); + var path = context.Request.Url?.AbsolutePath ?? "/"; + Interlocked.Increment(ref RequestCount); + lock (Paths) Paths.Add(path); + + context.Response.StatusCode = StatusFor(path); + context.Response.OutputStream.Close(); + } + } + catch + { + // Listener closed at teardown — the expected way out. + } + } + + private static int FreePort() + { + var probe = new TcpListener(IPAddress.Loopback, 0); + probe.Start(); + var port = ((IPEndPoint)probe.LocalEndpoint).Port; + probe.Stop(); + return port; + } + + public async ValueTask DisposeAsync() + { + _cts.Cancel(); + _listener.Close(); + await Task.CompletedTask; + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj b/dotnet/OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj new file mode 100644 index 0000000..1a021ef --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + diff --git a/dotnet/OpenWaf.Tests.Unit/DecisionEngineTests.cs b/dotnet/OpenWaf.Tests.Unit/DecisionEngineTests.cs new file mode 100644 index 0000000..d695c06 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/DecisionEngineTests.cs @@ -0,0 +1,184 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +public sealed class DecisionEngineTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + + private static BlockEntry Manual(string key, string? redirect = null, DateTimeOffset? expires = null) => new() + { + SourceKey = key, + Source = BlockSource.Operator, + CreatedAt = Now.AddHours(-3), + ExpiresAt = expires, + RedirectTo = redirect, + Reason = "operator: repeated scraping" + }; + + private static BlockEntry Ban(string key, DateTimeOffset expires) => new() + { + SourceKey = key, + Source = BlockSource.Engine, + CreatedAt = Now.AddMinutes(-1), + ExpiresAt = expires, + Reason = "10 consecutive refusals (400-499) within 5 min; last 404 /wp-login.php" + }; + + private static EdgeSnapshot Snapshot( + EdgePolicy policy, + IReadOnlyDictionary? bans = null, + IReadOnlyList? allow = null, + IReadOnlyDictionary? countries = null) => new() + { + GeneratedAt = Now, + Policy = policy, + EngineBans = bans ?? new Dictionary(), + AllowEntries = allow ?? [], + Countries = countries ?? new Dictionary() + }; + + private static Dictionary Map(params BlockEntry[] entries) + => entries.ToDictionary(e => e.SourceKey, StringComparer.Ordinal); + + [Fact] + public void Nothing_matched_passes() + { + var d = DecisionEngine.Decide(Snapshot(EdgePolicy.Default), "203.0.113.9", "/index.html", Now); + Assert.Equal(EdgeVerdict.Pass, d.Verdict); + } + + [Fact] + public void An_engine_ban_is_enforced_only_in_Enforce_mode() + { + var ban = Ban("203.0.113.9", Now.AddMinutes(30)); + + foreach (var mode in new[] { EnforcementMode.Off, EnforcementMode.Observe }) + { + var snapshot = Snapshot(new EdgePolicy { Mode = mode }, Map(ban)); + Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now).Verdict); + } + + var enforcing = Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, Map(ban)); + var decision = DecisionEngine.Decide(enforcing, "203.0.113.9", "/x", Now); + + Assert.Equal(EdgeVerdict.BlockEngine, decision.Verdict); + Assert.Equal(403, decision.StatusCode); + Assert.Contains("consecutive refusals", decision.Reason); + Assert.Equal(ban.ExpiresAt, decision.ExpiresAt); + } + + [Fact] + public void An_expired_ban_stops_blocking_without_anyone_deleting_it() + { + var snapshot = Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, Map(Ban("203.0.113.9", Now.AddMinutes(-1)))); + Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now).Verdict); + } + + [Fact] + public void An_operator_block_never_expires_and_answers_301_by_default() + { + var snapshot = Snapshot(EdgePolicy.Default, allow: []) with + { + OperatorBlocks = Map(Manual("203.0.113.9")) + }; + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now); + + Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict); + Assert.Equal(301, decision.StatusCode); + Assert.False(string.IsNullOrWhiteSpace(decision.Location)); + } + + [Fact] + public void A_per_entry_redirect_overrides_the_kind_default() + { + var snapshot = Snapshot(EdgePolicy.Default) with + { + OperatorBlocks = Map(Manual("203.0.113.9", "https://example.net/honeypot")) + }; + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now); + Assert.Equal("https://example.net/honeypot", decision.Location); + } + + [Fact] + public void The_allowlist_beats_an_operator_block_a_ban_and_a_geo_deny_together() + { + var policy = new EdgePolicy { Mode = EnforcementMode.Enforce, Geo = GeoMode.DenyList }; + var snapshot = new EdgeSnapshot + { + GeneratedAt = Now, + Policy = policy, + OperatorBlocks = Map(Manual("203.0.113.9")), + EngineBans = Map(Ban("203.0.113.9", Now.AddMinutes(30))), + AllowEntries = [new AllowEntry { Match = "203.0.113.0/24", Note = "office" }], + Countries = new Dictionary { ["UA"] = new() { Code = "UA", IsAllowed = false } } + }; + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now, "UA"); + + Assert.Equal(EdgeVerdict.PassAllowlisted, decision.Verdict); + Assert.Equal("office", decision.Reason); + } + + [Fact] + public void An_expired_allow_entry_stops_exempting() + { + var snapshot = Snapshot(EdgePolicy.Default, allow: + [new AllowEntry { Match = "203.0.113.9", ExpiresAt = Now.AddMinutes(-1) }]) with + { + OperatorBlocks = Map(Manual("203.0.113.9")) + }; + + Assert.Equal(EdgeVerdict.BlockOperator, DecisionEngine.Decide(snapshot, "203.0.113.9", "/x", Now).Verdict); + } + + [Fact] + public void Deny_list_rejects_with_451_and_allow_list_rejects_everything_else() + { + var countries = new Dictionary { ["DE"] = new() { Code = "DE", IsAllowed = false } }; + + var deny = DecisionEngine.Decide( + Snapshot(new EdgePolicy { Geo = GeoMode.DenyList }, countries: countries), "203.0.113.9", "/x", Now, "DE"); + Assert.Equal(EdgeVerdict.GeoReject, deny.Verdict); + Assert.Equal(451, deny.StatusCode); + + var allowList = DecisionEngine.Decide( + Snapshot(new EdgePolicy { Geo = GeoMode.AllowList }, countries: countries), "203.0.113.9", "/x", Now, "FR"); + Assert.Equal(EdgeVerdict.GeoReject, allowList.Verdict); + } + + [Fact] + public void Geo_off_never_rejects_even_when_a_country_is_denied() + { + var countries = new Dictionary { ["DE"] = new() { Code = "DE", IsAllowed = false } }; + var decision = DecisionEngine.Decide( + Snapshot(new EdgePolicy { Geo = GeoMode.Off }, countries: countries), "203.0.113.9", "/x", Now, "DE"); + + Assert.Equal(EdgeVerdict.Pass, decision.Verdict); + } + + [Theory] + [InlineData("/admin-api/blocks")] + [InlineData("/healthz")] + [InlineData("/readyz")] + [InlineData("/openapi/v1.json")] + public void The_recovery_hatch_stays_open_for_a_self_blocked_operator(string path) + { + var snapshot = Snapshot(EdgePolicy.Default) with { OperatorBlocks = Map(Manual("203.0.113.9")) }; + Assert.Equal(EdgeVerdict.PassBypassed, DecisionEngine.Decide(snapshot, "203.0.113.9", path, Now).Verdict); + } + + [Fact] + public void A_blocked_ipv6_source_is_matched_on_its_sixty_four_not_its_address() + { + var ban = Ban("2001:db8:1234:5678::/64", Now.AddMinutes(30)); + var snapshot = Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, Map(ban)); + + Assert.Equal(EdgeVerdict.BlockEngine, DecisionEngine.Decide(snapshot, "2001:db8:1234:5678::cafe", "/x", Now).Verdict); + Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "2001:db8:4321:8765::cafe", "/x", Now).Verdict); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj b/dotnet/OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj new file mode 100644 index 0000000..0a06de6 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + diff --git a/dotnet/OpenWaf.Tests.Unit/SourceKeyTests.cs b/dotnet/OpenWaf.Tests.Unit/SourceKeyTests.cs new file mode 100644 index 0000000..b8a2430 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/SourceKeyTests.cs @@ -0,0 +1,69 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Tests.Unit; + +public sealed class SourceKeyTests +{ + private static readonly EdgePolicy Policy = new(); + + [Fact] + public void Ipv4_is_its_own_source_by_default() + { + Assert.Equal("203.0.113.7", SourceKey.For("203.0.113.7", Policy)); + } + + [Fact] + public void Ipv6_addresses_inside_one_sixty_four_collapse_to_one_source() + { + var a = SourceKey.For("2001:db8:1234:5678::1", Policy); + var b = SourceKey.For("2001:db8:1234:5678:dead:beef:cafe:1", Policy); + + Assert.Equal(a, b); + Assert.Equal("2001:db8:1234:5678::/64", a); + } + + [Fact] + public void Different_ipv6_sixty_fours_stay_different_sources() + { + Assert.NotEqual(SourceKey.For("2001:db8:1234:5678::1", Policy), + SourceKey.For("2001:db8:1234:5679::1", Policy)); + } + + [Fact] + public void Ipv4_mapped_ipv6_is_the_same_source_as_the_ipv4() + { + Assert.Equal(SourceKey.For("203.0.113.7", Policy), SourceKey.For("::ffff:203.0.113.7", Policy)); + } + + [Fact] + public void A_wider_ipv6_prefix_groups_more_of_the_allocation() + { + var policy = Policy with { Ipv6KeyPrefixLength = 48 }; + Assert.Equal(SourceKey.For("2001:db8:1234:5678::1", policy), + SourceKey.For("2001:db8:1234:7777::1", policy)); + } + + [Fact] + public void Garbage_does_not_become_a_source_key_that_can_be_matched() + { + Assert.Equal("invalid:not-an-ip", SourceKey.For("not-an-ip", Policy)); + } + + [Theory] + [InlineData("198.51.100.24", "198.51.100.0/24", true)] + [InlineData("198.51.100.24", "198.51.100.24", true)] + [InlineData("198.51.101.24", "198.51.100.0/24", false)] + [InlineData("2001:db8:ff00::1", "2001:db8:ff00::/48", true)] + [InlineData("2001:db8:ff01::1", "2001:db8:ff00::/48", false)] + [InlineData("::ffff:198.51.100.24", "198.51.100.0/24", true)] + public void Allowlist_matching(string address, string match, bool expected) + => Assert.Equal(expected, NetworkMatch.Matches(address, match)); + + [Fact] + public void Masking_zeroes_only_the_host_part() + { + Assert.Equal("198.51.100.0", SourceKey.Mask(System.Net.IPAddress.Parse("198.51.100.24"), 24).ToString()); + Assert.Equal("198.51.96.0", SourceKey.Mask(System.Net.IPAddress.Parse("198.51.100.24"), 19).ToString()); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/StreakTrackerTests.cs b/dotnet/OpenWaf.Tests.Unit/StreakTrackerTests.cs new file mode 100644 index 0000000..945d84e --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/StreakTrackerTests.cs @@ -0,0 +1,121 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Tests.Unit; + +public sealed class StreakTrackerTests +{ + private static readonly DateTimeOffset T0 = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + private static readonly EdgePolicy Policy = new() { StreakThreshold = 3, StreakWindow = TimeSpan.FromMinutes(5) }; + + private static StreakOutcome Refusal(StreakTracker t, string key, DateTimeOffset at, int status = 404) + => t.Observe(key, status, ResponseClass.Refusal, Policy, at); + + [Fact] + public void Three_refusals_in_a_row_ban() + { + var t = new StreakTracker(); + Assert.False(Refusal(t, "1.1.1.1", T0).BanTriggered); + Assert.False(Refusal(t, "1.1.1.1", T0.AddSeconds(10)).BanTriggered); + Assert.True(Refusal(t, "1.1.1.1", T0.AddSeconds(20)).BanTriggered); + } + + [Fact] + public void A_gap_longer_than_the_window_restarts_the_streak() + { + var t = new StreakTracker(); + Refusal(t, "1.1.1.1", T0); + Refusal(t, "1.1.1.1", T0.AddMinutes(1)); + var afterGap = Refusal(t, "1.1.1.1", T0.AddMinutes(1).AddMinutes(6)); + + Assert.Equal(1, afterGap.ConsecutiveRefusals); + Assert.False(afterGap.BanTriggered); + } + + [Fact] + public void A_successful_response_resets_the_streak_because_pidryad_means_consecutive() + { + var t = new StreakTracker(); + Refusal(t, "1.1.1.1", T0); + Refusal(t, "1.1.1.1", T0.AddSeconds(1)); + t.Observe("1.1.1.1", 200, ResponseClass.Neutral, Policy, T0.AddSeconds(2)); + + Assert.False(Refusal(t, "1.1.1.1", T0.AddSeconds(3)).BanTriggered); + } + + [Fact] + public void A_run_of_server_errors_alerts_and_never_bans() + { + var t = new StreakTracker(); + StreakOutcome last = default; + for (var i = 0; i < 10; i++) + { + last = t.Observe("1.1.1.1", 502, ResponseClass.ServerError, Policy, T0.AddSeconds(i)); + } + + Assert.True(last.AlertTriggered); + Assert.False(last.BanTriggered); + } + + [Fact] + public void A_server_error_does_not_extend_a_refusal_streak() + { + var t = new StreakTracker(); + Refusal(t, "1.1.1.1", T0); + t.Observe("1.1.1.1", 500, ResponseClass.ServerError, Policy, T0.AddSeconds(1)); + var next = Refusal(t, "1.1.1.1", T0.AddSeconds(2)); + + Assert.Equal(2, next.ConsecutiveRefusals); + } + + [Fact] + public void Sources_are_counted_separately() + { + var t = new StreakTracker(); + Refusal(t, "1.1.1.1", T0); + Refusal(t, "1.1.1.1", T0.AddSeconds(1)); + var other = Refusal(t, "2.2.2.2", T0.AddSeconds(2)); + + Assert.False(other.BanTriggered); + Assert.Equal(1, other.ConsecutiveRefusals); + } + + [Fact] + public void The_map_is_bounded_so_a_scanner_cannot_grow_the_process() + { + var policy = Policy with { MaxTrackedSources = 100 }; + var t = new StreakTracker(); + t.Configure(policy); + + for (var i = 0; i < 5_000; i++) + { + t.Observe($"10.0.{i / 256}.{i % 256}", 404, ResponseClass.Refusal, policy, T0); + } + + Assert.True(t.TrackedCount <= 100, $"tracked {t.TrackedCount}"); + } + + [Fact] + public void Idle_states_age_out() + { + var policy = Policy with { StateIdleTtl = TimeSpan.FromMinutes(1) }; + var t = new StreakTracker(); + t.Observe("1.1.1.1", 404, ResponseClass.Refusal, policy, T0); + + t.Snapshot(T0.AddMinutes(2), policy); + + Assert.Equal(0, t.TrackedCount); + } + + [Fact] + public void Snapshots_are_copies_not_live_state() + { + var t = new StreakTracker(); + Refusal(t, "1.1.1.1", T0); + var before = t.Peek("1.1.1.1")!; + Refusal(t, "1.1.1.1", T0.AddSeconds(1)); + + Assert.Equal(1, before.TotalRefusals); + Assert.Equal(2, t.Peek("1.1.1.1")!.TotalRefusals); + } +} diff --git a/dotnet/OpenWaf.slnx b/dotnet/OpenWaf.slnx new file mode 100644 index 0000000..e65dee7 --- /dev/null +++ b/dotnet/OpenWaf.slnx @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet/global.json b/dotnet/global.json new file mode 100644 index 0000000..d46d21e --- /dev/null +++ b/dotnet/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} diff --git a/research/2026-09-30-inference-bench/RESULTS.md b/research/2026-09-30-inference-bench/RESULTS.md new file mode 100644 index 0000000..0e603a7 --- /dev/null +++ b/research/2026-09-30-inference-bench/RESULTS.md @@ -0,0 +1,88 @@ +# Inference speed test — 2026-09-30 + +Target: the server this Codex session is actually wired to (read from +`$CODEX_HOME/connection.json`, not hardcoded): + +| | | +|---|---| +| backend | Strata (llama.cpp-family engine), managed, `http://192.168.1.196:8080` | +| model | `qwen3.8-flash-next-iq3_s` (Flash-Next GSQ-RCO IQ3_S), text+image in | +| context | 262 144 tok, **1 slot**, KV int8, speculative decoding on | +| host | remote RTX 5090 box over LAN; `/health` RTT 12–23 ms | + +## 1. Synthetic probe (`bench_inference.py`) + +Cold prefill (unique prompt each time, so no prefix cache): + +| prompt tokens | prefill | TTFT | +|---|---|---| +| 4 226 | 3 970 t/s | 1.11 s | +| 13 949 | 3 881 t/s | 3.70 s | +| 34 778 | 4 095 t/s | 8.64 s | + +Prefix cache: same 34 778-token prompt twice → 34 772 tokens cached, +**TTFT 8.6 s → 0.25 s**, total 8.7 s → 3.0 s. + +## 2. Decode matrix (`bench_matrix.py`, 400 tok out, interleaved, min / median) + +| condition | server t/s | client t/s (SSE) | TTFT | draft accepted | +|---|---|---|---|---| +| tiny ctx, thinking off | 34 / 59 | 23 / 39 | 0.15 s | 68 % | +| tiny ctx, thinking on | 54 / 78 | 53 / 78 | 0.34 s | 78 % | +| 35 k ctx, thinking off | 66 / 83 | 56 / 70 | 6.68 s | 74 % | +| 35 k ctx, thinking on | 52 / 79 | 52 / 79 | 6.75 s | 72 % | + +Best single runs in the same session reached **178 t/s** (tiny ctx) and +**144 t/s** (35 k ctx). Highly repetitive output (counting, plain lists) with +83 % draft acceptance reached **163–197 t/s**; free-form prose sits at 50–90 t/s. +Thinking on/off is **not** the deciding variable — draft acceptance and output +repetitiveness are. + +## 3. Real agent workload (26 completed requests, this session's bridge metrics) + +Context grew 22 k → 60 k tokens over the session. + +| metric | min | median | max | +|---|---|---|---| +| input tokens | 22 262 | 47 929 | 60 614 | +| output tokens | 85 | 493 | 3 838 | +| TTFT | 0.8 s | 9.6 s | 151.3 s* | +| cold prefill | — | 4 928 t/s | 5 796 t/s | +| decode | 26.8 t/s | 47.2 t/s | 128.4 t/s | +| draft accepted | 57 % | 67 % | 84 % | + +Cached-prefix requests (the normal case while iterating in one session) start in +**1.0–3.6 s**; a cold 50–60 k-token prompt costs **10–19 s** before the first token. + +\* the 151 s TTFT outlier is my own session queued behind a benchmark request — see caveats. + +## Caveats + +* **One slot, shared with the agent.** Every benchmark request competes with this + session's own requests, and each of my turns re-prefills a 35–60 k-token + conversation. That is what produced the 12–36 t/s readings in the first pass. + `bench_matrix.py` interleaves conditions and reports min-of-4 as the + uncontended figure; treat medians as "with contention". +* Reasoning/`reasoning_content` deltas are counted as generated tokens — the + model thinks by default, so `out` includes thinking. +* Server-side `predicted_per_second` is consistently a bit above the client-side + SSE rate (chunking + LAN); the client number is what a human perceives. + +## Verdict + +Usable and fast for a 27B IQ3_S at 262 k context: **~5 k tok/s prefill**, +**~50–90 tok/s decode typical**, up to **~180 tok/s** on repetitive output, +**sub-second TTFT whenever the prefix cache hits**. The weak point is cold +long-context starts: at 50–60 k tokens uncached you wait 10–19 s for token one, +so keeping the session warm (avoiding auto-compaction / model switches mid-task) +matters more than raw decode speed. + +## Re-run + +```sh +python3 bench_inference.py # prefill + cache + decode sweep (~3 min) +python3 bench_matrix.py # 2x2 decode matrix, interleaved (~3 min) +``` +Both read endpoint/key from `$CODEX_HOME/connection.json` and write +`bench_*.json` / `bench_*.log` next to the script. Run them from a session that +is **not** doing other work, or the single slot will contaminate the numbers. diff --git a/research/2026-09-30-inference-bench/bench_decode.json b/research/2026-09-30-inference-bench/bench_decode.json new file mode 100644 index 0000000..b99249a --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_decode.json @@ -0,0 +1,118 @@ +{ + "warm": [ + { + "out": 277, + "in": 19, + "cached": 0, + "ttft_s": 0.181, + "total_s": 9.043, + "decode_tps": 31.2, + "client_tps": 20.8, + "draft_acc": 78, + "busy": false + }, + { + "out": 267, + "in": 19, + "cached": 12, + "ttft_s": 0.069, + "total_s": 1.688, + "decode_tps": 163.6, + "client_tps": 109.3, + "draft_acc": 83, + "busy": false + }, + { + "out": 271, + "in": 19, + "cached": 12, + "ttft_s": 0.064, + "total_s": 1.431, + "decode_tps": 196.9, + "client_tps": 131.7, + "draft_acc": 81, + "busy": false + }, + { + "out": 271, + "in": 19, + "cached": 12, + "ttft_s": 0.062, + "total_s": 1.441, + "decode_tps": 194.9, + "client_tps": 130.5, + "draft_acc": 78, + "busy": false + } + ], + "thinking": [ + { + "out": 400, + "in": 63, + "cached": 0, + "ttft_s": 0.482, + "total_s": 11.608, + "decode_tps": 35.9, + "client_tps": 35.3, + "draft_acc": 72, + "busy": false + }, + { + "out": 400, + "in": 63, + "cached": 58, + "ttft_s": 0.056, + "total_s": 11.083, + "decode_tps": 36.2, + "client_tps": 36.1, + "draft_acc": 62, + "busy": false + } + ], + "ctx35k": [ + { + "out": 130, + "in": 38493, + "cached": 0, + "ttft_s": 6.673, + "total_s": 9.088, + "decode_tps": 55.6, + "client_tps": 36.0, + "draft_acc": 59, + "busy": false + }, + { + "out": 129, + "in": 38493, + "cached": 38486, + "ttft_s": 0.176, + "total_s": 10.443, + "decode_tps": 12.9, + "client_tps": 8.4, + "draft_acc": 66, + "busy": false + }, + { + "out": 129, + "in": 38493, + "cached": 38486, + "ttft_s": 0.173, + "total_s": 5.757, + "decode_tps": 23.1, + "client_tps": 15.4, + "draft_acc": 66, + "busy": false + } + ], + "idle": { + "out": 129, + "in": 22, + "cached": 0, + "ttft_s": 0.237, + "total_s": 4.266, + "decode_tps": 31.9, + "client_tps": 21.6, + "draft_acc": 77, + "busy": false + } +} \ No newline at end of file diff --git a/research/2026-09-30-inference-bench/bench_decode.py b/research/2026-09-30-inference-bench/bench_decode.py new file mode 100644 index 0000000..46da7f3 --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_decode.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Decode-only probe: warm vs cold GPU, short vs 35k context, thinking on/off.""" +import json, os, statistics, time, urllib.request +CH = os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")) +c = json.load(open(os.path.join(CH, "connection.json"))) +BASE = c["url"].rstrip("/")[:-3] if c["url"].rstrip("/").endswith("/v1") else c["url"].rstrip("/") +KEY = open(os.path.expanduser(c["key_file"])).read().strip() +MODEL = json.load(urllib.request.urlopen(urllib.request.Request(BASE + "/v1/models", headers={"Authorization": "Bearer " + KEY})))["data"][0]["id"] + +def run(prompt, mx, think=True): + p = {"model": MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": mx, + "temperature": 0.0, "stream": True, "stream_options": {"include_usage": True}, "timings": True} + if not think: + p["chat_template_kwargs"] = {"enable_thinking": False} + busy = any(s.get("is_processing") for s in json.load(urllib.request.urlopen(urllib.request.Request(BASE + "/slots", headers={"Authorization": "Bearer " + KEY})))) + r = urllib.request.Request(BASE + "/v1/chat/completions", data=json.dumps(p).encode(), method="POST", + headers={"Content-Type": "application/json", "Authorization": "Bearer " + KEY}) + t0 = time.perf_counter(); usage = tim = None; n = ttft = last = None; buf = b"" + for raw in urllib.request.urlopen(r, timeout=900): + now = time.perf_counter() - t0; buf += raw + while b"\n" in buf: + line, buf = buf.split(b"\n", 1); line = line.strip() + if not line.startswith(b"data:"): continue + blob = line[5:].strip() + if blob in (b"", b"[DONE]"): continue + try: o = json.loads(blob) + except Exception: continue + usage = o.get("usage") or usage; tim = o.get("timings") or tim + for ch in o.get("choices", []): + d = ch.get("delta") or {}; piece = (d.get("content") or "") + (d.get("reasoning_content") or "") + if piece: + n = 0 if n is None else n + 1 + ttft = now if ttft is None else ttft; last = now + u, t = usage or {}, tim or {} + row = {"out": u.get("completion_tokens"), "in": u.get("prompt_tokens"), "cached": (u.get("prompt_tokens_details") or {}).get("cached_tokens"), + "ttft_s": round(ttft, 3) if ttft else None, "total_s": round(time.perf_counter() - t0, 3), + "decode_tps": round(t.get("predicted_per_second"), 1) if t else None, + "client_tps": round((n - 1) / (last - ttft), 1) if n and n > 1 and ttft is not None and last and last > ttft else None, + "draft_acc": round(100 * t["draft_n_accepted"] / t["draft_n"]) if t and t.get("draft_n") else None, "busy": busy} + print(f" {row['in']:>6} tok ctx | out={row['out']:>4} | ttft={row['ttft_s']:>6} | decode={row['decode_tps']:>6} t/s | client={row['client_tps']:>6} t/s | draft={row['draft_acc']}%" + (" BUSY" if busy else "")) + return row + +def filler(w, s): + ws = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu".split() + return " ".join([f"p{s}"] + [ws[(i + s * 7) % len(ws)] for i in range(w)]) + +print("warm-up") +run("Warm up.", 32, False) +print("\nwarm back-to-back, tiny ctx, thinking off (4x300)") +warm = [run("List animals, one per line.", 300, False) for _ in range(4)] +print("\nthinking on, tiny ctx (2x400)") +th = [run("Explain why the sky is blue, in detail.", 400) for _ in range(2)] +print("\nbuild ~35k-token context, then decode on top of it (3x300)") +big = filler(25000, 9) + "\nReply OK." +run(big, 8) +ctx = [run(big + "\nNow list 40 animals, one per line.", 300, False) for _ in range(3)] +print("\nGPU idle 75s, then one request (cold-cache penalty)") +time.sleep(75) +cold = run("List 40 birds, one per line.", 300, False) +def m(rs, k): + v = [r[k] for r in rs if isinstance(r.get(k), (int, float))] + return round(statistics.median(v), 1) if v else None +print("\n=== summary (median) ===") +print(f"warm tiny-ctx decode {m(warm,'decode_tps')} t/s server | {m(warm,'client_tps')} t/s client | ttft {m(warm,'ttft_s')}s") +print(f"thinking-on decode {m(th,'decode_tps')} t/s server | {m(th,'client_tps')} t/s client | ttft {m(th,'ttft_s')}s") +print(f"35k-context decode {m(ctx,'decode_tps')} t/s server | {m(ctx,'client_tps')} t/s client | ttft {m(ctx,'ttft_s')}s") +print(f"after 75s idle decode {cold['decode_tps']} t/s | ttft {cold['ttft_s']}s") +json.dump({"warm": warm, "thinking": th, "ctx35k": ctx, "idle": cold}, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "bench_decode.json"), "w"), indent=2) diff --git a/research/2026-09-30-inference-bench/bench_inference.json b/research/2026-09-30-inference-bench/bench_inference.json new file mode 100644 index 0000000..da80fa3 --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_inference.json @@ -0,0 +1,222 @@ +{ + "model": "qwen3.8-flash-next-iq3_s", + "base": "http://192.168.1.196:8080", + "runs": [ + { + "label": "decode-512-1", + "slot_busy_before": false, + "ttfb_s": 0.037, + "ttft_s": 2.004, + "total_s": 18.604, + "in": 64, + "cached": 0, + "out": 512, + "reasoning": null, + "sse_tokens": 512, + "prefill_tps": 32.8, + "decode_tps": 40.4, + "client_tps": 30.8, + "e2e_tps": 31.0, + "draft": 451, + "draft_ok": 264 + }, + { + "label": "decode-512-2", + "slot_busy_before": false, + "ttfb_s": 0.021, + "ttft_s": 0.054, + "total_s": 14.919, + "in": 64, + "cached": 59, + "out": 512, + "reasoning": null, + "sse_tokens": 512, + "prefill_tps": 223.2, + "decode_tps": 34.5, + "client_tps": 34.4, + "e2e_tps": 38.6, + "draft": 418, + "draft_ok": 256 + }, + { + "label": "decode-512-3", + "slot_busy_before": true, + "ttfb_s": 0.021, + "ttft_s": 16.691, + "total_s": 30.875, + "in": 64, + "cached": 0, + "out": 512, + "reasoning": null, + "sse_tokens": 512, + "prefill_tps": 193.6, + "decode_tps": 35.7, + "client_tps": 36.0, + "e2e_tps": 18.7, + "draft": 445, + "draft_ok": 275 + }, + { + "label": "decode-1500", + "slot_busy_before": false, + "ttfb_s": 0.023, + "ttft_s": 0.241, + "total_s": 26.431, + "in": 71, + "cached": 0, + "out": 1500, + "reasoning": null, + "sse_tokens": 1500, + "prefill_tps": 352.9, + "decode_tps": 64.6, + "client_tps": 57.2, + "e2e_tps": 59.4, + "draft": 1183, + "draft_ok": 946 + }, + { + "label": "nothink-512-1", + "slot_busy_before": true, + "ttfb_s": 0.028, + "ttft_s": 30.343, + "total_s": 39.427, + "in": 24, + "cached": 0, + "out": 212, + "reasoning": null, + "sse_tokens": 155, + "prefill_tps": 9.4, + "decode_tps": 23.3, + "client_tps": 17.2, + "e2e_tps": 6.0, + "draft": 208, + "draft_ok": 135 + }, + { + "label": "nothink-512-2", + "slot_busy_before": false, + "ttfb_s": 0.02, + "ttft_s": 0.065, + "total_s": 7.834, + "in": 24, + "cached": 17, + "out": 205, + "reasoning": null, + "sse_tokens": 149, + "prefill_tps": 214.7, + "decode_tps": 26.3, + "client_tps": 19.1, + "e2e_tps": 29.2, + "draft": 205, + "draft_ok": 129 + }, + { + "label": "nothink-512-3", + "slot_busy_before": false, + "ttfb_s": 0.012, + "ttft_s": 0.058, + "total_s": 1.549, + "in": 24, + "cached": 17, + "out": 205, + "reasoning": null, + "sse_tokens": 149, + "prefill_tps": 240.5, + "decode_tps": 180.5, + "client_tps": 99.3, + "e2e_tps": 147.9, + "draft": 200, + "draft_ok": 129 + }, + { + "label": "cold-3000w", + "slot_busy_before": false, + "ttfb_s": 0.034, + "ttft_s": 1.108, + "total_s": 1.155, + "in": 4226, + "cached": 0, + "out": 8, + "reasoning": null, + "sse_tokens": 8, + "prefill_tps": 3969.9, + "decode_tps": 147.3, + "client_tps": 152.0, + "e2e_tps": 3667.0, + "draft": 6, + "draft_ok": 6 + }, + { + "label": "cold-10000w", + "slot_busy_before": false, + "ttfb_s": 0.086, + "ttft_s": 3.697, + "total_s": 3.748, + "in": 13949, + "cached": 0, + "out": 8, + "reasoning": null, + "sse_tokens": 8, + "prefill_tps": 3881.0, + "decode_tps": 124.0, + "client_tps": 139.2, + "e2e_tps": 3723.7, + "draft": 7, + "draft_ok": 5 + }, + { + "label": "cold-25000w", + "slot_busy_before": false, + "ttfb_s": 0.124, + "ttft_s": 8.641, + "total_s": 8.688, + "in": 34778, + "cached": 0, + "out": 8, + "reasoning": null, + "sse_tokens": 8, + "prefill_tps": 4095.0, + "decode_tps": 118.9, + "client_tps": 149.4, + "e2e_tps": 4003.8, + "draft": 9, + "draft_ok": 5 + }, + { + "label": "cache-miss", + "slot_busy_before": true, + "ttfb_s": 0.164, + "ttft_s": 39.705, + "total_s": 40.78, + "in": 34777, + "cached": 0, + "out": 8, + "reasoning": null, + "sse_tokens": 8, + "prefill_tps": 4618.1, + "decode_tps": 7.4, + "client_tps": 6.5, + "e2e_tps": 853.0, + "draft": 9, + "draft_ok": 5 + }, + { + "label": "cache-hit", + "slot_busy_before": false, + "ttfb_s": 0.214, + "ttft_s": 0.252, + "total_s": 3.0, + "in": 34777, + "cached": 34772, + "out": 8, + "reasoning": null, + "sse_tokens": 8, + "prefill_tps": 167.8, + "decode_tps": 118.7, + "client_tps": 99.7, + "e2e_tps": 11596.9, + "draft": 9, + "draft_ok": 5 + } + ] +} \ No newline at end of file diff --git a/research/2026-09-30-inference-bench/bench_inference.py b/research/2026-09-30-inference-bench/bench_inference.py new file mode 100644 index 0000000..4c7eb5e --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_inference.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Inference speed probe for the local Strata/llama.cpp server behind codex-qwen. + +Reads endpoint + key from $CODEX_HOME/connection.json, so it always measures the +server the CLI is actually talking to. Stdlib only. + +Per run it reports: + ttft time to first token (reasoning tokens count as tokens - the model thinks) + prefill server-side prompt-eval tok/s (cold prefix vs cached prefix) + decode server-side generation tok/s AND client-side observed tok/s over SSE + draft speculative-decoding drafts issued / accepted + queue slot state sampled just before the request, to spot contention +""" +import json +import os +import statistics +import sys +import time +import urllib.request + +CODEX_HOME = os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")) +MODEL = None + + +def target(): + with open(os.path.join(CODEX_HOME, "connection.json")) as fh: + conn = json.load(fh) + base = conn["url"].rstrip("/") + if base.endswith("/v1"): + base = base[:-3] + key = open(os.path.expanduser(conn["key_file"])).read().strip() if conn.get("key_file") else None + return base, key, conn + + +def get(base, key, path): + req = urllib.request.Request(base + path) + if key: + req.add_header("Authorization", "Bearer " + key) + return json.loads(urllib.request.urlopen(req, timeout=30).read().decode()) + + +def stream_chat(base, key, prompt, max_tokens, thinking=True): + payload = { + "model": MODEL, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": max_tokens, + "temperature": 0.0, + "stream": True, + "stream_options": {"include_usage": True}, + "timings": True, + } + if not thinking: + payload["chat_template_kwargs"] = {"enable_thinking": False} + body = json.dumps(payload).encode() + req = urllib.request.Request(base + "/v1/chat/completions", data=body, method="POST") + req.add_header("Content-Type", "application/json") + if key: + req.add_header("Authorization", "Bearer " + key) + t0 = time.perf_counter() + resp = urllib.request.urlopen(req, timeout=900) + tfb = time.perf_counter() - t0 + usage = timings = None + toks = first_tok = last_tok = None + buf = b"" + for raw in resp: + now = time.perf_counter() - t0 + buf += raw + while b"\n" in buf: + line, buf = buf.split(b"\n", 1) + line = line.strip() + if not line.startswith(b"data:"): + continue # SSE comments (": keep-alive") land here too + blob = line[5:].strip() + if blob in (b"", b"[DONE]"): + continue + try: + obj = json.loads(blob) + except json.JSONDecodeError: + continue + usage = obj.get("usage") or usage + timings = obj.get("timings") or timings + for ch in obj.get("choices", []): + d = ch.get("delta") or {} + piece = (d.get("content") or "") + (d.get("reasoning_content") or "") + if piece: + toks = 0 if toks is None else toks + toks += 1 + if first_tok is None: + first_tok = now + last_tok = now + total = time.perf_counter() - t0 + return tfb, total, toks, first_tok, last_tok, usage, timings + + +def probe(base, key, label, prompt, max_tokens, thinking=True): + busy = any(s.get("is_processing") for s in get(base, key, "/slots")) + tfb, total, toks, ttft, last, usage, tim = stream_chat(base, key, prompt, max_tokens, thinking) + u, t = usage or {}, tim or {} + row = { + "label": label, + "slot_busy_before": busy, + "ttfb_s": round(tfb, 3), + "ttft_s": round(ttft, 3) if ttft is not None else None, + "total_s": round(total, 3), + "in": u.get("prompt_tokens"), + "cached": (u.get("prompt_tokens_details") or {}).get("cached_tokens"), + "out": u.get("completion_tokens"), + "reasoning": (u.get("completion_tokens_details") or {}).get("reasoning_tokens"), + "sse_tokens": toks, + "prefill_tps": round(t.get("prompt_per_second"), 1) if t.get("prompt_per_second") else None, + "decode_tps": round(t.get("predicted_per_second"), 1) if t.get("predicted_per_second") else None, + "client_tps": round((toks - 1) / (last - ttft), 1) if toks and toks > 1 and ttft is not None and last and last > ttft else None, + "e2e_tps": round((u.get("completion_tokens", 0) + u.get("prompt_tokens", 0)) / total, 1) if total else None, + "draft": t.get("draft_n"), + "draft_ok": t.get("draft_n_accepted"), + } + acc = 100.0 * row["draft_ok"] / row["draft"] if row.get("draft") else None + print(f" {label:<16} in={str(row['in']):<6} cached={str(row['cached']):<6} out={str(row['out']):<5} " + f"ttft={str(row['ttft_s']):<7} total={str(row['total_s']):<7} " + f"prefill={str(row['prefill_tps']):<8} decode={str(row['decode_tps']):<7} " + f"client={str(row['client_tps']):<7}" + (f" draft_acc={acc:.0f}%" if acc else "") + + (" [slot was busy]" if busy else "")) + return row + + +def filler(n_words, salt): + words = ("alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike " + "november oscar papa quebec romeo sierra tango uniform victor whiskey xray " + "yankee zulu one two three four five six seven eight nine zero").split() + return " ".join([f"probe{salt}"] + [words[(i + salt * 7) % len(words)] for i in range(n_words)]) + + +def med(rows, k): + vals = [r[k] for r in rows if isinstance(r.get(k), (int, float))] + return round(statistics.median(vals), 1) if vals else None + + +def main(): + global MODEL + base, key, conn = target() + models = get(base, key, "/v1/models")["data"] + MODEL = models[0]["id"] + props = get(base, key, "/props") + print(f"target {base} backend={conn.get('backend')} managed={conn.get('managed')}") + print(f"model {MODEL} n_ctx={models[0].get('meta', {}).get('n_ctx')} " + f"slots={props.get('total_slots')} modalities={models[0].get('architecture', {}).get('input_modalities')}") + lat = [] + for _ in range(5): + t0 = time.perf_counter() + get(base, key, "/health") + lat.append((time.perf_counter() - t0) * 1000) + print(f"network /health rtt min={min(lat):.1f} median={statistics.median(lat):.1f} max={max(lat):.1f} ms") + print(f"note thinking/reasoning is ON by default, so 'out' includes reasoning tokens\n") + + get(base, key, "/health") + stream_chat(base, key, "Warm up.", 16) + + print("decode, thinking on (3 reps x 512 tok out)") + dec = [probe(base, key, f"decode-512-{i+1}", "List every fruit you can think of, one per line.", 512) for i in range(3)] + print("\nlong decode (1500 tok out)") + lng = probe(base, key, "decode-1500", "Count from 1 to 2000, one number per line, nothing else.", 1500) + print("\ndecode, thinking off (3 reps x 512 tok out)") + nothink = [probe(base, key, f"nothink-512-{i+1}", "List every vegetable you can think of, one per line.", 512, thinking=False) for i in range(3)] + + print("\ncold prefill (unique prompt, 8 tok out)") + pre = [probe(base, key, f"cold-{w}w", filler(w, s) + "\nReply OK.", 8) for w, s in ((3000, 1), (10000, 2), (25000, 3))] + + print("\nprefix cache (identical 25000-word prompt twice)") + big = filler(25000, 4) + "\nReply OK." + c1 = probe(base, key, "cache-miss", big, 8) + c2 = probe(base, key, "cache-hit", big, 8) + + rows = dec + [lng] + nothink + pre + [c1, c2] + print("\n=== summary ===") + print(f"decode 512 (thinking on) median {med(dec, 'decode_tps')} t/s server | {med(dec, 'client_tps')} t/s client") + print(f"decode 1500 {lng['decode_tps']} t/s over {lng['out']} tokens") + print(f"decode 512 (thinking off) median {med(nothink, 'decode_tps')} t/s server | {med(nothink, 'client_tps')} t/s client") + print(f"ttft (short prompt) median {med(dec, 'ttft_s')} s") + for r in pre: + print(f"cold prefill {r['in']:>6} tok {r['prefill_tps']:>8} t/s ttft {r['ttft_s']}s") + print(f"prefill 30k cached {c1['in']} tok in {c1['total_s']}s cold -> {c2['total_s']}s warm " + f"({round(c1['total_s'] / c2['total_s'], 1)}x), ttft {c1['ttft_s']}s -> {c2['ttft_s']}s") + acc = [r["draft_ok"] / r["draft"] for r in rows if r.get("draft")] + print(f"draft acceptance median {100 * statistics.median(acc):.0f}% (range {100*min(acc):.0f}-{100*max(acc):.0f}%)") + out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bench_inference.json") + json.dump({"model": MODEL, "base": base, "runs": rows}, open(out, "w"), indent=2) + print(f"\nwrote {out}") + + +if __name__ == "__main__": + main() diff --git a/research/2026-09-30-inference-bench/bench_matrix.json b/research/2026-09-30-inference-bench/bench_matrix.json new file mode 100644 index 0000000..5eeffd2 --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_matrix.json @@ -0,0 +1,186 @@ +{ + "tiny/off": [ + { + "in": 22, + "cached": 0, + "out": 194, + "reason": null, + "ttft": 0.188, + "total": 5.855, + "srv_tps": 34.1, + "cli_tps": 23.3, + "acc": 68 + }, + { + "in": 22, + "cached": 0, + "out": 196, + "reason": null, + "ttft": 0.151, + "total": 3.207, + "srv_tps": 64.0, + "cli_tps": 43.9, + "acc": 66 + }, + { + "in": 22, + "cached": 0, + "out": 189, + "reason": null, + "ttft": 0.158, + "total": 3.891, + "srv_tps": 53.3, + "cli_tps": 34.0, + "acc": 67 + }, + { + "in": 22, + "cached": 0, + "out": 196, + "reason": null, + "ttft": 0.157, + "total": 1.247, + "srv_tps": 178.5, + "cli_tps": 124.6, + "acc": 69 + } + ], + "tiny/on": [ + { + "in": 62, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 0.448, + "total": 6.176, + "srv_tps": 69.7, + "cli_tps": 69.5, + "acc": 77 + }, + { + "in": 62, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 0.355, + "total": 7.752, + "srv_tps": 54.0, + "cli_tps": 52.9, + "acc": 76 + }, + { + "in": 62, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 0.355, + "total": 4.964, + "srv_tps": 86.7, + "cli_tps": 86.4, + "acc": 81 + }, + { + "in": 62, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 0.342, + "total": 2.58, + "srv_tps": 178.0, + "cli_tps": 174.3, + "acc": 78 + } + ], + "35k/off": [ + { + "in": 38485, + "cached": 0, + "out": 386, + "reason": null, + "ttft": 6.803, + "total": 11.493, + "srv_tps": 80.0, + "cli_tps": 68.7, + "acc": 82 + }, + { + "in": 38485, + "cached": 0, + "out": 394, + "reason": null, + "ttft": 6.68, + "total": 11.296, + "srv_tps": 85.2, + "cli_tps": 71.5, + "acc": 74 + }, + { + "in": 38485, + "cached": 0, + "out": 387, + "reason": null, + "ttft": 6.873, + "total": 12.722, + "srv_tps": 66.1, + "cli_tps": 55.5, + "acc": 72 + }, + { + "in": 38485, + "cached": 0, + "out": 391, + "reason": null, + "ttft": 6.833, + "total": 9.383, + "srv_tps": 143.9, + "cli_tps": 128.2, + "acc": 74 + } + ], + "35k/on": [ + { + "in": 38525, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 19.453, + "total": 24.689, + "srv_tps": 76.3, + "cli_tps": 76.0, + "acc": 79 + }, + { + "in": 38525, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 19.266, + "total": 26.897, + "srv_tps": 52.0, + "cli_tps": 52.2, + "acc": 67 + }, + { + "in": 38525, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 23.464, + "total": 28.27, + "srv_tps": 82.2, + "cli_tps": 82.8, + "acc": 71 + }, + { + "in": 38525, + "cached": 0, + "out": 400, + "reason": null, + "ttft": 6.754, + "total": 9.723, + "srv_tps": 130.8, + "cli_tps": 134.1, + "acc": 72 + } + ] +} \ No newline at end of file diff --git a/research/2026-09-30-inference-bench/bench_matrix.py b/research/2026-09-30-inference-bench/bench_matrix.py new file mode 100644 index 0000000..5a154f8 --- /dev/null +++ b/research/2026-09-30-inference-bench/bench_matrix.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""2x2 decode matrix: thinking on/off x context tiny/35k, interleaved, min-of-N. +min = least-contaminated by the agent session sharing the single slot.""" +import json, os, statistics, time, urllib.request +CH = os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")) +c = json.load(open(os.path.join(CH, "connection.json"))) +B = c["url"].rstrip("/"); B = B[:-3] if B.endswith("/v1") else B +K = open(os.path.expanduser(c["key_file"])).read().strip() +H = {"Content-Type": "application/json", "Authorization": "Bearer " + K} +MODEL = json.load(urllib.request.urlopen(urllib.request.Request(B + "/v1/models", headers=H)))["data"][0]["id"] + +def run(prompt, mx, think): + p = {"model": MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": mx, + "temperature": 0.0, "stream": True, "stream_options": {"include_usage": True}, "timings": True} + if not think: p["chat_template_kwargs"] = {"enable_thinking": False} + t0 = time.perf_counter(); u = t = None; n = ttft = last = None; buf = b"" + for raw in urllib.request.urlopen(urllib.request.Request(B + "/v1/chat/completions", data=json.dumps(p).encode(), method="POST", headers=H), timeout=900): + now = time.perf_counter() - t0; buf += raw + while b"\n" in buf: + ln, buf = buf.split(b"\n", 1); ln = ln.strip() + if not ln.startswith(b"data:"): continue + blob = ln[5:].strip() + if blob in (b"", b"[DONE]"): continue + try: o = json.loads(blob) + except Exception: continue + u = o.get("usage") or u; t = o.get("timings") or t + for ch in o.get("choices", []): + d = ch.get("delta") or {}; s = (d.get("content") or "") + (d.get("reasoning_content") or "") + if s: + n = 0 if n is None else n + 1; ttft = now if ttft is None else ttft; last = now + u, t = u or {}, t or {} + return {"in": u.get("prompt_tokens"), "cached": (u.get("prompt_tokens_details") or {}).get("cached_tokens"), + "out": u.get("completion_tokens"), "reason": (u.get("completion_tokens_details") or {}).get("reasoning_tokens"), + "ttft": round(ttft, 3) if ttft else None, "total": round(time.perf_counter() - t0, 3), + "srv_tps": round(t.get("predicted_per_second"), 1) if t else None, + "cli_tps": round((n - 1) / (last - ttft), 1) if n and n > 1 and ttft is not None and last and last > ttft else None, + "acc": round(100 * t["draft_n_accepted"] / t["draft_n"]) if t and t.get("draft_n") else None} + +def filler(w, s): + ws = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu".split() + return " ".join([f"p{s}"] + [ws[(i + s * 7) % len(ws)] for i in range(w)]) + +Q = "List 60 animals, one per line." +BIG = filler(25000, 11) + "\n" + Q +run("warm", 32, False); run(BIG, 8, False) # warm engine + seed the 35k prefix cache +cells = {"tiny/off": [], "tiny/on": [], "35k/off": [], "35k/on": []} +for r in range(4): + for name, prompt, think in (("tiny/off", Q, False), ("tiny/on", Q, True), ("35k/off", BIG, False), ("35k/on", BIG, True)): + x = run(prompt, 400, think); cells[name].append(x) + print(f" r{r+1} {name:<9} ctx={x['in']:>6} out={x['out']:>4} ttft={x['ttft']:>6} srv={x['srv_tps']:>6} cli={x['cli_tps']:>6} acc={x['acc']}%") +print("\n=== min-of-4 (uncontended) / median ===") +for name, rs in cells.items(): + f = lambda k: [r[k] for r in rs if isinstance(r.get(k), (int, float))] + print(f"{name:<10} srv {min(f('srv_tps')):>6} / {round(statistics.median(f('srv_tps')),1):>6} t/s | " + f"cli {min(f('cli_tps')):>6} / {round(statistics.median(f('cli_tps')),1):>6} t/s | " + f"ttft {min(f('ttft')):>6}s | acc {round(statistics.median(f('acc')))}%") +json.dump(cells, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "bench_matrix.json"), "w"), indent=2) diff --git a/scripts/smoke.sh b/scripts/smoke.sh new file mode 100755 index 0000000..2563838 --- /dev/null +++ b/scripts/smoke.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +# End-to-end smoke test against a real edge and a real upstream. +# +# The integration tests prove the decision logic in isolation; this proves the +# deployed shape: the binary starts, proxies to an upstream it knows nothing +# about, bans a source that drew enough refusals, answers the way the design +# says it should, and healthchecks itself the way a shell-less distroless image +# needs. +# +# Sources are simulated with X-Forwarded-For and TrustProxyHeaders=on. That is +# not a shortcut: it is the only way to exercise "this source is banned, that +# one is not" over a loopback connection, and it doubles as a check that the +# trusted-proxy path is wired. +set -uo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +EDGE_PORT=${EDGE_PORT:-18088} +UP_PORT=${UP_PORT:-18900} +DB=/tmp/openwaf-smoke-$$.db +TOKEN=smoketoken +BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Release/net10.0/OpenWaf.Edge.dll" +[ -f "$BIN" ] || BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Debug/net10.0/OpenWaf.Edge.dll" + +export HEALTHCHECK_PORT="$EDGE_PORT" + +SCANNER=203.0.113.66 +OFFICER=198.51.100.7 +Bystander=198.51.100.99 + +# Payloads live in single-quoted variables: embedding them in the command +# substitutions below with escaped quotes is exactly the kind of thing that +# silently truncates a body. +BLOCK_JSON='{"ip":"198.51.100.7","reason":"confirmed scraper","redirectTo":"https://honeypot.example.org/"}' +ALLOW_JSON='{"match":"198.51.100.0/24","note":"office"}' +POLICY_OFF_JSON='{"mode":"Off"}' + + +cleanup() { + [ -n "${EDGE_PID:-}" ] && kill "$EDGE_PID" 2>/dev/null + [ -n "${UP_PID:-}" ] && kill "$UP_PID" 2>/dev/null + rm -f "$DB" "$DB-shm" "$DB-wal" +} +trap cleanup EXIT + +mkdir -p /tmp/openwaf-upstream +python3 -m http.server "$UP_PORT" --bind 127.0.0.1 -d /tmp/openwaf-upstream >/dev/null 2>&1 & +UP_PID=$! + +rm -f "$DB" +ASPNETCORE_URLS="http://127.0.0.1:$EDGE_PORT" \ +OPENWAF_ADMIN_TOKEN="$TOKEN" \ +ConnectionStrings__OpenWaf="Data Source=$DB" \ +OpenWaf__Policy__StreakThreshold=3 \ +OpenWaf__Policy__Mode=Enforce \ +OpenWaf__Policy__BanDuration="00:00:06" \ +OpenWaf__Policy__TrustProxyHeaders=true \ +ReverseProxy__Clusters__upstream__Destinations__upstream1__Address="http://127.0.0.1:$UP_PORT/" \ + dotnet "$BIN" >/tmp/openwaf-smoke.log 2>&1 & +EDGE_PID=$! + +for _ in $(seq 1 60); do + curl -fsS "http://127.0.0.1:$EDGE_PORT/healthz" >/dev/null 2>&1 && break + sleep 0.25 +done + +pass=0; fail=0 +check() { + if [ "$2" = "$3" ]; then pass=$((pass+1)); printf ' ok %-56s %s\n' "$1" "$3" + else fail=$((fail+1)); printf ' FAIL %-56s expected %s, got %s\n' "$1" "$2" "$3"; fi +} +code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } +from() { printf 'http://127.0.0.1:%s/%s' "$EDGE_PORT" "$1"; } # usage: from path + -H "X-Forwarded-For: ip" + +echo "edge :$EDGE_PORT upstream :$UP_PORT db $DB" + +echo '- streak ban' +for i in 1 2 3; do + check "probe $i from the scanner reaches the upstream" 404 \ + "$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")" +done +check '4th request from the scanner is refused by the edge' 403 \ + "$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")" +check 'a bystander is untouched' 404 \ + "$(code -H "X-Forwarded-For: $Bystander" "$(from anything)")" +check 'the refusal explains itself' blocked_by_policy \ + "$(curl -s -H "X-Forwarded-For: $SCANNER" "$(from anything)" | python3 -c 'import sys,json;print(json.load(sys.stdin)["error"])')" +check 'the ban carries a Retry-After' yes \ + "$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $SCANNER" "$(from anything)" | grep -qi '^retry-after:' && echo yes || echo no)" + +echo '- operator list' +check 'add an operator block' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$BLOCK_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" +check 'an operator block answers 301 with Location' https://honeypot.example.org/ \ + "$(curl -s -o /dev/null -w '%{redirect_url}' -H "X-Forwarded-For: $OFFICER" "$(from anything)")" + +echo '- allowlist outranks everything' +check 'allow the office range' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$ALLOW_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow")" +check 'the blocked office address gets through' 404 \ + "$(code -H "X-Forwarded-For: $OFFICER" "$(from anything)")" +check 'the scanner outside that range stays banned' 403 \ + "$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")" + +echo '- expiry and clearing' +sleep 7 +check 'the engine ban lifted itself' 404 "$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")" +check 'clearing engine bans leaves operator rows' '{"deleted":1}' \ + "$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" | tr -d ' ')" +check 'an operator row survives it' 1 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" + +echo '- admin surface' +check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" +check 'the policy is readable' Enforce \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')" +check 'switching the engine off is accepted' Off \ + "$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' --data-binary "$POLICY_OFF_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')" + +echo '- healthcheck mode (a shell-less image can only ask the binary)' +dotnet "$BIN" --healthcheck; check 'healthcheck exit code' 0 "$?" + +echo +echo "passed $pass, failed $fail" +[ "$fail" -eq 0 ]