The push queue was a channel in one process: three attempts inside one request of work, then the row was simply no longer owed to anybody. An endpoint down for ten minutes swallowed every alert raised in that window, and a restart swallowed everything still waiting. The alert table stayed correct the whole time, which is exactly what made the hole invisible from the surface. What is owed is now a row in alert_pushes: denormalised payload (retention prunes edge_alerts, and a delivery still owed must not go with the row it was copied from), attempts, next-attempt time, last error, and a claim so two edges over one database send each row once. Attempts are configuration (OpenWaf:Alerts:MaxPushAttempts, PushRetrySeconds), validated at startup like the other bounds; when they run out the row records that and the surface says how many were given up, because a counter that cannot tell 'still retrying' from 'stopped retrying' is the blindness this item removes. Surfaces: /admin-api/state answers alertPushPending/Delivered/GivenUp/OldestPendingAt/LastError from the table, /metrics publishes the same as gauges from a cache no older than 5s (the metrics endpoint's rule is that it never leans on the database per scrape). Retention prunes only rows that are finished. What the run caught, in order: (1) SchemaUpgradeTests hardcoded the migration count as a literal, so the new migration turned a working upgrade into a red test - the count is now read from the migrations assembly. (2) Two of the new queue tests asserted 'pending == 0' after waiting only for 'delivered >= 1'; one scene raises more than one alert, so the read landed between two rows and failed on a correct product - the wait now requires the queue to have emptied. (3) The whole integration suite answered 9 failures of 251, every one 'Timed out waiting for the entry point to build the IHost after 00:05:00', while the identical build minutes later answered 251/251 in 34s: a test host that cannot bind a loopback socket fails as a timeout, and the README now says so next to the scheduling note that used to be the only explanation on file. Gates on this tree: build 0 warnings / 0 errors, unit 277/277, integration 251/251 in 34s, smoke 68 passed / 0 failed (3 new), image 261 MB, compose-smoke 232 passed / 0 failed with 0 containers left behind (2 new, including the push-queue table being added by the edge to a volume that predates it), console 90 assertions / 0 failed. Refs OPEN-60.
134 lines
6.9 KiB
C#
134 lines
6.9 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";
|
|
|
|
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? 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 ?? "");
|
|
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);
|
|
}
|
|
}
|