Files
Pavlo Ratushnyi 8082e6a598 The alerting pillar had an endpoint and nobody reading it
`GET /admin-api/alerts` appeared in **zero** gate scripts. Both alert kinds were
proven in-process, against `FakeUpstream`, at the database level — and the half
that matters for an alert, the half where a human sees it, had nothing on the
other end. The console read six endpoints and this was not one of them.

The page now renders them: kind, source, count, last status and path, when. The
kind an operator has to act on is marked rather than only printed, and the note
above the table says what each kind means in words, because `server_error_streak`
and `candidate_ban` are different sentences: your upstream is failing (and the
edge will not ban the visitor who saw it) versus the rule would have banned and
the mode is Observe.

`scripts/console-smoke.sh` seeds four 502s from an address chosen for this run
(`/boom`, added last commit), and `scripts/console-check.cjs` asserts the row by
**source and count**, the note text, the marking, and that the table survives the
phone pass: 26 → **30 assertions**.

The wiring was the interesting part. The seeding runs in one container and the
browser in another, so the address chosen at seed time cannot be inherited — an
empty `SEED_ERROR` on the driver side would have quietly turned "the alert this
run wrote" into "some alert exists somewhere". The seed now writes its values to
`console-seed.env` (gitignored) and the rehearsal passes them to the browser
container.

`AdminConsoleTests` got the fast half: the markup contains the alerts table and
fetches the endpoint. A static check cannot assert the row is there — that is
what the browser gate is for — but it can notice the table disappearing without
waiting for Chromium. 28 → **29 integration tests**.

Numbers. Host: build 0 warnings, unit 54/54, integration 29/29. Linux rehearsal,
one invocation on this tree, EXIT=0: source gates 54/54 + 29/29 + smoke 19/19,
compose **35/35**, console **30/30** in a real Chromium. actionlint 1.7.12 over
both workflow files: 0 problems; shellcheck, `bash -n` and `node --check` clean.

Two things said plainly. The console number above is the Linux one: this laptop's
browser cache has chromium-1223/1228/1234 and the pinned Playwright wants 1243,
so the darwin console gate was not re-run for this change. And during the run the
table's own note read "Newest 25" — the endpoint is capped and residue from
earlier runs fills the page. That is OPEN-18's amplification showing up where an
operator would see it, and the note states the cap instead of pretending the
table is everything.
2026-10-01 16:40:37 +02:00

