diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index fc52ab9..f21243f 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -144,12 +144,34 @@ async function apiRaw(path, opts = {}) { const r = await fetch(path, Object.assign({}, opts, { headers })); if (r.status === 401) { note('token rejected', true); throw new Error('401'); } if (r.status === 404) { note('admin api disabled — set OpenWaf__Admin__Token', true); throw new Error('404'); } - const body = r.status === 204 ? null : await r.json(); + let body = null; + if (r.status !== 204) { + try { + body = await r.json(); + } catch (e) { + // An empty 5xx is still an answer, and it used to be an answer the page + // swallowed: r.json() threw, the caller's catch said "note() already said + // why", and nothing had been said. The status line went quiet exactly + // when the edge had the worst news to report. + body = r.ok ? null : { error: 'the edge answered ' + r.status + ' with no explanation' }; + } + } return { body, total: r.headers.get('X-Total-Count'), truncated: r.headers.get('X-Truncated') === 'true' }; } async function api(path, opts = {}) { return (await apiRaw(path, opts)).body; } +// The answer carried a reason this call did not work. Every write on this page +// has to ask before it says it worked — the note in the status line is the only +// feedback a click gets, and a green note over an error answer is the page +// repeating the API's old lie: "deleted 0" when nothing could be deleted. +let holdNote = false; + +function failed(r) { + if (r.body && r.body.error) { note(r.body.error, true); holdNote = true; return true; } + return false; +} + function note(text, bad) { const s = el('status'); s.textContent = text; @@ -286,7 +308,17 @@ async function load() { ? ' ' : '') } ])).join('') || row([{ v: 'none' }]); - note('refreshed ' + new Date().toLocaleTimeString(), false); + // A refresh that worked must not erase the reason the click before it did + // not: load() runs after every row action, and its green "refreshed" used to + // replace the error line within a second, which is roughly how long an + // operator takes to read it. + // A refresh that worked must not erase the reason the click before it did + // not: every row action ends with load(), and its green "refreshed" used to + // replace the error line inside a second — about how long the line takes to + // read. Only the refresh that follows the failed action holds the note; the + // next one says "refreshed" again, so the page does not stay red forever. + if (holdNote) holdNote = false; + else note('refreshed ' + new Date().toLocaleTimeString(), false); } catch (e) { /* note() already said why */ } } @@ -303,8 +335,7 @@ el('save').onclick = () => { async function postJson(path, body) { const r = await apiRaw(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); - if (r.body && r.body.error) { note(r.body.error, true); return false; } - return true; + return !failed(r); } el('addBlock').onclick = async () => { @@ -349,29 +380,36 @@ document.addEventListener('click', async (e) => { const b = e.target.closest('button[data-act]'); if (!b) return; b.disabled = true; + // A new action owns the status line from now on. + holdNote = false; try { if (b.dataset.act === 'delblock') { - const r = await api('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); - note('deleted ' + (r && r.deleted !== undefined ? r.deleted : '?') + ' block(s)', false); + const r = await apiRaw('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); + if (!failed(r)) note('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)', false); } else if (b.dataset.act === 'delallow') { - await api('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); - note('allow entry removed', false); + const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); + if (!failed(r)) note('allow entry removed', false); } else if (b.dataset.act === 'country') { - await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' }); - note('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'), false); + const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' }); + if (!failed(r)) note('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'), false); } else if (b.dataset.act === 'countrydel') { - await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); - note('country rule ' + b.dataset.k + ' removed', false); + const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); + if (!failed(r)) note('country rule ' + b.dataset.k + ' removed', false); } load(); } catch (err) { /* note() already said why */ } b.disabled = false; }); -el('refresh').onclick = load; +el('refresh').onclick = () => { holdNote = false; load(); }; el('setMode').onclick = async () => { - await api('/admin-api/policy', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ mode: el('mode').value }) }); + // The mode select is the one control that decides whether this edge bans + // anyone at all. It used to fire the PUT, ignore the answer and reload: a + // change the storage refused reloaded to the old mode with no explanation. + const wanted = el('mode').value; + const r = await apiRaw('/admin-api/policy', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: wanted }) }); + if (!failed(r)) note('mode → ' + wanted, false); load(); }; el('clearEngine').onclick = async () => { diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 72f41a3..1e82d99 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -96,8 +96,18 @@ internal static class AdminEndpoints // come back as 500 with no body — the block itself broke. if (req.RedirectTo is not null && !RedirectTarget.IsSendable(req.RedirectTo)) return Results.BadRequest(new { error = $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{req.RedirectTo}\"" }); - var (ok, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct); - return ok ? Results.NoContent() : Results.BadRequest(new { error }); + var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct); + // Two different failures used to arrive as the same 400. A rejected + // input and a storage failure are not the same event: one is fixed + // by editing the request, the other by fixing the database, and a + // 400 tells the operator to do the first while the block they asked + // for is not in effect. + return added switch + { + BlockStore.AddResult.Ok => Results.NoContent(), + BlockStore.AddResult.InvalidInput => Results.BadRequest(new { error }), + _ => StorageUnavailable(error!) + }; }); // Provenance is part of the delete, not an afterthought: "clear the @@ -107,7 +117,14 @@ internal static class AdminEndpoints if (!TryParseSource(source, out var parsed)) return BadSource(source); if (parsed is null && string.IsNullOrWhiteSpace(key)) return Results.BadRequest(new { error = "refusing to delete every block: pass source=operator|engine or key=..." }); - var n = await store.DeleteAsync(parsed, key, ct); + var (result, n) = await store.DeleteAsync(parsed, key, ct); + // {"deleted":0} is a fact about the list, so it may only be said + // when the delete actually ran. Measured on the shipped image with + // the block table gone: 200 {"deleted":0} for a list that held two + // operator blocks — indistinguishable from "there was nothing to + // remove", which is how an operator stops trusting the count. + if (result == BlockStore.DeleteResult.StorageFailure) + return StorageUnavailable("the block list could not be read or written: NOTHING was deleted"); return Results.Ok(new { deleted = n }); }); @@ -190,7 +207,14 @@ internal static class AdminEndpoints // The toggle is a policy change, never a data change: switching // automatic banning off must leave every row — manual or engine — // exactly where it was. - await policy.SaveAsync(overrides, ct); + // SaveAsync says whether the row landed. Its answer used to be + // thrown away and the endpoint answered 200 with the policy body + // regardless, so a policy change the storage refused — the mode + // toggle, a threshold, the geo lists — read as done. The body even + // showed the old values, which an operator could only notice by + // reading the answer they had just asked for. + if (!await policy.SaveAsync(overrides, ct)) + return StorageUnavailable("the policy could not be written: the change is NOT in effect"); // The policy lives inside the snapshot the guard reads, so saving // it without refreshing the snapshot would leave the toggle // appearing to work in the API and not on the wire. @@ -475,6 +499,15 @@ internal static class AdminEndpoints private static IResult BadSource(string? source) => Results.BadRequest(new { error = $"source must be operator|engine|all; got \"{source}\"" }); + /// + /// The answer for "the storage could not do this". 503, not 400: the + /// request was fine. 503, not 200: nothing happened. The body keeps the + /// error shape the console already renders, so the operator sees the + /// sentence rather than an empty 5xx. + /// + private static IResult StorageUnavailable(string error) + => Results.Json(new { error }, statusCode: StatusCodes.Status503ServiceUnavailable); + private static bool FixedTimeEquals(string a, string b) { if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false; diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 2881e90..1fdb3f4 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -97,7 +97,13 @@ app.MapGet("/readyz", async (OpenWafDbContext db, CancellationToken ct) => { try { - await db.Database.CanConnectAsync(ct); + // CanConnectAsync only proves the file opens. Measured on the shipped + // image with the block table dropped out from under a running edge: + // every block write, delete and listing failed, and /readyz kept + // answering 200. "Ready" has to mean the table the operator's commands + // touch is actually readable, because this is the surface an operator + // or an orchestrator consults to decide whether the edge is healthy. + await db.Blocks.AsNoTracking().AnyAsync(ct); return Results.Ok(new { status = "ready" }); } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs index 75f2cd2..f066854 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -121,44 +121,77 @@ public sealed class BlockStore } } - public async Task<(bool Ok, string? Error)> AddOperatorAsync( + /// What a write to the block list ended as. The caller has to be + /// able to tell "your input was wrong" from "the storage failed", because + /// those two arrive at the operator as different answers and different + /// next actions — and until now they arrived as the same 400. + public enum AddResult { Ok, InvalidInput, StorageFailure } + + /// + /// Add or refresh an operator block. + /// + /// Two attempts, deliberately: the read-then-insert below is not atomic and + /// the unique index on (source key, provenance) is what makes the loser of + /// that race throw. Measured on the shipped image (openwaf:ci, head + /// 72d37ad) with six concurrent POSTs for one address: 4 answered 204 and 2 + /// answered 400 {"error":"database error"} — the block was in effect + /// either way, so what the operator saw was a 400 blaming their own request + /// for a race the API itself caused. That is exactly what a double-click in + /// the console looks like. The retry takes the winner's row and updates it, + /// which is the same path a sequential repeat already takes. + /// + public async Task<(AddResult Result, string? Error)> AddOperatorAsync( string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default) { if (!SourceKey.TryParse(sourceKey, out _, out var normalized)) - return (false, $"not an IP address: {sourceKey}"); + return (AddResult.InvalidInput, $"not an IP address: {sourceKey}"); var key = SourceKey.For(normalized.ToString(), _policy.Current); - try + for (var attempt = 0; attempt < 2; attempt++) { - using var scope = _scopeFactory.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct); - if (row is null) + try { - db.Blocks.Add(new BlockEntry + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct); + if (row is null) { - SourceKey = key, - Source = BlockSource.Operator, - CreatedAt = now, - Reason = reason, - RedirectTo = redirectTo - }); + db.Blocks.Add(new BlockEntry + { + SourceKey = key, + Source = BlockSource.Operator, + CreatedAt = now, + Reason = reason, + RedirectTo = redirectTo + }); + } + else + { + row.Reason = reason ?? row.Reason; + row.RedirectTo = redirectTo ?? row.RedirectTo; + } + await db.SaveChangesAsync(ct); + await _state.InvalidateAsync(ct); + return (AddResult.Ok, null); } - else + catch (DbUpdateException ex) when (attempt == 0) { - row.Reason = reason ?? row.Reason; - row.RedirectTo = redirectTo ?? row.RedirectTo; + _log.LogWarning(ex, "BlockStore: concurrent add on {Key}; retrying against the winner's row.", key); + } + catch (Exception ex) + { + // Not the caller's fault, and not a success either. The old + // answer was a 400 whose only content was "database error", + // which reads like a rejected request: an operator who retried + // got the same 400 and moved on, while the block they typed was + // never in effect. + _log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key); + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); } - await db.SaveChangesAsync(ct); - await _state.InvalidateAsync(ct); - return (true, null); - } - catch (Exception ex) - { - _log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key); - return (false, "database error"); } + + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); } /// @@ -166,7 +199,21 @@ public sealed class BlockStore /// filter is not cosmetic: "clear the automatic bans" must never be able to /// erase what an operator typed by hand, which is exactly what R1 forbids. /// - public async Task DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default) + public enum DeleteResult { Ok, StorageFailure } + + /// + /// Delete blocks, optionally restricted to one provenance. The provenance + /// filter is not cosmetic: "clear the automatic bans" must never be able to + /// erase what an operator typed by hand, which is exactly what R1 forbids. + /// + /// The count is only meaningful when the result is Ok. Returning 0 from the + /// catch was the bug: measured on the shipped image with the block table + /// dropped out from under a running edge that held two operator blocks, + /// DELETE ?source=operator answered 200 {"deleted":0} — the + /// same bytes the operator gets when the list really is empty. A destructive + /// command that cannot run has to say it did not run. + /// + public async Task<(DeleteResult Result, int Deleted)> DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default) { try { @@ -177,12 +224,12 @@ public sealed class BlockStore if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey); var n = await q.ExecuteDeleteAsync(ct); await _state.InvalidateAsync(ct); - return n; + return (DeleteResult.Ok, n); } catch (Exception ex) { _log.LogWarning(ex, "BlockStore: delete failed."); - return 0; + return (DeleteResult.StorageFailure, 0); } } diff --git a/dotnet/OpenWaf.Tests.Integration/StorageFailureHonestyTests.cs b/dotnet/OpenWaf.Tests.Integration/StorageFailureHonestyTests.cs new file mode 100644 index 0000000..42242f3 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/StorageFailureHonestyTests.cs @@ -0,0 +1,217 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Three answers the admin surface gave when the storage could not do what it +/// was asked. All three were measured on the shipped image (openwaf:ci built +/// from 72d37ad) against a running edge whose block table was dropped out from +/// under it with an external sqlite client, while the edge kept serving: +/// +/// DELETE /admin-api/blocks?source=operator → 200 {"deleted":0} +/// DELETE /admin-api/blocks?key=203.0.113.201 → 200 {"deleted":0} +/// POST /admin-api/blocks {"ip":...} → 400 {"error":"database error"} +/// GET /admin-api/blocks → 500 (empty body) +/// GET /readyz → 200 {"status":"ready"} +/// +/// …and the list had held two operator blocks a moment earlier. So a destructive +/// command that never ran reported the same bytes as "there was nothing to +/// remove"; a write that failed blamed the caller with a 400; and the readiness +/// probe — the surface an operator or an orchestrator checks to decide whether +/// this edge is usable — said ready. +/// +/// The fourth measurement needs no broken storage at all: six concurrent POSTs +/// for the same address answered 4× 204 and 2× 400 {"error":"database error"}. +/// The unique index on (source key, provenance) made the loser of a race the API +/// itself started look like a caller who sent a bad request — which is what a +/// double-click on "block" in the console looks like. +/// +public sealed class StorageFailureHonestyTests +{ + private const string Blocked = "203.0.113.201"; + private const string AlsoBlocked = "203.0.113.202"; + + private static Task<(HttpStatusCode Status, string Body)> AdminAsync( + EdgeFixture f, HttpMethod method, string url, string? json = null) + => AdminAsync(f.Client, method, url, json); + + private static async Task<(HttpStatusCode Status, string Body)> AdminAsync( + HttpClient client, HttpMethod method, string url, string? json = null) + { + using var request = new HttpRequestMessage(method, url); + if (json is not null) + request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await client.SendAsync(request); + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } + + /// + /// The same damage the probe stand did from outside the container: the + /// table the block commands touch stops existing while the edge is serving. + /// + private static async Task DropBlockTableAsync(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.ExecuteSqlRawAsync("DROP TABLE block_entries"); + } + + private static async Task BlockRowsAsync(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Blocks.CountAsync(); + } + + private static string? ErrorOf(string body) => + JsonDocument.Parse(body).RootElement.TryGetProperty("error", out var e) ? e.GetString() : null; + + [Fact] + public async Task A_delete_that_could_not_run_says_so_instead_of_reporting_zero_deleted() + { + await using var f = new EdgeFixture(); + + // Control: while the storage works, the count is a fact about the list. + Assert.Equal(HttpStatusCode.NoContent, (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + $$"""{"ip":"{{Blocked}}","reason":"first"}""")).Status); + Assert.Equal(HttpStatusCode.NoContent, (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + $$"""{"ip":"{{AlsoBlocked}}","reason":"second"}""")).Status); + var (beforeStatus, beforeBody) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/blocks?source=operator"); + Assert.Equal(HttpStatusCode.OK, beforeStatus); + Assert.Equal("""{"deleted":2}""", beforeBody); + + await DropBlockTableAsync(f); + + var (status, body) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/blocks?source=operator"); + + // Before the fix this was exactly 200 {"deleted":0} — the same answer an + // empty list gives. + Assert.Equal(HttpStatusCode.ServiceUnavailable, status); + Assert.NotNull(ErrorOf(body)); + Assert.Contains("NOTHING was deleted", body); + } + + [Fact] + public async Task A_delete_by_key_reports_the_failure_the_same_way() + { + await using var f = new EdgeFixture(); + await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", $$"""{"ip":"{{Blocked}}"}"""); + await DropBlockTableAsync(f); + + var (status, body) = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/blocks?key={Blocked}"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, status); + Assert.Contains("NOTHING was deleted", body); + } + + [Fact] + public async Task An_empty_list_is_still_a_200_with_zero_and_not_a_failure() + { + await using var f = new EdgeFixture(); + + var (status, body) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/blocks?source=engine"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("""{"deleted":0}""", body); + } + + [Fact] + public async Task A_block_that_was_not_written_is_not_reported_as_the_callers_request_being_bad() + { + await using var f = new EdgeFixture(); + await DropBlockTableAsync(f); + + var (status, body) = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + $$"""{"ip":"{{Blocked}}","reason":"while the table is gone"}"""); + + // Before the fix: 400 {"error":"database error"} — a 400 invites the + // operator to fix the request and move on, while no block is in effect. + Assert.Equal(HttpStatusCode.ServiceUnavailable, status); + Assert.Contains("NOT in effect", body); + Assert.DoesNotContain("database error", body); + } + + [Fact] + public async Task Readyz_notices_a_block_table_that_is_not_there() + { + await using var f = new EdgeFixture(); + + using (var ok = await f.Client.GetAsync("/readyz")) + Assert.Equal(HttpStatusCode.OK, ok.StatusCode); + + await DropBlockTableAsync(f); + + using var broken = await f.Client.GetAsync("/readyz"); + // CanConnectAsync answered true for the whole of this test: the file is + // there and opens. What is missing is the table every block command + // needs, and that is the thing readiness has to prove. + Assert.Equal(HttpStatusCode.ServiceUnavailable, broken.StatusCode); + } + + [Fact] + public async Task A_policy_change_the_storage_refused_is_not_reported_as_applied() + { + await using var f = new EdgeFixture(); + + // Control: with the storage working the toggle lands and the body says + // which mode the edge is now enforcing. + var (okStatus, okBody) = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", """{"mode":"Observe"}"""); + Assert.Equal(HttpStatusCode.OK, okStatus); + Assert.Equal("Observe", JsonDocument.Parse(okBody).RootElement.GetProperty("mode").GetString()); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.ExecuteSqlRawAsync("DROP TABLE policy_settings"); + } + + var (status, body) = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", """{"mode":"Enforce"}"""); + + // SaveAsync returns false here and the endpoint used to discard it, so + // this was 200 — with a body carrying the mode that was NOT saved. + Assert.Equal(HttpStatusCode.ServiceUnavailable, status); + Assert.Contains("NOT in effect", body); + } + + [Fact] + public async Task Concurrent_blocks_of_one_address_all_land_instead_of_blaming_the_caller() + { + await using var f = new EdgeFixture(); + + // A barrier, not a loop: the collision the shipped image produced needs + // every request to reach the read-then-insert window at the same moment. + using var start = new ManualResetEventSlim(false); + var client = f.Client; + // Warm the host up first: WebApplicationFactory starts the host (and + // with it the migration) on the first client, and 16 threads asking for + // a client at once make the migration race with itself. + await client.GetAsync("/healthz"); + var tasks = Enumerable.Range(1, 16).Select(i => Task.Run(async () => + { + start.Wait(); + return await AdminAsync(client, HttpMethod.Post, "/admin-api/blocks", + $$"""{"ip":"{{Blocked}}","reason":"click {{i}}"}"""); + })).ToArray(); + start.Set(); + var responses = await Task.WhenAll(tasks); + + // Measured on the shipped image: 4× 204 and 2× 400 {"error":"database + // error"} out of six. The block was in effect either way, so the 400 was + // a lie about the request, not about the outcome. + Assert.All(responses, r => Assert.Equal(HttpStatusCode.NoContent, r.Status)); + Assert.Equal(1, await BlockRowsAsync(f)); + + // One row, and the note on it is one of the eight clicks — the same + // last-write-wins a sequential repeat already has. + var (_, listing) = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks"); + var reasons = JsonDocument.Parse(listing).RootElement.EnumerateArray() + .Select(e => e.GetProperty("reason").GetString()).ToList(); + Assert.Single(reasons); + Assert.Contains(reasons[0], Enumerable.Range(1, 16).Select(i => $"click {i}")); + } +} diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 9f9b421..a050cee 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -344,6 +344,34 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); afterRemove === '—' && !(await hasRemove()), `rule cell after remove: ${afterRemove}, remove button gone: ${!(await hasRemove())}`); + // Every destructive row button shares this one handler, and until now the + // handler wrote its green note whatever came back: a 400 whose body said + // "refusing to delete every block" still produced "deleted ? block(s)" in the + // success colour. The button is synthetic because the page only ever renders a + // remove button for a row that exists; the handler is delegated on the + // document, so this is the same code a real click runs. An empty key is the + // refused call — DELETE /admin-api/blocks?key= is the one destructive row + // request the API answers with a 400 and a reason. (A 404 would not do: the + // page reads every 404 as "the admin API is switched off", which is its own + // story and is recorded separately.) + await page.evaluate(() => { + const b = document.createElement('button'); + b.id = 'c26-refused-remove'; + b.dataset.act = 'delblock'; + b.dataset.k = ''; + document.body.appendChild(b); + }); + await page.click('#c26-refused-remove'); + await page.waitForFunction( + () => /refusing to delete every block/.test(document.getElementById('status').textContent), + null, { timeout: 10000 }).catch(() => {}); + const refusedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim(); + const refusedClass = await page.getAttribute('#status', 'class'); + await page.evaluate(() => { const b = document.getElementById('c26-refused-remove'); if (b) b.remove(); }); + check('a row action does not write a success note over an answer that said it failed', + /refusing to delete every block/.test(refusedStatus) && refusedClass === 'warn', + `${refusedClass}: ${refusedStatus}`); + // A phone in dark mode is the case an operator actually reaches the console // from — the address that got them blocked is the one they are typing about. // Both halves of this used to be broken and measured: the page overflowed a