The alerting pillar ended at a table. The rows are right — the server-error
streak fires, the dry-run candidate is recorded — and then they wait for an
operator to open a page. That is the posture this project already removed for
blocking ("blocking is usually manual: a human notices abuse and adds an IP.
That never fires at 3am"), applied one level up: an alert nobody is told about
never fires at 3am either.
OpenWaf:Alerts:WebhookUrl (env fallback OPENWAF_ALERT_WEBHOOK_URL) POSTs each
raised alert as JSON — kind, sourceKey, count, lastStatusCode, lastPath,
createdAt, detail — off the request path, from a bounded queue of 1000, and only
after the row is durably written. Three attempts with a short backoff;
OpenWaf:Alerts:WebhookTimeoutSeconds (1-60, default 5) refuses startup outside
that range rather than falling back, as the other startup-parsed bounds do. The
default is empty, which is no push at all: the shipped stack behaves exactly as
it did before.
The endpoint is counted like every other write side pillar, because a webhook
that has been down for a week is otherwise indistinguishable from a quiet night:
alertWebhookFailures, alertWebhookLost, alertWebhookDelivered,
alertWebhookLastError, alertWebhookLastSuccessAt, plus alertWebhookConfigured and
alertWebhookHost — host, never the URL, since a webhook URL carries its secret
in the path and this is rendered on the operator page. The console's alert line
now ends in "pushed to <host>, N delivered" or "not pushed anywhere: each row
waits for someone to open this page", so "no alerts" and "alerts go nowhere" stay
two different sentences.
Two things the tests caught instead of the design assuming:
* the queue was BoundedChannelFullMode.DropWrite, where TryWrite returns true
and the overflow vanishes with no trace — the counter it was written to feed
stayed at zero. The mode is Wait now, chosen for what TryWrite reports when
the queue is full; nothing here awaits a write, so the response path still
cannot block.
* a refused push counted as an entry lost, which conflated a lost delivery with
a lost record. The alert row is in the table either way, so EntriesLost on
this pillar is reserved for the one case where the push is gone for good.
Measured on this tree: build 0 warnings / 0 errors, unit 151/151 (19 new),
integration 194/194 in 28 s (3 new: the push arrives with the alert in it, an
unconfigured edge sends nothing and keeps every row, an endpoint answering 500 is
counted and does not undo the alert), smoke 29/0, console 79 assertions 0 failed,
compose 209/0 against the built image at 261 MB.
238 lines
11 KiB
C#
238 lines
11 KiB
C#
using System.Net;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Domain.Security;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The one gap the multi-instance research measured rather than guessed: the
|
|
/// block list is shared through the database, the streak map was not. Four
|
|
/// refusals from one address, two per edge, at a threshold of 3, produced no ban
|
|
/// anywhere (research/2026-10-01-multi-instance/, D1, reproduced twice).
|
|
///
|
|
/// These tests run two real edge instances against one SQLite file, so the
|
|
/// answer is not a simulation of sharing — it is sharing. The default stays the
|
|
/// in-process map, and the second test is the proof that the default still
|
|
/// behaves the way the research measured it.
|
|
/// </summary>
|
|
public sealed class SharedStreakTests
|
|
{
|
|
private const string Scanner = "203.0.113.71";
|
|
|
|
private static string NewSharedDb() =>
|
|
Path.Combine(Path.GetTempPath(), $"openwaf-shared-{Guid.NewGuid():N}.db");
|
|
|
|
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
|
|
return await f.Client.SendAsync(request);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Two_edges_on_one_database_mature_one_streak_together()
|
|
{
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var a = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true);
|
|
await using var b = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true);
|
|
|
|
// Two refusals at one edge: 1 of 3, then 2 of 3. Nothing bans yet.
|
|
using (var first = await GetAsync(a, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, first.StatusCode);
|
|
using (var second = await GetAsync(a, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, second.StatusCode);
|
|
|
|
// The third lands at the other edge. Per process that is 1 of 3 and
|
|
// bans nobody; shared it is 3 of 3, so the ban exists after this
|
|
// request — which is the request D1 measured as answering 404 on
|
|
// both edges, because neither map had crossed on its own.
|
|
using (var third = await GetAsync(b, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, third.StatusCode);
|
|
|
|
using (var scope = b.Factory.Services.CreateScope())
|
|
{
|
|
var dbf = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var ban = await dbf.Blocks.SingleOrDefaultAsync(x => x.SourceKey == Scanner && x.Source == BlockSource.Engine);
|
|
Assert.NotNull(ban);
|
|
Assert.Equal(3, ban!.ConsecutiveRefusals);
|
|
}
|
|
|
|
// The banning edge enforces it, and so does the edge that never saw
|
|
// a third refusal — the ban is the fleet's, once the snapshot moves.
|
|
using (var enforcedHere = await GetAsync(b, "/anything", Scanner))
|
|
Assert.Equal(HttpStatusCode.Forbidden, enforcedHere.StatusCode);
|
|
await a.Service<EdgeStateStore>().InvalidateAsync(CancellationToken.None);
|
|
using (var enforcedThere = await GetAsync(a, "/anything", Scanner))
|
|
Assert.Equal(HttpStatusCode.Forbidden, enforcedThere.StatusCode);
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_same_split_traffic_bans_nobody_without_the_shared_store()
|
|
{
|
|
// The default, kept honest: this is D1 reproduced, not a strawman. Two
|
|
// edges, threshold 3, two refusals each — nobody crosses the threshold
|
|
// in either map, so the visitor is served and no ban exists anywhere.
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var a = new EdgeFixture(threshold: 3, dbPath: db);
|
|
await using var b = new EdgeFixture(threshold: 3, dbPath: db);
|
|
|
|
for (var i = 0; i < 2; i++)
|
|
using (var viaA = await GetAsync(a, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, viaA.StatusCode);
|
|
for (var i = 0; i < 2; i++)
|
|
using (var viaB = await GetAsync(b, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, viaB.StatusCode);
|
|
|
|
// Four refusals, two per map, threshold 3: nobody crossed, so no ban
|
|
// was written anywhere. (A fifth request would be the third of one
|
|
// edge's own run — that is the per-process behaviour, and it is not
|
|
// what this test is about.)
|
|
using (var scope = a.Factory.Services.CreateScope())
|
|
{
|
|
var dbf = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.Empty(await dbf.Blocks.Where(x => x.SourceKey == Scanner).ToListAsync());
|
|
}
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_streak_listing_names_the_store_it_answered_from_and_shows_the_other_edge_s_work()
|
|
{
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var a = new EdgeFixture(threshold: 5, dbPath: db, sharedStreaks: true);
|
|
await using var b = new EdgeFixture(threshold: 5, dbPath: db, sharedStreaks: true);
|
|
await using var local = new EdgeFixture(threshold: 5);
|
|
|
|
using (await GetAsync(a, "/probe", Scanner)) { }
|
|
using (await GetAsync(a, "/probe", Scanner)) { }
|
|
|
|
// Asked on the edge that saw nothing, the shared listing still shows
|
|
// the streak — and says where it came from.
|
|
var shared = await (await b.Client.GetAsync(
|
|
$"/admin-api/streaks?source={Scanner}&token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync();
|
|
Assert.Contains("\"scope\":\"shared-database\"", shared);
|
|
Assert.Contains("\"consecutiveRefusals\":2", shared);
|
|
Assert.Contains("\"standingStreaks\":1", shared);
|
|
|
|
// The default store answers for one process and says so.
|
|
var localBody = await (await local.Client.GetAsync(
|
|
$"/admin-api/streaks?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync();
|
|
Assert.Contains("\"scope\":\"this-process\"", localBody);
|
|
Assert.Contains("\"standingStreaks\":0", localBody);
|
|
|
|
var state = await (await b.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync();
|
|
Assert.Contains("\"streakScope\":\"shared-database\"", state);
|
|
|
|
// And the bound beside the count is the one that actually applies.
|
|
// A cap is a property of one process's memory; the shared store is
|
|
// bounded by time, so naming a cap there would name a limit nothing
|
|
// enforces.
|
|
Assert.Contains("\"maxTrackedSources\":null", shared);
|
|
Assert.Contains("\"trackedRetentionDays\":7", shared);
|
|
Assert.Contains("\"trackedIdleMinutes\":120", shared);
|
|
Assert.Contains("\"maxTrackedSources\":10000", localBody);
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_clean_answer_at_the_other_edge_ends_the_shared_streak()
|
|
{
|
|
// "Consecutive" has to mean the same thing across edges, or sharing the
|
|
// counters makes the ban worse rather than correct: a visitor who fixes
|
|
// what the edge objected to, on any instance, starts over.
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var a = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true);
|
|
await using var b = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true);
|
|
a.Upstream.StatusFor = path => path == "/ok" ? StatusCodes.Status200OK : StatusCodes.Status404NotFound;
|
|
b.Upstream.StatusFor = path => path == "/ok" ? StatusCodes.Status200OK : StatusCodes.Status404NotFound;
|
|
|
|
using (await GetAsync(a, "/probe", Scanner)) { }
|
|
using (await GetAsync(a, "/probe", Scanner)) { }
|
|
|
|
using (var clean = await GetAsync(b, "/ok", Scanner))
|
|
Assert.Equal(HttpStatusCode.OK, clean.StatusCode);
|
|
|
|
// Two more refusals at the first edge. Without the reset across
|
|
// edges this is the third and fourth of one run and bans at the
|
|
// first of them.
|
|
using (var afterReset1 = await GetAsync(a, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, afterReset1.StatusCode);
|
|
using (var afterReset2 = await GetAsync(a, "/probe", Scanner))
|
|
Assert.Equal(HttpStatusCode.NotFound, afterReset2.StatusCode);
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Two_edges_started_at_the_same_moment_against_one_database_both_come_up()
|
|
{
|
|
// The shared store makes "two edges, one database" the configuration
|
|
// rather than an accident, and both edges create the schema on startup.
|
|
// The loser of that race used to die in StartAsync with 'table
|
|
// "allow_entries" already exists' and never listened — measured with two
|
|
// real processes on one file, which is also how the fix was confirmed.
|
|
// Here both hosts are forced to build at the same instant.
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var a = new EdgeFixture(dbPath: db, sharedStreaks: true);
|
|
await using var b = new EdgeFixture(dbPath: db, sharedStreaks: true);
|
|
|
|
var responses = await Task.WhenAll(
|
|
a.Client.GetAsync("/healthz"),
|
|
b.Client.GetAsync("/healthz"),
|
|
a.Client.GetAsync("/healthz"),
|
|
b.Client.GetAsync("/healthz"));
|
|
Assert.All(responses, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode));
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_retention_window_ages_out_shared_streak_rows_too()
|
|
{
|
|
// The shared map is the one table this edge writes on the request path,
|
|
// so the privacy window has to sweep it as well: a source key must not
|
|
// outlive ObservationRetentionDays just because the counters moved out
|
|
// of memory.
|
|
var db = NewSharedDb();
|
|
try
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true, observationRetentionDays: 1);
|
|
using (await GetAsync(f, "/probe", Scanner)) { }
|
|
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var dbf = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var row = await dbf.Streaks.SingleAsync(t => t.SourceKey == Scanner);
|
|
row.LastSeenAt = DateTimeOffset.UtcNow.AddDays(-3);
|
|
await dbf.SaveChangesAsync();
|
|
}
|
|
|
|
await f.Service<RetentionWorker>().PruneAsync(CancellationToken.None);
|
|
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var dbf = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.Equal(0, await dbf.Streaks.CountAsync());
|
|
}
|
|
}
|
|
finally { if (File.Exists(db)) File.Delete(db); }
|
|
}
|
|
}
|