Files
Pavlo Ratushnyi f1715e4b7c 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.
2026-10-04 21:53:06 +02:00

161 lines
8.2 KiB
C#

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";
}
}