diff --git a/README.md b/README.md
index c231389..2238176 100644
--- a/README.md
+++ b/README.md
@@ -113,6 +113,41 @@ answer ends the episode, which lets the next outage announce itself again.
`A_dry_run_announces_each_candidate_ban_twice_at_most_rather_than_once_per_request`
are the tests; both fail with the edge detection removed.
+### A refusal is written for the person who got it
+
+Every refusal used to be one JSON body. The operator reads the listings; the
+only audience that can act on a refusal — the office whose address tripped a
+streak, the visitor who followed a link into a path a rule refuses — cannot do
+anything with `{"error":"blocked_by_policy","reason":"3 consecutive refusals…"}`.
+So the guard negotiates the **body** by `Accept`: a client that names
+`text/html` or `application/xhtml+xml` with q>0 gets sentences, everything else
+gets the JSON it has always got. `Accept: */*` is *not* a request for HTML — it
+means "I did not think about it", and it is what curl, monitors and SDKs send,
+which are exactly the clients that parse the body.
+
+Three rules the renderer exists to keep:
+
+* **the status never changes.** Negotiation changes the body, never the answer.
+ A 429 that became 200 because a browser looked at it would be a defence that
+ switches itself off when observed.
+* **nothing is fetched.** Inline CSS, no script, no font, no image, no link, and
+ `robots=noindex` so a refusal never becomes an indexed page. The page goes to
+ anonymous visitors and the runtime image is distroless: everything the visitor
+ needs arrived in these bytes.
+* **the operator's note is never shown.** An operator block's `reason` is free
+ text typed during an incident ("confirmed scraper"). It is an internal note
+ about a source, so that branch renders the fact and no reference; the note
+ stays in the listings.
+
+What the page does carry is the machine reference the JSON already carried —
+`rule_12`, `country_denied_DE`, `rate_3_of_2`, a ban's reason — plus
+`Retry-After` and the expiry in UTC, in words. That reference is the string the
+visitor quotes and the string the operator searches the listings for, which is
+the whole point of the page. `BlockPage` is a pure function in the domain (no
+`HttpContext`, no I/O), so the wording is testable without a pipeline; the wire
+half is `RefusalPageTests` and four smoke lines that ask a real edge what a
+browser and what curl get for the same refusal.
+
### The toggle
Automatic banning is a mode, not a replacement:
@@ -877,8 +912,8 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own.
On the head of this file the host suite has been re-run and the container stages
have not, so the two sets of numbers are labelled separately rather than merged
into one green line. macOS host, this tree, re-measured 2026-10-04 with the
-request budget on it: build 0 warnings / 0 errors, unit **207/207**, integration
-**219/219 in 20 s**, console **90 assertions, 0 failed**, smoke **passed 48,
+refusal page on it: build 0 warnings / 0 errors, unit **227/227**, integration
+**225/225 in 20 s**, console **90 assertions, 0 failed**, smoke **passed 52,
failed 0**, and compose **209 passed, 0 failed** against the built image at
261 MB. The smoke count moved by more than its new scene: the edge was being
started from the repository root, where there is no `appsettings.json`, so it
@@ -1087,6 +1122,12 @@ Stated, because a defence that hides its failure modes is not a defence.
and `requestRulesError` on `/admin-api/state`, a NOT READ line over the rules
table — instead of freezing the operator's block list, which is the failure
this file keeps warning about.
+* **A browser gets a page, and the page is not the operator's.** The wording is
+ ours, one template, fixed per verdict. An operator who wants their own brand
+ and their own sentence on a block page cannot have one yet — the extension
+ point is the reference, not the template. And the page never renders what the
+ operator typed about a source, so a visitor learns the verdict and nothing
+ else.
* **A path rule is matched on every request.** The scan is a linear walk over
the live rules, capped at 500 of them, and the pattern language is a glob
rather than a regex so no pattern can backtrack exponentially against a path
@@ -1100,14 +1141,14 @@ Stated, because a defence that hides its failure modes is not a defence.
```
dotnet/
- OpenWaf.Domain/ pure decision core: source key, streak, ordered decision
+ OpenWaf.Domain/ pure decision core: source key, streak, ordered decision, refusal page
OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo
OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode
- OpenWaf.Tests.Unit/ 207 tests over the decision logic, the budget window and the durability counters
- OpenWaf.Tests.Integration/ 219 tests driving the real pipeline against a fake upstream
-scripts/smoke.sh 48 assertions against a running edge + a real upstream
+ OpenWaf.Tests.Unit/ 227 tests over the decision logic, the budget window, the refusal wording and the durability counters
+ OpenWaf.Tests.Integration/ 225 tests driving the real pipeline against a fake upstream
+scripts/smoke.sh 52 assertions against a running edge + a real upstream
scripts/compose-smoke.sh 209 assertions against the built image (compose + nginx)
-scripts/console-check.cjs 75 assertions against the page, in a real Chromium
+scripts/console-check.cjs 90 assertions against the page, in a real Chromium
scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2)
.github/workflows/ci.yml runs the gates on every push
.github/workflows/geo-freshness.yml the same check on a schedule
diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs
index aaa2158..ed3ade5 100644
--- a/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs
+++ b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs
@@ -21,5 +21,10 @@ public enum EdgeVerdict
///
").Append(WebUtility.HtmlEncode(note)).Append("
"); + + if (retryAfterSeconds > 0) + html.Append("Try again in ").Append(retryAfterSeconds) + .Append(" second").Append(retryAfterSeconds == 1 ? "" : "s").Append(".
"); + + if (expiresAt is { } expires) + { + var absolute = expires.ToUniversalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); + var remaining = expires - now; + html.Append("This ends at ").Append(absolute).Append(" UTC"); + if (remaining > TimeSpan.Zero && remaining < TimeSpan.FromDays(1)) + html.Append(" — about ").Append(Describe(remaining)).Append(" from now"); + html.Append(".
"); + } + + if (!string.IsNullOrWhiteSpace(reference)) + html.Append("Reference: ") + .Append(WebUtility.HtmlEncode(reference)).Append("
"); + + html.Append("If you think this is wrong, the person who runs this site can ") + .Append("check that reference and let you through.
"); + return html.ToString(); + } + + private static (string Title, string Headline, string Note) Wording(EdgeVerdict verdict) => verdict switch + { + EdgeVerdict.BlockRate => ( + "Slow down", + "You are asking too often.", + "This site limits how many requests one source may make in a short window. " + + "The limit is on the number of requests, not on anything you did."), + EdgeVerdict.BlockEngine => ( + "Blocked by this site", + "This site blocked your address.", + "The block was made automatically from the responses your address produced. " + + "It expires on its own, and an operator can clear it sooner."), + EdgeVerdict.BlockRule => ( + "Not available", + "This path is refused on this site.", + "A rule written for this site refuses this path before the application sees the request. " + + "The rule is not about you personally."), + EdgeVerdict.GeoReject => ( + "Not available from your region", + "This site is not available from your region.", + "Your region is inferred from your address, not known about you — VPNs and misattributed " + + "ranges are wrong sometimes. If you are a real customer, an operator can allow you in."), + // An operator block has no reference worth showing: its reason is the + // operator's own note about a source, not a message to this visitor. + _ => ( + "Refused", + "This site refused your request.", + "An operator of this site added your address to a list. Only they can take it off.") + }; + + private static string Describe(TimeSpan remaining) + { + if (remaining < TimeSpan.FromMinutes(1)) return $"{(int)Math.Ceiling(remaining.TotalSeconds)} seconds"; + if (remaining < TimeSpan.FromHours(1)) return $"{(int)Math.Round(remaining.TotalMinutes)} minutes"; + return $"{Math.Round(remaining.TotalHours, 1)} hours"; + } +} diff --git a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs index b038aa0..a5bbca9 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs @@ -1,5 +1,6 @@ using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Responses; using OpenWaf.Infrastructure.Geo; using OpenWaf.Infrastructure.Persistence; @@ -71,12 +72,18 @@ public sealed class EdgeGuardMiddleware( ctx.Response.StatusCode = 429; var seconds = Math.Max(1, (int)Math.Ceiling((rate.WindowEnd - now).TotalSeconds)); ctx.Response.Headers.RetryAfter = seconds.ToString(); - await ctx.Response.WriteAsJsonAsync(new BlockedBody( - "rate_limited", - $"rate_{rate.Count}_of_{policy.RateLimitPerWindow}", - rate.WindowEnd.ToString("O"), - "This source asked more often than this site allows. The pause ends on its own; " - + "if it is wrong, an operator can raise the budget or allowlist the address.")); + log.LogInformation("edge: {Verdict} {Ip} {Path} ({Count} over a budget of {Limit})", + EdgeVerdict.BlockRate, ctx.Connection.RemoteIpAddress, ctx.Request.Path.Value ?? "/", + rate.Count, policy.RateLimitPerWindow); + await WriteRefusalAsync(ctx, BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString()), + EdgeVerdict.BlockRate, $"rate_{rate.Count}_of_{policy.RateLimitPerWindow}", + rate.WindowEnd, seconds, now, + () => ctx.Response.WriteAsJsonAsync(new BlockedBody( + "rate_limited", + $"rate_{rate.Count}_of_{policy.RateLimitPerWindow}", + rate.WindowEnd.ToString("O"), + "This source asked more often than this site allows. The pause ends on its own; " + + "if it is wrong, an operator can raise the budget or allowlist the address."))); if (!rate.BreachStarted) return true; @@ -153,6 +160,15 @@ public sealed class EdgeGuardMiddleware( ctx.Response.StatusCode = decision.StatusCode; + // OPEN-57: the refusal is written in the language of whoever asked. A + // browser named text/html in Accept, so it gets sentences; everything + // else — including `Accept: */*`, which is "I did not think about it" + // and is what curl, monitors and SDKs send — gets the JSON body it has + // always got. The status and the headers are decided before this line + // and are not touched by it: a 429 that turns into a friendly page must + // stay a 429. + var wantsHtml = BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString()); + switch (decision.Verdict) { case EdgeVerdict.BlockOperator when decision.Location is not null: @@ -162,17 +178,20 @@ public sealed class EdgeGuardMiddleware( case EdgeVerdict.BlockEngine: if (decision.Location is not null) ctx.Response.Headers.Location = decision.Location; + var engineRetry = 0; if (decision.ExpiresAt is { } expires) { - var seconds = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds)); - ctx.Response.Headers.RetryAfter = seconds.ToString(); + engineRetry = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds)); + ctx.Response.Headers.RetryAfter = engineRetry.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.")); + await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.BlockEngine, decision.Reason, + decision.ExpiresAt, engineRetry, now, + () => 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.BlockRule: @@ -181,28 +200,59 @@ public sealed class EdgeGuardMiddleware( // while the pattern in a 403 body tells an anonymous visitor // exactly which payload to change. The pattern goes to the log // and to the alert, which are the operator's channels. - await ctx.Response.WriteAsJsonAsync(new BlockedBody( - "blocked_by_rule", - decision.Reason, - null, - "This path matches a rule written for this site. If it is wrong, " + - "the operator who wrote it can remove it.")); + await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.BlockRule, decision.Reason, + null, 0, now, + () => ctx.Response.WriteAsJsonAsync(new BlockedBody( + "blocked_by_rule", + decision.Reason, + null, + "This path matches a rule written for this site. If it is wrong, " + + "the operator who wrote it can remove 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.")); + await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.GeoReject, decision.Reason, + null, 0, now, + () => 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); + // An operator block that is not a redirect has no reference to + // show: its reason is the operator's own note about a source, + // not a message to this visitor. The page says the fact and + // points at the operator, which is all the visitor can act on. + if (wantsHtml) + { + ctx.Response.ContentType = "text/html; charset=utf-8"; + await ctx.Response.WriteAsync( + BlockPage.Render(EdgeVerdict.BlockOperator, null, decision.ExpiresAt, 0, now)); + } + else + { + await ctx.Response.WriteAsync(string.Empty); + } break; } } + + ///