The default schema step is EnsureCreated: it creates a missing database and changes nothing about an existing one. The migrate path could not rescue that database either, because a database EnsureCreated once made has no __EFMigrationsHistory, so the migration set would begin by creating tables that are already there. Same bug with two faces. An operator who upgraded kept a schema with every table except the new ones, and the pillar behind them answered as if there were nothing to see — the compose data volume outliving 'compose down' is exactly that state, which is where it was noticed. At startup the edge now lists the tables the model describes and the database lacks and creates exactly those, from the model through the provider in use, indexes included. A table that exists is never touched, so an upgrade cannot lose an operator's block list — proven on the wire, not asserted: a block written before the upgrade still refuses the same request after it, with the note the operator typed still in the listing. On the migrate path a database with no history table is baselined first: a migration is claimed as applied only when every table its target model describes is already present, and the claim stops at the first migration it cannot confirm, so a later one is never applied over an unclaimed earlier one. SchemaBaseline is that decision as a pure function; SchemaDdl is the statement filter over EF's own generated script, and an unrecognised statement is left out rather than run, because the safe failure is a table that stays missing and is reported. What happened is on /admin-api/state: schemaStrategy, schemaTablesAdded, schemaMigrationsBaselined, schemaMigrationsApplied, schemaMissingTables. The last is the invariant — non-empty names a pillar this build can run with no storage behind it, and OPENWAF_SCHEMA=none now changes nothing and reports all of it the same way. The limit is stated rather than hidden: the baseline recognises a table by its name, so a migration that alters an existing table still needs a human decision and the edge refuses to guess one. OPENWAF_SCHEMA is read through configuration instead of the environment directly. An environment variable still sets it; the change is that a test can now ask for a strategy without mutating process-wide state that parallel xUnit collections share. Gates on this tree: build 0 warnings / 0 errors, unit 240/240 (+13: the baseline claim, the statement filter), integration 230/230 in 22 s (+5: an edge started against a database with two tables dropped, the indexes arriving with the table, the operator block surviving, the baseline on the migrate path, and the operator-managed schema reporting rather than fixing), smoke passed 52 failed 0 unchanged, compose 216 passed 0 failed (+7: the same upgrade against the shipped image, where the volume really does outlive the stack), console 90 assertions 0 failed unchanged. Two things the new compose scene caught about the gate itself. The rule-write assertion used code(), which discards the body, so the first run answered 400 and the gate could not say why — the assertion now prints the body it got. And the delete looked its rule up with jget while writing jcount's loop variable, a NameError inside the helper that surfaced as a 405 on the assertion: the trap the script's own comment names, walked into anyway.
125 lines
6.4 KiB
C#
125 lines
6.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";
|
|
|
|
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,
|
|
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());
|
|
// 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);
|
|
}
|
|
}
|