Files
openwaf/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs
T
Pavlo Ratushnyi 5cf93ef0fd a source that asks too often is stopped, even when the origin keeps answering
Every defence this edge had reads something that already happened: the status the
application answered, the country the address sits in, a list a human wrote. A
source asking for a cheap path two hundred times a minute produces no refusal, so
no streak matures, no path rule names it, and the origin serves all two hundred.
The only signal is the count, and a count has to be kept while the requests are
arriving — which is why this pillar is the one piece of live state on the request
path, and why it runs after the ordered decision instead of inside it.

`rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds`
(policy_settings, so no schema change). Off is the default: a limit nobody wrote
is a defence nobody asked for, and a false positive here locks out a whole office
behind one address. `observe` counts and raises one `rate_breach` alert per
source per window. `enforce` answers the request that crosses with 429 +
Retry-After — the surplus never reaches the origin — and writes an engine ban, so
the stop outlives the window, is shared with the other edges and survives a
restart; from then on the answer is the ban's own 403. One breach, one alert, one
ban write per source per window: a flood is exactly the traffic that turns a
per-request durable write into the thing that takes the database down.

Exempt by construction rather than by a second copy of the precedence rules: the
counter runs only on a plain Pass, so an always-pass prefix, an allowlisted
address, a matched rule, a block or a geo refusal never reaches it. The budget
counts exactly the requests that would have cost the origin.

Costs, stated rather than hidden: the counter is per process, so N edges allow N
times the budget (the same trade `SharedStreaks` made for the streak, at a round
trip per request instead of per observed response); the window is fixed, not
sliding, so the worst sustained rate is twice the limit across one boundary — a
sliding counter needs one entry per request, which is a map that grows at attack
rate.

Two things the run caught rather than the design assumed:

 * The guard wrote the 429 and then called next() anyway, so YARP answered
   "the request cannot be forwarded, the response has already started". The
   pillar now says whether the request may go through.
 * `StreakTracker.Configure` was called by nobody outside its own tests, so
   `maxTrackedSources` bounded nothing in a running edge — the map grew to the
   built-in 10000 whatever the operator had asked for. Both maps are configured
   at warm-up and on a policy write now.

And the smoke gate was not testing what its first line says. The edge was started
from the repository root, where there is no appsettings.json, so it loaded no
ReverseProxy section at all, logged "Request reached the end of the middleware
pipeline without being handled by application code" for every request, and
answered 404 for a path the upstream was serving with 200. Every assertion in the
file expects a 404 or a refusal, so the gate kept passing on an edge that never
proxied anything. Naming the content root fixes it; the streak scene also waits
for the ban row to exist before asking the wire whether it is enforced, because
the ban is written out of band after the response that proved it.

Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219
in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209
passed 0 failed, image 261 MB.

OPEN-56
2026-10-04 21:00:33 +02:00

119 lines
6.0 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,
string rate = "Off",
int rateLimitPerWindow = 100,
double rateWindowSeconds = 60)
{
_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());
// 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());
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);
}
}