using System.Net; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// 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. /// public sealed class AdminConsoleTests { private const string Scanner = "203.0.113.66"; private static async Task 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 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 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().CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); 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().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()); } }