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 /// 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. - PassRuleObserved = 7 + PassRuleObserved = 7, + /// 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. + BlockRate = 8 } diff --git a/dotnet/OpenWaf.Domain/Responses/BlockPage.cs b/dotnet/OpenWaf.Domain/Responses/BlockPage.cs new file mode 100644 index 0000000..d4ef7f4 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Responses/BlockPage.cs @@ -0,0 +1,160 @@ +using System.Globalization; +using System.Net; +using OpenWaf.Domain.Engine; + +namespace OpenWaf.Domain.Responses; + +/// +/// 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: +/// +/// * The status never changes. 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. +/// * Nothing is fetched. 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. +/// * The operator's words are not shown. 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. +/// +public static class BlockPage +{ + /// + /// 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". + /// + 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; + } + + /// + /// 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. + /// + 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("") + .Append("") + .Append("") + .Append("").Append(WebUtility.HtmlEncode(title)).Append("") + .Append("") + .Append("

").Append(WebUtility.HtmlEncode(headline)).Append("

") + .Append("

").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; } } + + /// + /// 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. + /// + private static Task WriteRefusalAsync( + HttpContext ctx, bool wantsHtml, EdgeVerdict verdict, string? reference, + DateTimeOffset? expiresAt, int retryAfterSeconds, DateTimeOffset now, Func 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); diff --git a/dotnet/OpenWaf.Tests.Integration/RefusalPageTests.cs b/dotnet/OpenWaf.Tests.Integration/RefusalPageTests.cs new file mode 100644 index 0000000..db2c4d0 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/RefusalPageTests.cs @@ -0,0 +1,191 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.AspNetCore.Http; + +namespace OpenWaf.Tests.Integration; + +/// +/// 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. +/// +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 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 BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync(); + + /// 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. + 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(" 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 = "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("", got.Body); + } + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/BlockPageTests.cs b/dotnet/OpenWaf.Tests.Unit/BlockPageTests.cs new file mode 100644 index 0000000..794fbc9 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/BlockPageTests.cs @@ -0,0 +1,116 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Responses; +using Xunit; + +namespace OpenWaf.Tests.Unit; + +/// +/// 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. +/// +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, + "", null, 0, T0); + Assert.DoesNotContain("", page); + Assert.Contains("