Files
Pavlo Ratushnyi a77ab53ea8 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.
2026-10-02 04:22:07 +02:00

218 lines
9.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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}"));
}
}