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

192 lines
9.0 KiB
C#

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