A storage failure was reported to the operator as success, as their own bad request, and as ready
Measured on two shipped images of the same stand — openwaf:prefix built from
72d37ad and openwaf:ci built from this tree — with the block table and the
policy table dropped out from under a running edge that held 3 blocks and 1
policy row:
DELETE /admin-api/blocks?source=operator 200 {"deleted":0} -> 503 "NOTHING was deleted"
DELETE /admin-api/blocks?key=203.0.113.201 200 {"deleted":0} -> 503 "NOTHING was deleted"
POST /admin-api/blocks 400 database error -> 503 "the block is NOT in effect"
PUT /admin-api/policy {"mode":"Enforce"} 200, body mode=Observe -> 503 "the change is NOT in effect"
GET /admin-api/blocks 500 -> 500 (unchanged)
GET /readyz 200 ready -> 503
GET /healthz 200 -> 200 (unchanged: the recovery hatch)
Four separate lies, one class:
* BlockStore.DeleteAsync caught everything, logged a warning and returned 0, so
the endpoint answered {"deleted":0} — the same bytes an empty list produces.
A destructive command that could not run told the operator there was nothing
to remove.
* BlockStore.AddOperatorAsync returned the string "database error" and the
endpoint mapped it to 400, next to the real validation errors. A storage
failure arrived as "your request is wrong", which invites a retry of the
request while no block is in effect.
* PUT /admin-api/policy threw away SaveAsync's false and answered 200 with the
policy body — showing the mode that had NOT been saved.
* /readyz used CanConnectAsync, which only proves the file opens. It kept
answering 200 through all of the above.
The same stand, six concurrent POSTs for one address (no broken storage):
4x 204 and 2x 400 {"error":"database error"} before; 6x 204 after. 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 is. The write now retries against the winner's row.
The console had its own copy of the bug: every destructive row button wrote its
green note whatever came back, so a refused delete read as "deleted ? block(s)",
and load() — which runs after every action and on a 5 s interval — replaced the
error line with "refreshed" inside a second. The note now waits for an answer
that did not carry an error, and the refresh that follows a failed action holds
it. An empty 5xx body is now reported as an empty 5xx body instead of throwing
inside apiRaw and being swallowed.
Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 106/106 (7 new in StorageFailureHonestyTests), smoke 19/0,
compose 43/0, image 261 MB, console 45/45 (1 new assertion).
Dents: delete answers deleted:0 -> 2 fail; POST answers 400 -> 1; readyz trusts
CanConnectAsync -> 1; no retry after the unique-index loser -> 1; delete
swallows into a bare 0 -> 2; PUT /policy discards the save answer -> 1; console
writes the note whatever came back -> the console gate fails that assertion.
This commit is contained in:
@@ -144,12 +144,34 @@ async function apiRaw(path, opts = {}) {
|
|||||||
const r = await fetch(path, Object.assign({}, opts, { headers }));
|
const r = await fetch(path, Object.assign({}, opts, { headers }));
|
||||||
if (r.status === 401) { note('token rejected', true); throw new Error('401'); }
|
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'); }
|
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' };
|
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; }
|
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) {
|
function note(text, bad) {
|
||||||
const s = el('status');
|
const s = el('status');
|
||||||
s.textContent = text;
|
s.textContent = text;
|
||||||
@@ -286,7 +308,17 @@ async function load() {
|
|||||||
? ' <button data-act="countrydel" data-k="' + esc(c.code) + '">remove rule</button>'
|
? ' <button data-act="countrydel" data-k="' + esc(c.code) + '">remove rule</button>'
|
||||||
: '') }
|
: '') }
|
||||||
])).join('') || row([{ v: 'none' }]);
|
])).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 */ }
|
} catch (e) { /* note() already said why */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,8 +335,7 @@ el('save').onclick = () => {
|
|||||||
async function postJson(path, body) {
|
async function postJson(path, body) {
|
||||||
const r = await apiRaw(path, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
const r = await apiRaw(path, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(body) });
|
body: JSON.stringify(body) });
|
||||||
if (r.body && r.body.error) { note(r.body.error, true); return false; }
|
return !failed(r);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
el('addBlock').onclick = async () => {
|
el('addBlock').onclick = async () => {
|
||||||
@@ -349,29 +380,36 @@ document.addEventListener('click', async (e) => {
|
|||||||
const b = e.target.closest('button[data-act]');
|
const b = e.target.closest('button[data-act]');
|
||||||
if (!b) return;
|
if (!b) return;
|
||||||
b.disabled = true;
|
b.disabled = true;
|
||||||
|
// A new action owns the status line from now on.
|
||||||
|
holdNote = false;
|
||||||
try {
|
try {
|
||||||
if (b.dataset.act === 'delblock') {
|
if (b.dataset.act === 'delblock') {
|
||||||
const r = await api('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
const r = await apiRaw('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||||
note('deleted ' + (r && r.deleted !== undefined ? r.deleted : '?') + ' block(s)', false);
|
if (!failed(r)) note('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)', false);
|
||||||
} else if (b.dataset.act === 'delallow') {
|
} else if (b.dataset.act === 'delallow') {
|
||||||
await api('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||||
note('allow entry removed', false);
|
if (!failed(r)) note('allow entry removed', false);
|
||||||
} else if (b.dataset.act === 'country') {
|
} else if (b.dataset.act === 'country') {
|
||||||
await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' });
|
const r = await apiRaw('/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);
|
if (!failed(r)) note('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'), false);
|
||||||
} else if (b.dataset.act === 'countrydel') {
|
} else if (b.dataset.act === 'countrydel') {
|
||||||
await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||||
note('country rule ' + b.dataset.k + ' removed', false);
|
if (!failed(r)) note('country rule ' + b.dataset.k + ' removed', false);
|
||||||
}
|
}
|
||||||
load();
|
load();
|
||||||
} catch (err) { /* note() already said why */ }
|
} catch (err) { /* note() already said why */ }
|
||||||
b.disabled = false;
|
b.disabled = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
el('refresh').onclick = load;
|
el('refresh').onclick = () => { holdNote = false; load(); };
|
||||||
el('setMode').onclick = async () => {
|
el('setMode').onclick = async () => {
|
||||||
await api('/admin-api/policy', { method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
// The mode select is the one control that decides whether this edge bans
|
||||||
body: JSON.stringify({ mode: el('mode').value }) });
|
// 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();
|
load();
|
||||||
};
|
};
|
||||||
el('clearEngine').onclick = async () => {
|
el('clearEngine').onclick = async () => {
|
||||||
|
|||||||
@@ -96,8 +96,18 @@ internal static class AdminEndpoints
|
|||||||
// come back as 500 with no body — the block itself broke.
|
// come back as 500 with no body — the block itself broke.
|
||||||
if (req.RedirectTo is not null && !RedirectTarget.IsSendable(req.RedirectTo))
|
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}\"" });
|
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);
|
var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct);
|
||||||
return ok ? Results.NoContent() : Results.BadRequest(new { error });
|
// 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
|
// 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 (!TryParseSource(source, out var parsed)) return BadSource(source);
|
||||||
if (parsed is null && string.IsNullOrWhiteSpace(key))
|
if (parsed is null && string.IsNullOrWhiteSpace(key))
|
||||||
return Results.BadRequest(new { error = "refusing to delete every block: pass source=operator|engine or 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 });
|
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
|
// The toggle is a policy change, never a data change: switching
|
||||||
// automatic banning off must leave every row — manual or engine —
|
// automatic banning off must leave every row — manual or engine —
|
||||||
// exactly where it was.
|
// 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
|
// The policy lives inside the snapshot the guard reads, so saving
|
||||||
// it without refreshing the snapshot would leave the toggle
|
// it without refreshing the snapshot would leave the toggle
|
||||||
// appearing to work in the API and not on the wire.
|
// 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)
|
private static IResult BadSource(string? source)
|
||||||
=> Results.BadRequest(new { error = $"source must be operator|engine|all; got \"{source}\"" });
|
=> Results.BadRequest(new { error = $"source must be operator|engine|all; got \"{source}\"" });
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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
|
||||||
|
/// <c>error</c> shape the console already renders, so the operator sees the
|
||||||
|
/// sentence rather than an empty 5xx.
|
||||||
|
/// </summary>
|
||||||
|
private static IResult StorageUnavailable(string error)
|
||||||
|
=> Results.Json(new { error }, statusCode: StatusCodes.Status503ServiceUnavailable);
|
||||||
|
|
||||||
private static bool FixedTimeEquals(string a, string b)
|
private static bool FixedTimeEquals(string a, string b)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
|
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
|
||||||
|
|||||||
@@ -97,7 +97,13 @@ app.MapGet("/readyz", async (OpenWafDbContext db, CancellationToken ct) =>
|
|||||||
{
|
{
|
||||||
try
|
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" });
|
return Results.Ok(new { status = "ready" });
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|||||||
@@ -121,44 +121,77 @@ public sealed class BlockStore
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<(bool Ok, string? Error)> AddOperatorAsync(
|
/// <summary>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.</summary>
|
||||||
|
public enum AddResult { Ok, InvalidInput, StorageFailure }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <c>400 {"error":"database error"}</c> — 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(AddResult Result, string? Error)> AddOperatorAsync(
|
||||||
string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default)
|
string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (!SourceKey.TryParse(sourceKey, out _, out var normalized))
|
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);
|
var key = SourceKey.For(normalized.ToString(), _policy.Current);
|
||||||
|
|
||||||
try
|
for (var attempt = 0; attempt < 2; attempt++)
|
||||||
{
|
{
|
||||||
using var scope = _scopeFactory.CreateScope();
|
try
|
||||||
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
||||||
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct);
|
|
||||||
if (row is null)
|
|
||||||
{
|
{
|
||||||
db.Blocks.Add(new BlockEntry
|
using var scope = _scopeFactory.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||||
|
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct);
|
||||||
|
if (row is null)
|
||||||
{
|
{
|
||||||
SourceKey = key,
|
db.Blocks.Add(new BlockEntry
|
||||||
Source = BlockSource.Operator,
|
{
|
||||||
CreatedAt = now,
|
SourceKey = key,
|
||||||
Reason = reason,
|
Source = BlockSource.Operator,
|
||||||
RedirectTo = redirectTo
|
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;
|
_log.LogWarning(ex, "BlockStore: concurrent add on {Key}; retrying against the winner's row.", key);
|
||||||
row.RedirectTo = redirectTo ?? row.RedirectTo;
|
}
|
||||||
|
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");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -166,7 +199,21 @@ public sealed class BlockStore
|
|||||||
/// filter is not cosmetic: "clear the automatic bans" must never be able to
|
/// 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.
|
/// erase what an operator typed by hand, which is exactly what R1 forbids.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task<int> DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default)
|
public enum DeleteResult { Ok, StorageFailure }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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,
|
||||||
|
/// <c>DELETE ?source=operator</c> answered <c>200 {"deleted":0}</c> — 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(DeleteResult Result, int Deleted)> DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -177,12 +224,12 @@ public sealed class BlockStore
|
|||||||
if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey);
|
if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey);
|
||||||
var n = await q.ExecuteDeleteAsync(ct);
|
var n = await q.ExecuteDeleteAsync(ct);
|
||||||
await _state.InvalidateAsync(ct);
|
await _state.InvalidateAsync(ct);
|
||||||
return n;
|
return (DeleteResult.Ok, n);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.LogWarning(ex, "BlockStore: delete failed.");
|
_log.LogWarning(ex, "BlockStore: delete failed.");
|
||||||
return 0;
|
return (DeleteResult.StorageFailure, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The same damage the probe stand did from outside the container: the
|
||||||
|
/// table the block commands touch stops existing while the edge is serving.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task DropBlockTableAsync(EdgeFixture f)
|
||||||
|
{
|
||||||
|
using var scope = f.Factory.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||||
|
await db.Database.ExecuteSqlRawAsync("DROP TABLE block_entries");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<int> BlockRowsAsync(EdgeFixture f)
|
||||||
|
{
|
||||||
|
using var scope = f.Factory.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||||
|
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<OpenWafDbContext>();
|
||||||
|
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}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -344,6 +344,34 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
|||||||
afterRemove === '—' && !(await hasRemove()),
|
afterRemove === '—' && !(await hasRemove()),
|
||||||
`rule cell after remove: ${afterRemove}, remove button gone: ${!(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
|
// 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.
|
// 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
|
// Both halves of this used to be broken and measured: the page overflowed a
|
||||||
|
|||||||
Reference in New Issue
Block a user