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.
316 lines
14 KiB
C#
316 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore.Migrations;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The upgrade path (OPEN-55). The default schema step is <c>EnsureCreated</c>,
|
|
/// which creates a missing database and changes nothing about an existing one —
|
|
/// so an operator who upgrades keeps a database with every table except the new
|
|
/// ones, and the pillar those tables back answers as if there were nothing to
|
|
/// see. The compose data volume outliving <c>compose down</c> is the same state,
|
|
/// which is how it was first noticed.
|
|
///
|
|
/// These tests build the state by hand: a real edge runs against a real SQLite
|
|
/// file, the tables the previous schema did not have are dropped from it, and a
|
|
/// second edge starts against what is left. The assertion is not that the code
|
|
/// noticed — it is that the pillar works and the operator's own rows are still
|
|
/// enforced afterwards.
|
|
/// </summary>
|
|
public sealed class SchemaUpgradeTests
|
|
{
|
|
private const string Blocked = "203.0.113.181";
|
|
private const string Visitor = "203.0.113.182";
|
|
|
|
private static string NewDbPath() => Path.Combine(Path.GetTempPath(), $"openwaf-upgrade-{Guid.NewGuid():N}.db");
|
|
|
|
private static async Task<JsonElement> StateAsync(EdgeFixture f)
|
|
{
|
|
using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
|
|
}
|
|
|
|
/// <summary>
|
|
/// How many migrations the shipped assembly carries. The baseline test wants
|
|
/// this number to come from the same place the upgrader reads it, so adding a
|
|
/// migration never turns a working upgrade into a red test.
|
|
/// </summary>
|
|
private static int MigrationCount() =>
|
|
typeof(OpenWafDbContext).Assembly
|
|
.GetTypes()
|
|
.Count(t => !t.IsAbstract
|
|
&& typeof(Migration).IsAssignableFrom(t)
|
|
&& t.GetCustomAttribute<MigrationAttribute>() is not null);
|
|
|
|
/// <summary>
|
|
/// The host starts on first use, and the schema step runs when it starts — so
|
|
/// a test that wants a database on disk has to make a request before it can
|
|
/// assume one exists.
|
|
/// </summary>
|
|
private static async Task StartedAsync(EdgeFixture f)
|
|
{
|
|
using var response = await f.Client.GetAsync("/healthz");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
}
|
|
|
|
private static async Task DropTablesAsync(string dbPath, params string[] tables)
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
await using var connection = new SqliteConnection($"Data Source={dbPath}");
|
|
await connection.OpenAsync();
|
|
foreach (var table in tables)
|
|
{
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = $"DROP TABLE {table}";
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
|
|
SqliteConnection.ClearAllPools();
|
|
}
|
|
|
|
private static async Task<IReadOnlyList<string>> IndexesAsync(string dbPath)
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
await using var connection = new SqliteConnection($"Data Source={dbPath}");
|
|
await connection.OpenAsync();
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name";
|
|
await using var reader = await command.ExecuteReaderAsync();
|
|
var names = new List<string>();
|
|
while (await reader.ReadAsync()) names.Add(reader.GetString(0));
|
|
SqliteConnection.ClearAllPools();
|
|
return names;
|
|
}
|
|
|
|
private static async Task<IReadOnlyList<string>> TablesAsync(string dbPath)
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
await using var connection = new SqliteConnection($"Data Source={dbPath}");
|
|
await connection.OpenAsync();
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name";
|
|
await using var reader = await command.ExecuteReaderAsync();
|
|
var names = new List<string>();
|
|
while (await reader.ReadAsync()) names.Add(reader.GetString(0));
|
|
SqliteConnection.ClearAllPools();
|
|
return names;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_database_that_predates_a_table_gains_it_on_the_next_start()
|
|
{
|
|
var db = NewDbPath();
|
|
try
|
|
{
|
|
await using (var first = new EdgeFixture(dbPath: db))
|
|
{
|
|
var state = await StateAsync(first);
|
|
// A fresh database is not an upgrade: nothing was added, and the
|
|
// state says so rather than leaving the field blank.
|
|
Assert.Equal(0, state.GetProperty("schemaTablesAdded").GetInt32());
|
|
Assert.Empty(state.GetProperty("schemaMissingTables").EnumerateArray());
|
|
}
|
|
|
|
// The state an upgrade leaves behind: a database with the previous
|
|
// schema's tables and none of this build's new ones.
|
|
await DropTablesAsync(db, "request_rules", "source_streaks");
|
|
|
|
await using var second = new EdgeFixture(dbPath: db);
|
|
|
|
{
|
|
var state = await StateAsync(second);
|
|
Assert.Equal(2, state.GetProperty("schemaTablesAdded").GetInt32());
|
|
Assert.Empty(state.GetProperty("schemaMissingTables").EnumerateArray());
|
|
Assert.True(state.GetProperty("requestRulesAvailable").GetBoolean());
|
|
}
|
|
|
|
Assert.Contains("request_rules", await TablesAsync(db));
|
|
Assert.Contains("source_streaks", await TablesAsync(db));
|
|
|
|
// The point of the table is the pillar behind it: a rule written
|
|
// after the upgrade refuses the path, which is what "the table
|
|
// exists" has to mean for it to be worth adding.
|
|
using (var created = await second.Client.PostAsJsonAsync(
|
|
$"/admin-api/rules?token={EdgeFixture.AdminToken}",
|
|
new { pattern = "/upgrade-check*", action = "block", note = "written after the upgrade" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/upgrade-check");
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", Visitor);
|
|
using var refused = await second.Client.SendAsync(request);
|
|
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
if (File.Exists(db)) File.Delete(db);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_table_added_in_place_arrives_with_the_indexes_the_model_describes()
|
|
{
|
|
var db = NewDbPath();
|
|
try
|
|
{
|
|
await using (var first = new EdgeFixture(dbPath: db))
|
|
await StartedAsync(first);
|
|
|
|
await DropTablesAsync(db, "request_rules");
|
|
|
|
await using var second = new EdgeFixture(dbPath: db);
|
|
var state = await StateAsync(second);
|
|
Assert.Equal(1, state.GetProperty("schemaTablesAdded").GetInt32());
|
|
|
|
// The DDL is EF's own, generated from the model for this provider.
|
|
// Keeping only the CREATE TABLE line would leave a table that exists
|
|
// and a listing that scans it in full, so the indexes have to come
|
|
// with it.
|
|
Assert.Contains("request_rules", await TablesAsync(db));
|
|
var indexes = await IndexesAsync(db);
|
|
Assert.Contains("IX_request_rules_Pattern", indexes);
|
|
Assert.Contains("IX_request_rules_ExpiresAt", indexes);
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
if (File.Exists(db)) File.Delete(db);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_upgrade_leaves_the_operators_own_block_enforced()
|
|
{
|
|
var db = NewDbPath();
|
|
HttpStatusCode enforcedBefore = default;
|
|
try
|
|
{
|
|
await using (var first = new EdgeFixture(dbPath: db))
|
|
{
|
|
using var created = await first.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}",
|
|
new { ip = Blocked, reason = "written before the upgrade" });
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using var before = new HttpRequestMessage(HttpMethod.Get, "/anything");
|
|
before.Headers.TryAddWithoutValidation("X-Forwarded-For", Blocked);
|
|
using var beforeResponse = await first.Client.SendAsync(before);
|
|
// The block changed the answer. Which refusal an operator block
|
|
// answers with is the guard's business, not this test's; that it
|
|
// is the same refusal after the upgrade is the whole claim.
|
|
Assert.NotEqual(HttpStatusCode.NotFound, beforeResponse.StatusCode);
|
|
enforcedBefore = beforeResponse.StatusCode;
|
|
}
|
|
|
|
await DropTablesAsync(db, "request_rules", "source_streaks");
|
|
|
|
await using var second = new EdgeFixture(dbPath: db);
|
|
|
|
using var after = new HttpRequestMessage(HttpMethod.Get, "/anything");
|
|
after.Headers.TryAddWithoutValidation("X-Forwarded-For", Blocked);
|
|
using var afterResponse = await second.Client.SendAsync(after);
|
|
Assert.Equal(enforcedBefore, afterResponse.StatusCode);
|
|
|
|
// The row is still the operator's, with the note they typed.
|
|
using var listing = await second.Client.GetAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}");
|
|
Assert.Contains("written before the upgrade", await listing.Content.ReadAsStringAsync());
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
if (File.Exists(db)) File.Delete(db);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_database_with_no_migration_history_is_baselined_before_the_migration_runs()
|
|
{
|
|
var db = NewDbPath();
|
|
try
|
|
{
|
|
// EnsureCreated — the sqlite default — leaves no history table, so
|
|
// asking this database to migrate is the postgres upgrade against a
|
|
// database that was never tracked.
|
|
await using (var first = new EdgeFixture(dbPath: db))
|
|
{
|
|
await StartedAsync(first);
|
|
Assert.DoesNotContain("__EFMigrationsHistory", await TablesAsync(db));
|
|
}
|
|
|
|
await using var second = new EdgeFixture(dbPath: db, schema: "migrate");
|
|
|
|
{
|
|
var state = await StateAsync(second);
|
|
Assert.Equal("migrate", state.GetProperty("schemaStrategy").GetString());
|
|
// Every migration is demonstrably applied to a database that
|
|
// already has every table they describe, so nothing is left to
|
|
// run — and that is stated as a number, not assumed. The number
|
|
// is counted from the migrations assembly, not typed here: a
|
|
// literal would make the next migration fail this test with a
|
|
// passing product.
|
|
Assert.Equal(
|
|
MigrationCount(),
|
|
state.GetProperty("schemaMigrationsBaselined").GetInt32());
|
|
Assert.Equal(0, state.GetProperty("schemaMigrationsApplied").GetInt32());
|
|
Assert.Empty(state.GetProperty("schemaMissingTables").EnumerateArray());
|
|
}
|
|
|
|
var tables = await TablesAsync(db);
|
|
Assert.Contains("__EFMigrationsHistory", tables);
|
|
|
|
// The edge still serves, which is the whole reason the baseline
|
|
// exists: the alternative was a migration that begins by creating a
|
|
// table that is already there.
|
|
using var response = await second.Client.GetAsync("/anything");
|
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
if (File.Exists(db)) File.Delete(db);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_operator_managed_schema_reports_what_is_missing_instead_of_fixing_it()
|
|
{
|
|
var db = NewDbPath();
|
|
try
|
|
{
|
|
await using (var first = new EdgeFixture(dbPath: db))
|
|
await StartedAsync(first);
|
|
|
|
await DropTablesAsync(db, "request_rules", "source_streaks");
|
|
|
|
await using var second = new EdgeFixture(dbPath: db, schema: "none");
|
|
|
|
{
|
|
var state = await StateAsync(second);
|
|
Assert.Equal("none", state.GetProperty("schemaStrategy").GetString());
|
|
Assert.Equal(0, state.GetProperty("schemaTablesAdded").GetInt32());
|
|
var missing = state.GetProperty("schemaMissingTables").EnumerateArray()
|
|
.Select(value => value.GetString()).ToList();
|
|
Assert.Contains("request_rules", missing);
|
|
Assert.Contains("source_streaks", missing);
|
|
// The pillar that needs the table says so, rather than answering
|
|
// with an empty list that reads like "no rules written".
|
|
Assert.False(state.GetProperty("requestRulesAvailable").GetBoolean());
|
|
}
|
|
|
|
Assert.DoesNotContain("request_rules", await TablesAsync(db));
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
if (File.Exists(db)) File.Delete(db);
|
|
}
|
|
}
|
|
}
|