Files
openwaf/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs
T
Pavlo Ratushnyi 6e6461a760 A 404 explained one missing row and said nothing about another, and the page answered the silent one with "the admin API is off"
Measured on the shipped image (openwaf:ci 08bebf43, the tree with the
storage-failure fix):

  DELETE /admin-api/countries/ZZ   -> 404 {"error":"no country rule for \"ZZ\""}
  DELETE /admin-api/allow/999999   -> 404, Content-Length: 0

Same status, two qualities of answer. The silent half is what the console then
had to invent an explanation for: apiRaw read EVERY 404 as
"admin api disabled — set OpenWaf__Admin__Token" and threw, so removing a row
that another tab had already removed told the operator to go configure a token
that is already configured. And because the throw landed in a catch that says
nothing, the status line ended up reading "refreshed" in the success colour —
measured in the console gate before the fix:

  FAIL a missing row is reported as a missing row… — ok: refreshed 4:50:18 AM

After the fix, on the image built from this tree (4823e9ae):

  DELETE /admin-api/allow/999999   -> 404 {"error":"no allow entry with id 999999"}

The page now shows that sentence instead of guessing:

  ok  a missing row is reported as a missing row, not as the admin API being switched off
      — warn: no allow entry with id 999999

Whether the admin surface is switched off at all is no longer inferred from a
status code: the core read (/admin-api/state) is checked for a non-200 and the
edge's own body is shown — "admin api disabled: set OpenWaf__Admin__Token",
which the API already says and which a new test pins.

While in this handler, the most destructive button on the page was found doing
worse than lying: "clear the automatic bans" fired the DELETE and read nothing
back, so cleared 7, cleared 0 and a refused write looked identical after the
reload. It now reports the count the edge gave ("engine bans cleared: 0"), and
the note for the action just taken survives the refresh that action itself
triggered — load() used to overwrite it with "refreshed" inside a second, which
is shorter than the time it takes to read.

Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 109/109 (3 new in NotFoundExplanationTests), smoke 19/0,
compose 43/0, image 261 MB, console 47/47 (2 new assertions).
Dents: allow 404 silent again -> 2 tests fail; apiRaw reading every 404 as
"disabled" -> 2 console assertions fail; clearEngine reading nothing back -> 1;
the action note not held across its own refresh -> 1.
2026-10-02 05:21:44 +02:00

76 lines
3.3 KiB
C#

using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// One edge instance per test, with its own SQLite file and its own upstream.
/// Isolation is not tidiness here: the streak map and the block table are the
/// things under test, and a shared one would make the assertions about "this
/// source is banned, that one is not" meaningless.
/// </summary>
internal sealed class EdgeFixture : IAsyncDisposable
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
public FakeUpstream Upstream { get; } = FakeUpstream.Start();
public WebApplicationFactory<Program> Factory { get; }
public const string AdminToken = "test-admin-token";
public EdgeFixture(
string mode = "Enforce",
int threshold = 3,
string streakWindow = "00:05:00",
string banDuration = "01:00:00",
string geo = "Off",
int? refreshTtlSeconds = null,
string? adminToken = AdminToken)
{
Factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.UseSetting("ConnectionStrings:OpenWaf", $"Data Source={_dbPath}");
builder.UseSetting("Database:Provider", "sqlite");
// An empty token is a real configuration, not a missing one: it is
// how the admin surface is switched off, and a test that asserts what
// the page sees has to be able to ask for it.
builder.UseSetting("OpenWaf:Admin:Token", adminToken ?? "");
builder.UseSetting("OpenWaf:Policy:Mode", mode);
builder.UseSetting("OpenWaf:Policy:StreakThreshold", threshold.ToString());
builder.UseSetting("OpenWaf:Policy:StreakWindow", streakWindow);
builder.UseSetting("OpenWaf:Policy:BanDuration", banDuration);
builder.UseSetting("OpenWaf:Policy:Geo", geo);
// The only way to give a TestServer request a source address is a
// header, so these tests exercise the trusted-proxy path too.
builder.UseSetting("OpenWaf:Policy:TrustProxyHeaders", "true");
if (refreshTtlSeconds is { } ttl)
builder.UseSetting("OpenWaf:State:RefreshTtlSeconds", ttl.ToString());
builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address);
});
}
public HttpClient Client => Factory.CreateClient();
public T Service<T>() where T : notnull => Factory.Services.GetRequiredService<T>();
public async Task FlushObservationsAsync() => await Service<ObservationWriter>().FlushAsync(CancellationToken.None);
public async Task SendAsync(HttpClient client, string path, string sourceIp)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp);
using var response = await client.SendAsync(request);
}
public async ValueTask DisposeAsync()
{
await Factory.DisposeAsync();
Upstream.RequestCount = 0;
await Upstream.DisposeAsync();
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
if (File.Exists(_dbPath)) File.Delete(_dbPath);
}
}