diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 4c6bf72..f4e7b8d 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -208,7 +208,7 @@ async function load() { apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'), apiRaw('/admin-api/observations?limit=25'), apiRaw('/admin-api/streaks'), apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'), - apiRaw('/admin-api/allow'), apiRaw('/admin-api/alerts?limit=25'), + apiRaw('/admin-api/allow?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'), apiRaw('/admin-api/geo') ]); // The core read decides whether there is anything to draw. When the admin @@ -245,7 +245,12 @@ async function load() { 'tracked ' + esc(state.trackedSources) + ' ' + 'engine bans ' + esc(state.engineBans) + ' ' + 'operator blocks ' + esc(state.operatorBlocks) + ' ' + - 'allow entries ' + esc(state.allowEntries) + '' + + // Live exemptions, not rows: the pill used to count rows, which is how a + // page could say "allow entries 1" about an exemption the edge had + // already stopped honouring. + 'allow entries ' + esc(state.allowEntries) + + (Number(state.allowEntriesExpired) > 0 ? ' live · ' + esc(state.allowEntriesExpired) + ' expired' : '') + + '' + // Which geo database this edge is actually enforcing on, and how old it is. // The pin ages with the image and a named volume is seeded once, so "which // one am I running" is a question an operator can only answer from here. @@ -263,13 +268,24 @@ async function load() { { v: (b.lastStatusCode || '') + ' ' + (b.lastPath || ''), n: true }, { h: '' } ])).join('') || row([{ v: 'none' }]); + // The row is not the answer. An allow entry with an expiry stops being + // obeyed the moment it ages — measured on the shipped image: the exempted + // address went 502 (through) at 03:58:20 and back to 301 (blocked) at + // 03:59:38 — while this table kept printing the row as if it still meant + // something, and nothing prunes those rows. So the cell carries the + // engine's verdict, not just the column. + const allowExpired = (allow || []).filter((a) => a.live === false).length; el('allow').tBodies[0].innerHTML = (allow || []).map((a) => row([ { v: a.match }, { v: a.note }, - { v: (a.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, + { v: a.live === false + ? (a.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it' + : (a.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, { h: '' } ])).join('') || row([{ v: 'none — everything not blocked is allowed' }]); el('allownote').textContent = (allow || []).length ? 'an allow entry outranks every ban, engine or operator — it is the "my customer is locked out" control' + + (allowRes.truncated ? ' · showing ' + allow.length + ' of ' + allowRes.total + ' rows' : '') + + (allowExpired ? ' · ' + allowExpired + ' EXPIRED: those rows no longer exempt anyone' : '') : 'nothing allowlisted'; el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([ { v: o.sourceKey }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index a039060..c4dd96a 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -29,7 +29,17 @@ internal sealed record StreakDto( string? LastCountryCode, DateTimeOffset LastSeenAt); -internal sealed record AllowDto(long Id, string Match, string? Note, DateTimeOffset CreatedAt, DateTimeOffset? ExpiresAt); +internal sealed record AllowDto( + long Id, + string Match, + string? Note, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + /// What the engine will answer for this match right now. The + /// expiry is a column; this is the decision made from it, and the two + /// disagree the moment a row ages — which is the whole reason the row is + /// not the answer. + bool Live); internal sealed record NewAllowRequest(string Match, string? Note, int? ExpiresInMinutes); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 3d61408..36b0a41 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -128,8 +128,41 @@ internal static class AdminEndpoints return Results.Ok(new { deleted = n }); }); - group.MapGet("/allow", async (OpenWafDbContext db, CancellationToken ct) => - Results.Ok(await db.AllowEntries.AsNoTracking().OrderBy(a => a.Match).ToListAsync(ct))); + // The exemption listing, with the two things the shipped image left out. + // Measured there (openwaf:c28, the head tree): one entry added for one + // minute against an operator block let its address through at 03:58:20 + // (502 from the upstream) and was obeyed no more at 03:59:38 (301, the + // block back) — yet at 03:59:39 GET /admin-api/allow still listed the + // row with no liveness field and /admin-api/state still counted it. The + // operator's table said "exempted" a minute after the edge stopped + // honouring it. And with 1101 rows the listing answered 130,386 bytes + // with no X-Total-Count and no X-Truncated, ignoring ?limit=10, + // ?offset=1000, ?limit=0 and ?limit=100000 alike. Expired rows are + // never pruned — retention ages out observations, engine bans and + // alerts, and an operator's own rows are not the machine's to delete — + // so the dead ones are only ever removable if they can be seen. + group.MapGet("/allow", async (bool? live, int? limit, int? offset, + OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => + { + if (!TryPaging(limit, offset, AllowListDefaultLimit, AllowListMaxLimit, + out var take, out var skip, out var pagingError)) + return Results.BadRequest(new { error = pagingError }); + var now = DateTimeOffset.UtcNow; + // Same shape as the block listing: live by default, live=false means + // "do not filter", because "who is exempt" and "what rows exist" + // are different questions and the page has to be able to ask both. + var liveOnly = live ?? true; + var rows = await FilterAllow(db.AllowEntries.AsNoTracking(), liveOnly, now) + .OrderBy(a => a.Match).ThenBy(a => a.Id) + .Skip(skip).Take(take) + .Select(a => new AllowDto(a.Id, a.Match, a.Note, a.CreatedAt, a.ExpiresAt, + a.ExpiresAt == null || a.ExpiresAt > now)) + .ToListAsync(ct); + var total = await FilterAllow(db.AllowEntries.AsNoTracking(), liveOnly, now).CountAsync(ct); + ctx.Response.Headers["X-Total-Count"] = total.ToString(); + ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); + return Results.Ok(rows); + }); group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => { @@ -358,7 +391,12 @@ internal static class AdminEndpoints supportsCity = geo.Info?.SupportsCity ?? false })); - group.MapGet("/state", (EdgeStateStore state, StreakTracker tracker) => Results.Ok(new + group.MapGet("/state", (EdgeStateStore state, StreakTracker tracker) => + { + var now = DateTimeOffset.UtcNow; + var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now)); + var allowExpired = state.Current.AllowEntries.Count - allowLive; + return Results.Ok(new { snapshotAgeSeconds = Math.Round((DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds, 1), // The age without the TTL it is measured against is half a number. On @@ -370,13 +408,23 @@ internal static class AdminEndpoints trackedSources = tracker.TrackedCount, operatorBlocks = state.Current.OperatorBlocks.Count, engineBans = state.Current.EngineBans.Count, - allowEntries = state.Current.AllowEntries.Count, + // The count of exemptions the engine is honouring, not the count of + // rows. Measured on the shipped image: one minute after the edge + // stopped obeying an allow entry (the request went from 502 back to + // 301), this number still said 1 and the listing still showed the + // row. Expired rows are kept on purpose — they are the operator's + // own writes — so they are counted separately rather than hidden. + allowEntries = allowLive, + allowEntriesExpired = allowExpired, mode = state.Current.Policy.Mode.ToString() - })); + }); + }); return app; } + private const int AllowListDefaultLimit = 500; + private const int AllowListMaxLimit = 2000; private const int ReadListDefaultLimit = 100; private const int ReadListMaxLimit = 1000; private const int StreakListDefaultLimit = 50; @@ -410,6 +458,16 @@ internal static class AdminEndpoints return false; } + /// + /// The one predicate that says whether an allow row is in force, written once + /// so the listing, the count behind X-Total-Count and the number in /state + /// cannot drift apart. AllowEntry.IsLive is the engine's own answer; this is + /// the same rule in the form EF can translate. + /// + private static IQueryable FilterAllow( + IQueryable query, bool liveOnly, DateTimeOffset now) + => liveOnly ? query.Where(a => a.ExpiresAt == null || a.ExpiresAt > now) : query; + private static bool TryPaging(int? limit, int? offset, int defaultLimit, int maxLimit, out int take, out int skip, out string? error) { diff --git a/dotnet/OpenWaf.Tests.Integration/AllowListingHonestyTests.cs b/dotnet/OpenWaf.Tests.Integration/AllowListingHonestyTests.cs new file mode 100644 index 0000000..1cb48d8 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/AllowListingHonestyTests.cs @@ -0,0 +1,181 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// An allow entry is the one rule that outranks every ban, so the listing of it +/// is the operator's answer to "who is exempt right now". Measured on the +/// shipped image (openwaf:c28, the head tree), with one entry added for one +/// minute against an operator block: +/// +/// 03:58:16 POST /admin-api/allow {"match":"192.168.65.1","expiresInMinutes":1} → 204 +/// 03:58:20 GET /whatever → 502 (passed to the upstream: the exemption is in force) +/// 03:59:38 GET /whatever → 301 (the exemption has expired; the block is back) +/// 03:59:39 GET /admin-api/allow → 200, the row still listed, no liveness field +/// /admin-api/state → "allowEntries":1 +/// +/// So the page said the address was exempted one minute after the edge stopped +/// honouring it, and the count the page shows is the count of rows, not the +/// count of exemptions in force. The same listing answered 1101 rows in 130,386 +/// bytes with no X-Total-Count and no X-Truncated, and every paging parameter +/// was ignored: ?limit=10, ?offset=1000, ?limit=0 and ?limit=100000 each +/// returned all 1101. Nothing prunes expired allow rows either — the retention +/// worker ages out observations, engine bans and alerts — so the table only +/// grows, and the dead rows are the ones the operator cannot tell apart. +/// +public sealed class AllowListingHonestyTests +{ + private const string Expired = "203.0.113.88"; + private const string Live = "203.0.113.89"; + + private static string? Header(HttpResponseMessage r, string name) + => r.Headers.TryGetValues(name, out var a) ? string.Join(",", a) + : r.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b) + : null; + + private static async Task<(HttpStatusCode Status, JsonElement Body, string? Total, string? Truncated, string Text)> Listed( + EdgeFixture f, string url) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + var text = await response.Content.ReadAsStringAsync(); + var body = response.StatusCode == HttpStatusCode.OK && text.Length > 0 + ? JsonDocument.Parse(text).RootElement + : default; + return (response.StatusCode, body, Header(response, "X-Total-Count"), Header(response, "X-Truncated"), text); + } + + private static async Task FromAsync(EdgeFixture f, string path, string sourceIp) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); + using var response = await f.Client.SendAsync(request); + return response.StatusCode; + } + + private static string[] MatchesOf(JsonElement body) => + body.EnumerateArray().Select(e => e.GetProperty("match").GetString()!).ToArray(); + + /// + /// Rows are written straight to the database because the API cannot be asked + /// for an expiry in the past — expiresInMinutes is 1..5,256,000, which is the + /// fix from an earlier cycle and is not about to be loosened to make a test + /// easier. The backdated row is exactly what a minute of waiting produces. + /// + private static async Task SeedAllow(EdgeFixture f, string match, DateTimeOffset? expiresAt) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.AllowEntries.Add(new AllowEntry + { + Match = match, + Note = "seeded", + CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-120), + ExpiresAt = expiresAt + }); + await db.SaveChangesAsync(); + await f.Service().InvalidateAsync(); + } + + [Fact] + public async Task An_expired_exemption_is_out_of_the_default_listing_and_says_it_expired_in_the_full_one() + { + await using var f = new EdgeFixture(); + await SeedAllow(f, Expired, DateTimeOffset.UtcNow.AddMinutes(-1)); + await SeedAllow(f, Live, null); + + var defaults = await Listed(f, "/admin-api/allow"); + Assert.Equal(HttpStatusCode.OK, defaults.Status); + Assert.Equal(["203.0.113.89"], MatchesOf(defaults.Body)); + Assert.Equal("1", defaults.Total); + Assert.Equal("false", defaults.Truncated); + + var everything = await Listed(f, "/admin-api/allow?live=false"); + Assert.Equal(["203.0.113.88", "203.0.113.89"], MatchesOf(everything.Body)); + Assert.Equal("2", everything.Total); + var dead = everything.Body.EnumerateArray().Single(e => e.GetProperty("match").GetString() == Expired); + Assert.False(dead.GetProperty("live").GetBoolean()); + var alive = everything.Body.EnumerateArray().Single(e => e.GetProperty("match").GetString() == Live); + Assert.True(alive.GetProperty("live").GetBoolean()); + } + + [Fact] + public async Task The_allow_listing_and_the_wire_give_the_same_answer_about_an_expired_exemption() + { + await using var f = new EdgeFixture(); + // An operator block on both addresses, so the only thing that can let + // either one through is its allow entry. + using (var scope = f.Factory.Services.CreateScope()) + { + var store = scope.ServiceProvider.GetRequiredService(); + foreach (var ip in new[] { Expired, Live }) + await store.AddOperatorAsync(ip, "c28 seed", null, DateTimeOffset.UtcNow); + } + await SeedAllow(f, Expired, DateTimeOffset.UtcNow.AddMinutes(-1)); + await SeedAllow(f, Live, null); + + Assert.Equal(HttpStatusCode.NotFound, await FromAsync(f, "/anything", Live)); + Assert.Equal(HttpStatusCode.MovedPermanently, await FromAsync(f, "/anything", Expired)); + + // The number the page puts in its pill has to be the number of + // exemptions the edge is honouring, not the number of rows. + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state"); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(1, state.GetProperty("allowEntries").GetInt32()); + Assert.Equal(1, state.GetProperty("allowEntriesExpired").GetInt32()); + } + + [Fact] + public async Task The_allow_listing_is_capped_and_says_so_and_the_offset_reaches_the_rest() + { + await using var f = new EdgeFixture(); + for (var i = 1; i <= 5; i++) + await SeedAllow(f, $"198.51.100.{i}", null); + + var first = await Listed(f, "/admin-api/allow?limit=2"); + Assert.Equal("5", first.Total); + Assert.Equal("true", first.Truncated); + Assert.Equal(2, MatchesOf(first.Body).Length); + + var seen = new List(); + for (var offset = 0; offset < 5; offset++) + { + var page = await Listed(f, $"/admin-api/allow?limit=1&offset={offset}"); + Assert.Equal("5", page.Total); + seen.AddRange(MatchesOf(page.Body)); + } + Assert.Equal(5, seen.Distinct().Count()); + + var whole = await Listed(f, "/admin-api/allow?limit=2000"); + Assert.Equal("false", whole.Truncated); + Assert.Equal(5, MatchesOf(whole.Body).Length); + } + + [Fact] + public async Task A_paging_limit_nobody_meant_on_the_allow_listing_is_refused_by_name() + { + await using var f = new EdgeFixture(); + await SeedAllow(f, Live, null); + + foreach (var (query, expected) in new[] + { + ("?limit=0", "limit must be 1..2000; got 0"), + ("?limit=-1", "limit must be 1..2000; got -1"), + ("?limit=2001", "limit must be 1..2000; got 2001"), + ("?offset=-1", "offset must be 0 or more; got -1") + }) + { + var bad = await Listed(f, "/admin-api/allow" + query); + Assert.Equal(HttpStatusCode.BadRequest, bad.Status); + Assert.Contains(expected, bad.Text); + } + } +} diff --git a/scripts/ci-linux-rehearsal.sh b/scripts/ci-linux-rehearsal.sh index dcb2584..d2436e3 100755 --- a/scripts/ci-linux-rehearsal.sh +++ b/scripts/ci-linux-rehearsal.sh @@ -173,7 +173,11 @@ if [ "$STAGE" = all ] || [ "$STAGE" = console ]; then SEED_ERROR=$(sed -n 's/^SEED_ERROR=//p' console-seed.env 2>/dev/null) SEED_MARKUP_PATH=$(sed -n 's/^SEED_MARKUP_PATH=//p' console-seed.env 2>/dev/null) SEED_MARKUP_BLOCK=$(sed -n 's/^SEED_MARKUP_BLOCK=//p' console-seed.env 2>/dev/null) + SEED_EXPIRED_CIDR=$(sed -n 's/^SEED_EXPIRED_CIDR=//p' console-seed.env 2>/dev/null) [ -n "$SEED_ERROR" ] || { echo 'console stage: no SEED_ERROR in console-seed.env' >&2; console_status=1; } + # Empty here would make the expired-exemption assertion look at '' and fail, + # which is the right outcome but the wrong reason, so it is named instead. + [ -n "$SEED_EXPIRED_CIDR" ] || { echo 'console stage: no SEED_EXPIRED_CIDR in console-seed.env' >&2; console_status=1; } fi if [ "$console_status" -eq 0 ]; then @@ -184,6 +188,7 @@ if [ "$STAGE" = all ] || [ "$STAGE" = console ]; then -e SEED_SOURCE=203.0.113.55 -e SEED_BLOCK=203.0.113.77 \ -e SEED_ERROR="$SEED_ERROR" \ -e SEED_MARKUP_PATH="$SEED_MARKUP_PATH" -e SEED_MARKUP_BLOCK="$SEED_MARKUP_BLOCK" \ + -e SEED_EXPIRED_CIDR="$SEED_EXPIRED_CIDR" \ -e SCREENSHOT=/tmp/console-linux.png \ -e CHECK="$PWD/scripts/console-check.cjs" \ -e PW_VERSION="$PLAYWRIGHT_VERSION" \ diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 8bf8633..948f544 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -166,6 +166,21 @@ check 'operator block survives the clear' '301' "$(code -H "$(xff "$OFFICE")" "$ echo '- allowlist outranks the operator block' admin -X POST -H 'Content-Type: application/json' -d "{\"match\":\"$OFFICE\",\"note\":\"smoke\"}" "$EDGE/admin-api/allow" >/dev/null check 'allowlisted source gets through' '404' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")" +# The exemption listing was the one listing with no ceiling and no liveness. +# Measured on the shipped image: 1101 rows came back in 130,386 bytes with no +# X-Total-Count and no X-Truncated, ?limit=10 / ?offset=1000 / ?limit=0 / +# ?limit=100000 each returned all 1101, and a row whose minute had passed was +# printed as an exemption the edge still honoured (it was not — that address had +# gone back to 301 a minute earlier). The row is not the answer, so the answer +# now travels with it. +check 'the allow listing says how many rows there are' 'yes' \ + "$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/allow" | grep -qi '^x-total-count:' && echo yes || echo no)" +check 'the allow listing marks the entry live' '1' \ + "$(admin "$EDGE/admin-api/allow" | jcount "b['match']=='$OFFICE' and b['live']")" +check 'the allow listing refuses a limit nobody meant' '400' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/allow?limit=0")" +check 'and names the parameter it is refusing' 'limit must be 1..2000; got 0' \ + "$(admin "$EDGE/admin-api/allow?limit=0" | jval error)" ALLOW_ID=$(admin "$EDGE/admin-api/allow" | sed -n 's/.*"id":\([0-9]*\).*/\1/p' | head -1) admin -X DELETE "$EDGE/admin-api/allow/$ALLOW_ID" >/dev/null check 'block returns when the allow entry goes' '301' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")" diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index e25b992..2d542ac 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -22,6 +22,9 @@ const SEED_ERROR = process.env.SEED_ERROR || ''; // person reading this page. const SEED_MARKUP_PATH = process.env.SEED_MARKUP_PATH || ''; const SEED_MARKUP_BLOCK = process.env.SEED_MARKUP_BLOCK || ''; +// An allow entry the seed wrote a minute ago, with a one-minute TTL. The edge +// stopped honouring it; the row is still in the table. +const SEED_EXPIRED_CIDR = process.env.SEED_EXPIRED_CIDR || ''; let chromium; try { @@ -74,6 +77,20 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); const summary = (await page.textContent('#summary')).replace(/\s+/g, ' ').trim(); const cells = (sel) => page.$$eval(sel, (rows) => rows.map((tr) => [...tr.children].map((td) => td.textContent))); + // The allow table can hold several rows at once, so a delete has to be aimed at + // one of them: "click the first remove button" deletes whatever the server + // happened to sort first, which is not the row this assertion is about. + const removeAllow = async (match) => { + await page.evaluate((m) => { + const tr = [...document.querySelectorAll('#allow tbody tr')] + .find((r) => r.children[0].textContent === m); + const b = tr && tr.querySelector('button[data-act="delallow"]'); + if (b) b.click(); + }, match); + await page.waitForFunction( + (m) => ![...document.querySelectorAll('#allow tbody tr')].some((r) => r.children[0].textContent === m), + match, { timeout: 15000 }).catch(() => {}); + }; const streakRows = await cells('#streaks tbody tr'); const blockRows = await cells('#blocks tbody tr'); const obsRows = await page.$$eval('#obs tbody tr', (r) => r.length); @@ -244,10 +261,7 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); allowRows.some((r) => r[0] === WRITE_CIDR && /console gate/.test(r[1] || '') && /\d{4}-\d{2}-\d{2}/.test(r[2] || '')), JSON.stringify(allowRows.map((r) => [r[0], r[2]]))); - await page.click(`#allow tbody button[data-act="delallow"]`); - await page.waitForFunction( - (cidr) => ![...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr), - WRITE_CIDR, { timeout: 15000 }).catch(() => {}); + await removeAllow(WRITE_CIDR); check('the allow entry can be removed from the page too', (await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))).indexOf(WRITE_CIDR) === -1, JSON.stringify(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent)))); @@ -278,10 +292,35 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); check('leaving the TTL empty is still the way to ask for never', neverRows.some((r) => r[0] === WRITE_CIDR && /never/.test(r[2] || '')), JSON.stringify(neverRows.map((r) => [r[0], r[2]]))); - await page.click('#allow tbody button[data-act="delallow"]'); + await removeAllow(WRITE_CIDR); + + // The state the page used to get wrong: an allow entry with an expiry stops + // being obeyed the moment it ages, and the row outlives it — nothing prunes an + // operator's own rows, and the API cannot be asked for an expiry in the past. + // Measured on the shipped image: the exempted address answered 502 (through) + // at 03:58:20 and 301 (blocked again) at 03:59:38, while GET /admin-api/allow + // at 03:59:39 still printed the row with no liveness field and /admin-api/state + // still counted it. So the table said "exempted" a minute after the edge + // stopped honouring it. The seed wrote SEED_EXPIRED_CIDR a minute ago. + await page.fill('#allowMatch', WRITE_CIDR); + await page.fill('#allowNote', 'console gate: still live'); + await page.fill('#allowTtl', '60'); + await page.click('#addAllow'); await page.waitForFunction( - (cidr) => ![...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr), + (cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr), WRITE_CIDR, { timeout: 15000 }).catch(() => {}); + const liveAndDead = await cells('#allow tbody tr'); + check('a live allow entry is listed with no expired marker', + liveAndDead.some((r) => r[0] === WRITE_CIDR && !/EXPIRED/i.test(r[2] || '')), + JSON.stringify(liveAndDead.map((r) => [r[0], r[2]]))); + check('an expired allow entry is still listed, and says the edge no longer honours it', + liveAndDead.some((r) => r[0] === SEED_EXPIRED_CIDR && /EXPIRED/.test(r[2] || '')), + JSON.stringify(liveAndDead.map((r) => [r[0], r[2]]))); + const allowNote = (await page.textContent('#allownote')).replace(/\s+/g, ' ').trim(); + check('and the line under the table counts the dead rows rather than hiding them', + /EXPIRED/.test(allowNote), JSON.stringify(allowNote)); + await removeAllow(SEED_EXPIRED_CIDR); + await removeAllow(WRITE_CIDR); // The failure mode worth asserting on a write form is the quiet one: the // operator believes they blocked an address and did not. A typo in the field diff --git a/scripts/console-smoke.sh b/scripts/console-smoke.sh index 7121185..61d627d 100755 --- a/scripts/console-smoke.sh +++ b/scripts/console-smoke.sh @@ -22,7 +22,13 @@ SEED_BLOCK=203.0.113.77 # `compose down`, so a fixed address here would let last week's alert satisfy the # assertion. A fresh one makes the check about this run. SEED_ERROR="203.0.113.$(( 140 + RANDOM % 60 ))" -export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK +# An allow entry whose minute has passed by the time the page is driven. Seeded +# before the two waits this script already pays, so it costs no extra second and +# produces the state the shipped image printed as a live exemption: the row is +# still in the table, the edge stopped honouring it a minute ago. Chosen per run, +# so a leftover row in the data volume cannot satisfy the assertion. +SEED_EXPIRED_CIDR="203.0.113.$(( 240 + RANDOM % 10 ))/32" +export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK SEED_EXPIRED_CIDR admin() { curl -s -m 10 -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; } @@ -33,7 +39,9 @@ cleanup() { # The page can write allow entries. The gate removes the one it added, but if # it failed before that step the entry would outlive the run inside the data # volume and quietly change the next run — so clear them here too. - for id in $(admin "$EDGE/admin-api/allow" | tr ',' '\n' | sed -n 's/.*"id":\([0-9]*\).*/\1/p'); do + # live=false: the default listing hides the expired rows, and an expired row + # left in the volume quietly changes what the next run's table shows. + for id in $(admin "$EDGE/admin-api/allow?live=false&limit=2000" | tr ',' '\n' | sed -n 's/.*"id":\([0-9]*\).*/\1/p'); do admin -X DELETE "$EDGE/admin-api/allow/$id" >/dev/null 2>&1 done # The gate sets a US country rule and removes it again. PUT allowed=true would @@ -58,6 +66,13 @@ done # the same TTL the multi-instance measurement is about. admin -X PUT -H 'Content-Type: application/json' \ -d '{"mode":"Enforce","geo":"Off","streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null +# The expiring exemption is seeded here, ahead of the waits below, so it has aged +# out by the time the page is driven without adding a second to the gate. The API +# cannot be asked for an expiry in the past — expiresInMinutes is 1..5,256,000 — +# so waiting is the only honest way to produce this state. +admin -X POST -H 'Content-Type: application/json' \ + -d "{\"match\":\"$SEED_EXPIRED_CIDR\",\"note\":\"console gate: expired exemption\",\"expiresInMinutes\":1}" \ + "$EDGE/admin-api/allow" >/dev/null sleep 31 echo '- seeding what the page must show' @@ -102,8 +117,8 @@ if [ "${SEED_ONLY:-0}" = 1 ]; then # page in a browser image), so it cannot inherit these values. Writing them out # is what keeps the alert assertion honest: SEED_ERROR is chosen per run, and an # empty one on the driver side would silently weaken the check to "any alert". - printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\n' \ - "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" > "${SEED_FILE:-console-seed.env}" + printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\nSEED_EXPIRED_CIDR=%s\n' \ + "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" "$SEED_EXPIRED_CIDR" > "${SEED_FILE:-console-seed.env}" echo "- SEED_ONLY=1: stack is up and seeded at $EDGE; seed values in ${SEED_FILE:-console-seed.env}" trap - EXIT exit 0 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 2563838..084bb33 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -104,6 +104,18 @@ check 'the blocked office address gets through' 404 \ "$(code -H "X-Forwarded-For: $OFFICER" "$(from anything)")" check 'the scanner outside that range stays banned' 403 \ "$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")" +# The exemption listing used to be the only listing with no ceiling: every paging +# parameter was ignored and the response said nothing about how many rows there +# were. Measured on the shipped image: 1101 rows, 130,386 bytes, no X-Total-Count, +# and ?limit=10 answered all 1101. +check 'the allow listing says how many rows there are' yes \ + "$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow" | grep -qi '^x-total-count:' && echo yes || echo no)" +check 'the allow listing refuses a limit nobody meant' 400 \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?limit=0")" +check 'a page of one is a page of one' 1 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow?limit=1" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" echo '- expiry and clearing' sleep 7