Files
openwaf/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs
T
Pavlo Ratushnyi 718dcaaba3 a second token can read the operator's surfaces and change none of them
One admin secret meant one thing: whatever could read /admin-api/state could also delete every block and rewrite the policy. A Prometheus scrape therefore held a key that can lift a ban, a second operator checking why a visitor was refused held a key that can change what the edge enforces, and OPEN-61's export put a whole edge's config behind the same single GET. The operator's question was never "does this thing know the secret" but "what is it allowed to do", and the shipped answer could only be all or nothing.

OpenWaf:Admin:ReadOnlyToken (env OPENWAF_READ_ONLY_TOKEN) is the second level. Unset is the default and the whole of the previous behaviour. The rulings:

 * A known token without the right is answered 403, not 401, and the body names the key that would grant the write. Collapsing the two sentences sends someone debugging a failing script to check the secret when what is wrong is the endpoint it was sent to.
 * The line is drawn by the request method, not by a flag per endpoint: GET/HEAD/OPTIONS read, everything else writes. A write endpoint added tomorrow is behind the rule the moment it is written; a per-endpoint flag would fail the other way, and one forgotten flag would open the write.
 * GET /admin-api/export is the one read held to the admin token. It is a read and it is still the whole config, so it is the surface where "can read" and "can take" are the same act - and the dashboard token is exactly the one that must not be able to lift a fleet's config.
 * A read-only token sees byte-identical answers to the admin token. Read-only is about what a token may do, not about a weaker view: two people comparing answers must not get different answers because of who asked.
 * A read-only token equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret. /admin-api/state answers readOnlyTokenConfigured, so the operator can check the key took effect instead of guessing from a 401.

What the run caught, in order: (1) A real defect, and the interesting one. On the shipped image the startup refusal printed its reason and then the process sat at 100% CPU inside the runtime's crash path - the container stayed "Up (unhealthy)" forever, no exit code, nothing for a supervisor to react to. Refusing to start is only useful if the process leaves, so the refusal now writes the reason to stderr and returns 1; measured again on the image, it exits in 2 s with code 1 and the same sentence. (2) The gate's own assertion for that case had the same blind spot as the bug: waiting on a foreground docker compose run cannot tell "refused" from "hung", so the container is now started detached and polled for an exit within 30 s, and the assertion is that it left. (3) Two smoke asserts were wrong rather than the product: the blocks listing field is sourceKey, not ip, so the first version read an empty answer, and a two-code assertion compared a newline-separated pair against a space-separated literal. (4) An integration assert compared JsonElement.ToString() against "true" - a bool element prints True, so it now reads GetBoolean().

Gates on this tree: build 0 warnings / 0 errors, unit 307/307, integration 286/286 in 26s, smoke 105 passed / 0 failed (23 new), image 262 MB, compose-smoke 261 passed / 0 failed with 0 containers left behind (18 new, against the shipped image), console 90 assertions / 0 failed.

Refs OPEN-62.
2026-10-05 04:57:59 +02:00

142 lines
7.4 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;
/// <summary>True when the caller passed a database to share with another
/// fixture, in which case this fixture must not be the one that deletes it.
/// Two edges on one database is the multi-instance case (OPEN-52), and the
/// file is the thing under test.</summary>
private readonly bool _sharedDb;
public FakeUpstream Upstream { get; } = FakeUpstream.Start();
public WebApplicationFactory<Program> Factory { get; }
public const string AdminToken = "test-admin-token";
/// <summary>The second token (OPEN-62): reads the operator surfaces, and
/// is refused at every write. Passed only by the tests that are about it.</summary>
public const string ReadOnlyToken = "test-read-only-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,
int? observationRetentionDays = null,
int? banRetentionDays = null,
string? adminToken = AdminToken,
string? readOnlyToken = null,
string? dbPath = null,
bool sharedStreaks = false,
string? alertWebhookPath = null,
int? alertWebhookTimeoutSeconds = null,
int? maxPushAttempts = null,
int? pushRetrySeconds = null,
string rate = "Off",
int rateLimitPerWindow = 100,
double rateWindowSeconds = 60,
string? schema = null)
{
_sharedDb = dbPath is not null;
_dbPath = dbPath ?? Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
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 ?? "");
// The read-only token (OPEN-62). Empty means the level does not exist,
// which is the shipped default and what every other fixture runs with.
builder.UseSetting("OpenWaf:Admin:ReadOnlyToken", readOnlyToken ?? "");
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());
// The retention window is configuration as of OPEN-19, so a test can
// ask for a short window instead of backdating rows past a constant.
if (observationRetentionDays is { } ord)
builder.UseSetting("OpenWaf:Policy:ObservationRetentionDays", ord.ToString());
if (banRetentionDays is { } brd)
builder.UseSetting("OpenWaf:Policy:BanRetentionDays", brd.ToString());
// Which streak store the process registers. Off is the default and
// the shape every other fixture runs; on is the multi-instance case
// where two of these fixtures share one database.
builder.UseSetting("OpenWaf:Policy:SharedStreaks", sharedStreaks ? "true" : "false");
// Where a raised alert is pushed, and how long one push may take.
// Unset is the shipped default: the alert table is the only record.
// The path on this fixture's own upstream, because the upstream is
// the one HTTP endpoint a fixture already owns and can make answer
// whatever the test needs — including "500 to every push".
if (alertWebhookPath is not null)
builder.UseSetting("OpenWaf:Alerts:WebhookUrl",
Upstream.Address.TrimEnd('/') + alertWebhookPath);
if (alertWebhookTimeoutSeconds is { } wts)
builder.UseSetting("OpenWaf:Alerts:WebhookTimeoutSeconds", wts.ToString());
// How hard the delivery queue tries, and how long it waits between
// tries (OPEN-60). A test that asks about giving up has to be able to
// ask for a small bound rather than wait out an hour.
if (maxPushAttempts is { } mpa)
builder.UseSetting("OpenWaf:Alerts:MaxPushAttempts", mpa.ToString());
if (pushRetrySeconds is { } prs)
builder.UseSetting("OpenWaf:Alerts:PushRetrySeconds", prs.ToString());
// The volume pillar (OPEN-56). Off by default here exactly as in the
// shipped default, so every other test in this suite proves the
// counter costs nothing when the pillar is not asked for.
builder.UseSetting("OpenWaf:Policy:Rate", rate);
builder.UseSetting("OpenWaf:Policy:RateLimitPerWindow", rateLimitPerWindow.ToString());
builder.UseSetting("OpenWaf:Policy:RateWindowSeconds", rateWindowSeconds.ToString());
// How the schema is brought up. Unset is the shipped default for the
// provider under test; a test that asks about an upgrade has to be
// able to name the other strategy without touching process-wide
// environment variables that parallel tests share.
if (schema is not null) builder.UseSetting("OPENWAF_SCHEMA", schema);
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 (!_sharedDb && File.Exists(_dbPath)) File.Delete(_dbPath);
}
}