using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// 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. /// internal sealed class EdgeFixture : IAsyncDisposable { private readonly string _dbPath; /// 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. private readonly bool _sharedDb; public FakeUpstream Upstream { get; } = FakeUpstream.Start(); public WebApplicationFactory Factory { get; } public const string AdminToken = "test-admin-token"; /// The second token (OPEN-62): reads the operator surfaces, and /// is refused at every write. Passed only by the tests that are about it. 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().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() where T : notnull => Factory.Services.GetRequiredService(); public async Task FlushObservationsAsync() => await Service().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); } }