Files
openwaf/dotnet/OpenWaf.Tests.Integration/AdminConsoleTests.cs
T
Pavlo Ratushnyi 31d8633975 A console that can only read is a dashboard, not a console
The page could clear engine bans and switch the mode. During an incident the two
things an operator actually reaches for are: put one address behind a block with
a reason, and pull one customer range back out from under the bans. Both
endpoints already existed (`POST /admin-api/blocks`, `POST /admin-api/allow`,
`DELETE /admin-api/blocks?key=`, `DELETE /admin-api/allow/{id}`,
`PUT /admin-api/countries/{code}?allowed=`); the page just did not expose them.
Now it does: a block form, an allow form with an optional expiry, a delete on
every ban row, a remove on every allow row, and a rule toggle on every country
row. Row buttons carry their key in a data attribute and one delegated handler
reads it, so nothing is spliced into an inline onclick string. Still no decision
logic on the page — every control is exactly one call.

The gate now checks the write on the wire, not just in the table, and that is
where the two findings were:

- An operator block answers **301 with the policy's redirect Location**
  (`OperatorBlockStatus=301`, `DefaultRedirectTargets=[iana example]`), not 403.
  A `fetch` that follows redirects walks out to the public internet and comes
  back **200** — which is how the new assertion first reported "the ban drawn on
  the page is not enforced" while the edge had been refusing that client with a
  301 from the start. The probe uses `redirect: 'manual'` now. The same trap
  would catch anyone writing a smoke check against this edge, so it is a comment
  in the gate and a sentence in the README.
- The baseline probe in my own gate ran *after* the block was written, so it
  asserted "reaches the upstream" about an address that was already blocked.
  Caught because the numbers disagreed with each other, not because I re-read
  the code.

Sequence the gate now proves end to end: address answers 404 → page writes a ban
→ same address answers 301 with a Location → per-row delete removes that one row
→ address answers 404 again; an allow entry appears with an expiry and can be
removed; a country rule is set to denied and put back. There is no DELETE for a
country rule, so "put back" is `PUT ?allowed=true` and the row stays behind
meaning "not denied" — documented rather than papered over. `console-smoke.sh`
now also clears allow entries on teardown, so a run that dies halfway cannot
leave an allowlist behind in the data volume and quietly change the next run.

The fast suite notices the controls too: one integration test asserts the write
controls are in the served page, so their removal fails in seconds rather than
waiting for the browser gate.

Gates on this commit: build 0 warnings / 0 errors, unit 54/54, integration
**28/28**, smoke 19/19, image 261 MB, compose-smoke 27/27, console **24/24**
(wire sequence above, phone pass at 375 px dark: scrollWidth 375, contrast
11.85:1, bars 67 px), actionlint 0, shellcheck 0. Unchanged and said plainly:
no job has ever run on a runner — the repository has no remote.
2026-10-01 14:56:16 +02:00

168 lines
7.3 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_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());
}
}