186 lines
8.0 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// The console is a page over the admin API, so the properties worth testing are
/// the ones the page inherits from the guard: it is always reachable, it is
/// never observed, and it does not leak the token it asks for.
/// </summary>
public sealed class AdminConsoleTests
{
private const string Scanner = "203.0.113.66";
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string sourceIp)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp);
return await f.Client.SendAsync(request);
}
private static async Task<JsonElement> JsonAsync(HttpResponseMessage response)
=> JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
[Fact]
public async Task The_console_is_served_at_admin_and_never_carries_the_token_in_its_markup()
{
await using var f = new EdgeFixture();
using var page = await f.Client.GetAsync("/admin");
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
Assert.Contains("text/html", page.Content.Headers.ContentType?.ToString());
var html = await page.Content.ReadAsStringAsync();
Assert.Contains("openwaf", html);
// The page asks for a token; it must not already know one. A token baked
// into the markup is a token in every proxy log and browser cache that
// ever sees this page.
Assert.DoesNotContain(EdgeFixture.AdminToken, html);
}
[Fact]
public async Task The_console_offers_the_two_writes_an_incident_needs()
{
await using var f = new EdgeFixture();
using var page = await f.Client.GetAsync("/admin");
var html = await page.Content.ReadAsStringAsync();
// Reading the state is the easy half. The controls an operator actually
// reaches for mid-incident are: block one address with a reason, pull a
// range back out from under the bans, delete one row instead of clearing
// a whole provenance, and set a country rule. Each of these is one call
// to an endpoint that already exists; if any of them disappears from the
// page, the browser gate notices late — this notices in the fast suite.
Assert.Contains("id=\"addBlock\"", html);
Assert.Contains("id=\"blockIp\"", html);
Assert.Contains("id=\"addAllow\"", html);
Assert.Contains("id=\"allowMatch\"", html);
Assert.Contains("data-act=\"delblock\"", html);
Assert.Contains("data-act=\"delallow\"", html);
Assert.Contains("data-act=\"country\"", html);
Assert.Contains("id=\"allow\"", html);
}
[Fact]
public async Task The_console_shows_the_alerts_the_edge_says_it_raises()
{
await using var f = new EdgeFixture();
using var page = await f.Client.GetAsync("/admin");
var html = await page.Content.ReadAsStringAsync();
// /admin-api/alerts existed and nothing read it: the alerting pillar could
// have been empty and every other assertion stayed green. The page renders
// it now, and this is the fast half of that promise — the browser gate
// asserts the table holds the row this run seeded, which no static check
// can.
Assert.Contains("id=\"alerts\"", html);
Assert.Contains("/admin-api/alerts", html);
Assert.Contains("server_error_streak", html);
}
[Fact]
public async Task The_console_is_reachable_from_an_address_the_edge_has_banned()
{
await using var f = new EdgeFixture(threshold: 2);
for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose();
using (var banned = await GetAsync(f, "/probe", Scanner))
Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode);
// The recovery hatch has to include the page an operator would use to
// clear the ban, not only the API behind it.
using var console = await GetAsync(f, "/admin", Scanner);
Assert.Equal(HttpStatusCode.OK, console.StatusCode);
}
[Fact]
public async Task Fumbling_the_console_never_bans_the_operator_fumbling_it()
{
await using var f = new EdgeFixture(threshold: 3);
// Typing into a console produces wrong paths. If those counted as
// refusals, the page meant to undo a lockout would cause one.
for (var i = 0; i < 8; i++)
{
// A mistyped subpath shows the page rather than being proxied to an
// upstream that has never heard of it, and either way it must not
// count as a refusal against the person typing it.
using var mistyped = await GetAsync(f, "/admin/observationss", Scanner);
Assert.Equal(HttpStatusCode.OK, mistyped.StatusCode);
}
using var stillOpen = await GetAsync(f, "/anything", Scanner);
Assert.Equal(HttpStatusCode.NotFound, stillOpen.StatusCode);
}
[Fact]
public async Task The_country_summary_counts_sources_rather_than_requests()
{
await using var f = new EdgeFixture(threshold: 50);
// Two sources from one country, one from another, several requests each.
for (var i = 0; i < 3; i++) (await GetAsyncWithCountry(f, "/a", "203.0.113.10", "US")).Dispose();
(await GetAsyncWithCountry(f, "/b", "203.0.113.11", "US")).Dispose();
(await GetAsyncWithCountry(f, "/c", "198.51.100.30", "DE")).Dispose();
await f.FlushObservationsAsync();
using var response = await f.Client.GetAsync($"/admin-api/countries/summary?token={EdgeFixture.AdminToken}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var rows = await JsonAsync(response);
var byCode = rows.EnumerateArray().ToDictionary(
r => r.GetProperty("code").GetString()!,
r => r.GetProperty("sources").GetInt32());
Assert.Equal(2, byCode["US"]);
Assert.Equal(1, byCode["DE"]);
}
private static async Task<HttpResponseMessage> GetAsyncWithCountry(EdgeFixture f, string path, string ip, string country)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
request.Headers.TryAddWithoutValidation("CF-IPCountry", country);
return await f.Client.SendAsync(request);
}
[Fact]
public async Task The_block_listing_says_when_it_is_not_the_whole_answer()
{
await using var f = new EdgeFixture();
using (var scope = f.Service<IServiceScopeFactory>().CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var now = DateTimeOffset.UtcNow;
db.Blocks.AddRange(Enumerable.Range(0, 600).Select(i => new OpenWaf.Domain.Security.BlockEntry
{
SourceKey = $"203.0.{i / 256}.{i % 256}",
Source = OpenWaf.Domain.Security.BlockSource.Engine,
CreatedAt = now,
ExpiresAt = now.AddHours(1),
Reason = "seed for the cap",
ConsecutiveRefusals = 10
}));
await db.SaveChangesAsync();
}
await f.Service<EdgeStateStore>().InvalidateAsync();
using var page = await f.Client.GetAsync($"/admin-api/blocks?live=true&token={EdgeFixture.AdminToken}");
var items = (await JsonAsync(page)).EnumerateArray().ToList();
Assert.Equal(500, items.Count);
Assert.Equal("600", page.Headers.GetValues("X-Total-Count").Single());
Assert.Equal("true", page.Headers.GetValues("X-Truncated").Single());
using var whole = await f.Client.GetAsync($"/admin-api/blocks?live=true&limit=1000&token={EdgeFixture.AdminToken}");
Assert.Equal(600, (await JsonAsync(whole)).EnumerateArray().Count());
Assert.Equal("false", whole.Headers.GetValues("X-Truncated").Single());
}
}