a refused visitor gets the answer in sentences, and the status never moves

Every refusal this edge makes was written for the operator and read by a person. The audience that can actually act on a refusal — the office whose address tripped a streak, the visitor who followed a link into a path a rule refuses, the customer a geo policy misattributed — cannot do anything with {"error":"blocked_by_policy","reason":"3 consecutive refusals…"}. The guard now negotiates the body by Accept: a client that names text/html or application/xhtml+xml with q>0 gets a page, everything else gets the JSON it has always got. Accept: */* is deliberately not HTML: it means "I did not think about it", and it is what curl, monitors and SDKs send, which are exactly the clients that parse the body.

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

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

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

The smoke count also had to be re-derived rather than trusted: a python replace whose replacement omitted its anchor deleted the line check 'the path is refused rather than proxied' 403 and left its command dangling as a continuation of the rule-add check above it, so the gate reported 51 and one assertion had silently vanished while still looking green. Same failure mode as the PolicyBounds edit earlier in this session — replace(a, b) where b does not contain a is a delete, not an insert.
This commit is contained in:
Pavlo Ratushnyi
2026-10-04 21:53:06 +02:00
parent 5cf93ef0fd
commit f1715e4b7c
7 changed files with 612 additions and 35 deletions
+48 -7
View File
@@ -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
+6 -1
View File
@@ -21,5 +21,10 @@ public enum EdgeVerdict
/// <summary>Passed. An observe-action request rule matched, and the guard
/// records it — the verdict exists so "nothing matched" and "a rule matched
/// and was told to watch" are different answers.</summary>
PassRuleObserved = 7
PassRuleObserved = 7,
/// <summary>Refused for asking too often (OPEN-56). Produced by the guard
/// rather than by the ordered decision, because it is the only pillar that
/// reads live state; it is still one answer from the one place that may
/// refuse a request, and it deserves a name in the log for that.</summary>
BlockRate = 8
}
@@ -0,0 +1,160 @@
using System.Globalization;
using System.Net;
using OpenWaf.Domain.Engine;
namespace OpenWaf.Domain.Responses;
/// <summary>
/// The refusal as a page rather than as a JSON body (OPEN-57).
/// Lives in the domain because it is a pure function over the verdict: no
/// HttpContext, no encoding of a response, no I/O. The guard decides whether a
/// client asked for a page and writes whichever body it chose; this says what
/// the page says.
///
/// Every refusal this edge makes is written for the operator and read by a
/// person. The customer whose office IP tripped a streak, the company whose
/// whole egress crossed a budget, the visitor following a link into a path an
/// operator refused — none of them can do anything with
/// `{"error":"blocked_by_policy","reason":"3 consecutive refusals …"}`, and
/// they are the only audience that can act: wait for the pause to end, or quote
/// a reference to whoever runs the site. The machine answer stays for the
/// clients that asked for it; a browser gets the same facts in sentences.
///
/// Three rules this file exists to keep:
///
/// * <b>The status never changes.</b> Negotiation changes the body, never the
/// answer. A 429 that becomes 200 because it now has a page would be a
/// defence that turns itself off when a browser looks at it.
/// * <b>Nothing is fetched.</b> The runtime image is distroless and the page is
/// served to anonymous visitors: no stylesheet, no font, no image, no script,
/// no remote URL. Everything the visitor needs arrived in these bytes.
/// * <b>The operator's words are not shown.</b> An operator block's `reason` is
/// free text the operator typed ("confirmed scraper", "competitor", something
/// worse in the heat of an incident). It is an internal note about a source,
/// not a message to the visitor, and rendering it would also mean rendering
/// markup typed by a human into an anonymous person's page. The page shows
/// the fact and the machine reference; the note stays in the listings.
/// </summary>
public static class BlockPage
{
/// <summary>
/// Does this client want a page? Only an explicit request for HTML counts.
///
/// `Accept: */*` — what curl, most SDKs, most monitors and most scrapers
/// send — is not a request for HTML; it is "I did not think about it", and
/// treating it as a request for HTML would hand a page to exactly the
/// clients that parse the body. A browser always names text/html, so the
/// rule that separates the two is "named it, and did not set it to zero".
/// </summary>
public static bool PrefersHtml(string? accept)
{
if (string.IsNullOrWhiteSpace(accept)) return false;
foreach (var raw in accept.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var media = raw;
var quality = 1.0;
var semicolon = raw.IndexOf(';');
if (semicolon >= 0)
{
media = raw[..semicolon].Trim();
var q = raw[(semicolon + 1)..].Trim();
if (q.StartsWith("q=", StringComparison.OrdinalIgnoreCase)
&& double.TryParse(q[2..], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed))
quality = parsed;
}
if (quality <= 0) continue;
if (media.Equals("text/html", StringComparison.OrdinalIgnoreCase)
|| media.Equals("application/xhtml+xml", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// The page. `reference` is the machine token the JSON body already carries
/// (`rule_12`, `country_denied_DE`, `rate_3_of_2`, a ban's reason) — the
/// string the visitor quotes to the operator, and the string the operator
/// searches the listings for. Pass null when the refusal has no reference
/// that is safe to show, which is the case for an operator block.
/// </summary>
public static string Render(
EdgeVerdict verdict, string? reference, DateTimeOffset? expiresAt, int retryAfterSeconds, DateTimeOffset now)
{
var (title, headline, note) = Wording(verdict);
var html = new System.Text.StringBuilder(1024);
html.Append("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">")
.Append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">")
.Append("<meta name=\"robots\" content=\"noindex,nofollow\">")
.Append("<title>").Append(WebUtility.HtmlEncode(title)).Append("</title>")
.Append("<style>body{margin:2rem auto;max-width:38rem;padding:0 1rem;")
.Append("font:16px/1.5 system-ui,sans-serif;color:#111;background:#fff}")
.Append("h1{font-size:1.3rem;margin-bottom:.25rem}p{margin:.5rem 0}")
.Append(".ref{font-family:ui-monospace,monospace;background:#f2f2f2;padding:.1rem .3rem}")
.Append(".muted{color:#555;font-size:.9rem}</style></head><body>")
.Append("<h1>").Append(WebUtility.HtmlEncode(headline)).Append("</h1>")
.Append("<p>").Append(WebUtility.HtmlEncode(note)).Append("</p>");
if (retryAfterSeconds > 0)
html.Append("<p>Try again in ").Append(retryAfterSeconds)
.Append(" second").Append(retryAfterSeconds == 1 ? "" : "s").Append(".</p>");
if (expiresAt is { } expires)
{
var absolute = expires.ToUniversalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
var remaining = expires - now;
html.Append("<p>This ends at <strong>").Append(absolute).Append(" UTC</strong>");
if (remaining > TimeSpan.Zero && remaining < TimeSpan.FromDays(1))
html.Append(" — about ").Append(Describe(remaining)).Append(" from now");
html.Append(".</p>");
}
if (!string.IsNullOrWhiteSpace(reference))
html.Append("<p class=\"muted\">Reference: <span class=\"ref\">")
.Append(WebUtility.HtmlEncode(reference)).Append("</span></p>");
html.Append("<p class=\"muted\">If you think this is wrong, the person who runs this site can ")
.Append("check that reference and let you through.</p></body></html>");
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";
}
}
@@ -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;
}
}
/// <summary>
/// One refusal, two bodies. The JSON is the answer that has always been
/// given, kept byte for byte for the clients that parse it; the page is the
/// same facts for the clients that render it.
/// </summary>
private static Task WriteRefusalAsync(
HttpContext ctx, bool wantsHtml, EdgeVerdict verdict, string? reference,
DateTimeOffset? expiresAt, int retryAfterSeconds, DateTimeOffset now, Func<Task> json)
{
if (!wantsHtml) return json();
ctx.Response.ContentType = "text/html; charset=utf-8";
return ctx.Response.WriteAsync(BlockPage.Render(verdict, reference, expiresAt, retryAfterSeconds, now));
}
}
internal sealed record BlockedBody(string Error, string? Reason, string? ExpiresAt, string Note);
@@ -0,0 +1,191 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// The refusal in two languages (OPEN-57). Every refusal this edge makes is
/// written for the operator and read by a person, and until now the person got
/// a JSON body with a machine token in it. These tests hold the two halves
/// together: the browser gets sentences and the same reference, and the client
/// that never asked for HTML gets the body it has always parsed — byte for byte.
/// </summary>
public sealed class RefusalPageTests
{
private const string Browser = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
private static async Task<(HttpStatusCode Status, string ContentType, string Body)> ProbeAsync(
EdgeFixture f, string path, string ip, string? accept, string? country = null)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
if (accept is not null) request.Headers.TryAddWithoutValidation("Accept", accept);
if (country is not null) request.Headers.TryAddWithoutValidation("CF-IPCountry", country);
using var r = await f.Client.SendAsync(request);
return (r.StatusCode,
r.Content.Headers.ContentType?.ToString() ?? "",
await r.Content.ReadAsStringAsync());
}
private static async Task<HttpResponseMessage> AdminAsync(
EdgeFixture f, HttpMethod method, string url, object? body = null)
{
using var request = new HttpRequestMessage(method, url);
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
if (body is not null) request.Content = JsonContent.Create(body);
return await f.Client.SendAsync(request);
}
private static async Task<string> BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync();
/// <summary>The ban is written after the response that proved it, and the
/// guard reads a snapshot that is refreshed by that write — so the gate
/// waits for the row rather than racing it.</summary>
private static async Task WaitForBanAsync(EdgeFixture f, string ip)
{
for (var i = 0; i < 40; i++)
{
using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine");
if ((await BodyAsync(blocks)).Contains(ip)) return;
await Task.Delay(250);
}
}
[Fact]
public async Task An_engine_ban_answers_a_browser_in_sentences_and_a_client_in_json()
{
await using var f = new EdgeFixture();
const string visitor = "203.0.113.201";
for (var i = 0; i < 3; i++)
_ = await ProbeAsync(f, "/wp-admin", visitor, null);
await WaitForBanAsync(f, visitor);
var page = await ProbeAsync(f, "/anything", visitor, Browser);
Assert.Equal(HttpStatusCode.Forbidden, page.Status);
Assert.Contains("text/html", page.ContentType);
Assert.Contains("This site blocked your address.", page.Body);
// The reference is the same machine string the JSON carries, so the
// visitor can quote it and the operator can find it.
Assert.Contains("consecutive refusals", page.Body);
Assert.Contains("Try again in", page.Body);
Assert.DoesNotContain("<script", page.Body);
Assert.DoesNotContain("http://", page.Body);
var json = await ProbeAsync(f, "/anything", visitor, "*/*");
Assert.Equal(HttpStatusCode.Forbidden, json.Status);
Assert.Contains("application/json", json.ContentType);
Assert.Contains("blocked_by_policy", json.Body);
}
[Fact]
public async Task A_path_rule_page_names_the_rule_and_never_the_pattern()
{
await using var f = new EdgeFixture();
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
new { pattern = "/.env*", action = "block" }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
var page = await ProbeAsync(f, "/.env", "203.0.113.202", Browser);
Assert.Equal(HttpStatusCode.Forbidden, page.Status);
Assert.Contains("text/html", page.ContentType);
Assert.Contains("This path is refused on this site.", page.Body);
Assert.Contains("rule_", page.Body);
// OPEN-54's ruling survives the page: a refusal that quotes the pattern
// tells an anonymous visitor which payload to change.
Assert.DoesNotContain("/.env", page.Body);
var json = await ProbeAsync(f, "/.env", "203.0.113.202", null);
Assert.Contains("blocked_by_rule", json.Body);
}
[Fact]
public async Task A_geo_refusal_page_still_says_the_inference_is_probabilistic()
{
await using var f = new EdgeFixture(geo: "DenyList");
using (var deny = await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/de?allowed=false"))
Assert.Equal(HttpStatusCode.NoContent, deny.StatusCode);
var page = await ProbeAsync(f, "/", "203.0.113.203", Browser, country: "DE");
Assert.Equal((HttpStatusCode)451, page.Status);
Assert.Contains("text/html", page.ContentType);
Assert.Contains("not available from your region", page.Body);
Assert.Contains("inferred from your address", page.Body);
Assert.Contains("country_denied_DE", page.Body);
var json = await ProbeAsync(f, "/", "203.0.113.203", "*/*", country: "DE");
Assert.Contains("region_not_supported", json.Body);
}
[Fact]
public async Task A_rate_refusal_page_says_how_long_to_wait_and_keeps_the_status()
{
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120);
f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
const string visitor = "203.0.113.204";
for (var i = 0; i < 2; i++)
Assert.Equal(HttpStatusCode.OK, (await ProbeAsync(f, "/catalog", visitor, null)).Status);
using var request = new HttpRequestMessage(HttpMethod.Get, "/catalog");
request.Headers.TryAddWithoutValidation("X-Forwarded-For", visitor);
request.Headers.TryAddWithoutValidation("Accept", Browser);
using var over = await f.Client.SendAsync(request);
Assert.Equal((HttpStatusCode)429, over.StatusCode);
Assert.Contains("text/html", over.Content.Headers.ContentType?.ToString() ?? "");
Assert.True(over.Headers.TryGetValues("Retry-After", out var retry));
var body = await over.Content.ReadAsStringAsync();
Assert.Contains("You are asking too often.", body);
Assert.Contains("Try again in", body);
Assert.Contains("rate_3_of_2", body);
}
[Fact]
public async Task An_operators_own_note_about_a_source_is_never_shown_to_the_visitor()
{
await using var f = new EdgeFixture();
using (var put = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
new { operatorBlockStatus = 403 }))
Assert.Equal(HttpStatusCode.OK, put.StatusCode);
const string note = "<svg onload=document.title='XSS'>confirmed scraper";
using (var block = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = "203.0.113.205", reason = note }))
Assert.Equal(HttpStatusCode.NoContent, block.StatusCode);
var page = await ProbeAsync(f, "/", "203.0.113.205", Browser);
Assert.Equal(HttpStatusCode.Forbidden, page.Status);
Assert.Contains("text/html", page.ContentType);
Assert.Contains("added your address to a list", page.Body);
// The reason is an internal note about a source, and it is markup typed
// by a human: it neither belongs on a visitor's page nor gets rendered
// as an element on one.
Assert.DoesNotContain("confirmed scraper", page.Body);
Assert.DoesNotContain("<svg", page.Body);
using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=operator");
var rows = JsonDocument.Parse(await BodyAsync(blocks)).RootElement;
Assert.Contains("confirmed scraper", rows[0].GetProperty("reason").GetString());
}
[Fact]
public async Task A_client_that_never_named_html_gets_the_answer_it_parsed_before()
{
await using var f = new EdgeFixture();
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
new { pattern = "/gate-json-probe*", action = "block" }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
foreach (var accept in new string?[] { null, "*/*", "application/json", "text/plain;q=1" })
{
var got = await ProbeAsync(f, "/gate-json-probe", "203.0.113.206", accept);
Assert.Equal(HttpStatusCode.Forbidden, got.Status);
Assert.Contains("application/json", got.ContentType);
Assert.Contains("blocked_by_rule", got.Body);
Assert.DoesNotContain("<!doctype html>", got.Body);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Responses;
using Xunit;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The refusal as a page (OPEN-57). Two things are worth pinning here: which
/// clients get the page, and what the page is allowed to contain. Both are
/// rules about behaviour, not about looks — a page that leaks the operator's
/// note, quotes a rule pattern, or fetches a stylesheet is a different product
/// from the one this file describes.
/// </summary>
public sealed class BlockPageTests
{
private static readonly DateTimeOffset T0 = new(2026, 10, 4, 12, 0, 0, TimeSpan.Zero);
[Theory]
// A browser: text/html named explicitly.
[InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", true)]
[InlineData("text/html", true)]
[InlineData("application/xhtml+xml;q=0.9", true)]
[InlineData("TEXT/HTML", true)]
[InlineData("text/plain;q=1, text/html;q=0.2", true)]
// Not a browser. `*/*` is "I did not think about it", and it is what curl,
// monitors, SDKs and scrapers send — the clients that parse the body.
[InlineData("*/*", false)]
[InlineData("", false)]
[InlineData(null, false)]
[InlineData("application/json", false)]
[InlineData("application/json;q=1,*/*;q=0.5", false)]
// Named, then refused.
[InlineData("text/html;q=0", false)]
[InlineData("text/html;q=0.0", false)]
public void Only_a_client_that_named_html_gets_the_page(string? accept, bool wantsHtml)
=> Assert.Equal(wantsHtml, BlockPage.PrefersHtml(accept));
[Fact]
public void Each_refusal_says_what_it_is_in_words()
{
Assert.Contains("You are asking too often.",
BlockPage.Render(EdgeVerdict.BlockRate, "rate_3_of_2", null, 12, T0));
Assert.Contains("This site blocked your address.",
BlockPage.Render(EdgeVerdict.BlockEngine, "3 consecutive refusals", null, 0, T0));
Assert.Contains("This path is refused on this site.",
BlockPage.Render(EdgeVerdict.BlockRule, "rule_12", null, 0, T0));
Assert.Contains("not available from your region",
BlockPage.Render(EdgeVerdict.GeoReject, "country_denied_DE", null, 0, T0));
Assert.Contains("added your address to a list",
BlockPage.Render(EdgeVerdict.BlockOperator, null, null, 0, T0));
}
[Fact]
public void The_reference_the_json_carries_is_the_reference_the_page_shows()
{
var page = BlockPage.Render(EdgeVerdict.BlockRule, "rule_12", null, 0, T0);
Assert.Contains("rule_12", page);
Assert.Contains("Reference:", page);
}
[Fact]
public void A_reference_is_text_and_never_becomes_an_element()
{
var page = BlockPage.Render(EdgeVerdict.BlockEngine,
"<svg onload=document.title='XSS'>", null, 0, T0);
Assert.DoesNotContain("<svg", page);
Assert.Contains("&lt;svg", page);
}
[Fact]
public void An_expiry_is_shown_as_an_instant_and_a_wait()
{
var page = BlockPage.Render(EdgeVerdict.BlockEngine, "reason", T0.AddMinutes(25), 0, T0);
Assert.Contains("2026-10-04 12:25 UTC", page);
Assert.Contains("about 25 minutes from now", page);
}
[Fact]
public void A_pause_far_off_shows_the_instant_without_a_false_soon()
{
var page = BlockPage.Render(EdgeVerdict.BlockEngine, "reason", T0.AddHours(30), 0, T0);
Assert.Contains("2026-10-05 18:00 UTC", page);
Assert.DoesNotContain("from now", page);
}
[Fact]
public void A_retry_after_becomes_a_sentence_about_time()
{
Assert.Contains("Try again in 1 second.",
BlockPage.Render(EdgeVerdict.BlockRate, "rate_3_of_2", null, 1, T0));
Assert.Contains("Try again in 42 seconds.",
BlockPage.Render(EdgeVerdict.BlockRate, "rate_3_of_2", null, 42, T0));
Assert.DoesNotContain("Try again",
BlockPage.Render(EdgeVerdict.BlockRule, "rule_1", null, 0, T0));
}
[Fact]
public void The_page_fetches_nothing_and_runs_no_script()
{
var page = BlockPage.Render(EdgeVerdict.GeoReject, "country_denied_DE", T0.AddMinutes(5), 0, T0);
Assert.DoesNotContain("<script", page);
Assert.DoesNotContain("src=", page);
Assert.DoesNotContain("<link", page);
Assert.DoesNotContain("http://", page);
Assert.DoesNotContain("https://", page);
Assert.Contains("<style>", page);
Assert.Contains("<meta name=\"viewport\"", page);
}
[Fact]
public void An_operator_block_shows_no_reference_because_its_reason_is_the_operators_note()
{
var page = BlockPage.Render(EdgeVerdict.BlockOperator, null, null, 0, T0);
Assert.DoesNotContain("Reference:", page);
}
}
+14
View File
@@ -111,6 +111,17 @@ 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"])')"
# The refusal in the visitor's language (OPEN-57). A browser named text/html, so
# it gets sentences; the same refusal stays JSON for the client that did not ask.
check 'a browser gets a page it can read, not a JSON blob' 'text/html; charset=utf-8' \
"$(curl -s -o /dev/null -w '%{content_type}' -H 'Accept: text/html,*/*' \
-H "X-Forwarded-For: $SCANNER" "$(from anything)")"
check 'the page carries the reference an operator can look up' yes \
"$(curl -s -H 'Accept: text/html' -H "X-Forwarded-For: $SCANNER" "$(from anything)" \
| grep -q 'Reference:' && echo yes || echo no)"
check 'and the same refusal is still JSON for a client that parses it' blocked_by_policy \
"$(curl -s -H 'Accept: */*' -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)"
@@ -159,6 +170,9 @@ check 'add a blocking path rule' 204 \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules")"
check 'the path is refused rather than proxied' 403 \
"$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")"
check 'a browser gets the same refusal in sentences' yes \
"$(curl -s -H 'Accept: text/html' -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)" \
| grep -q 'This path is refused on this site.' && echo yes || echo no)"
check 'the refusal names the rule and not the pattern' yes \
"$(curl -s -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)" | grep -q blocked_by_rule && echo yes || echo no)"
check 'a pattern that could never match is refused' 400 \