From 871eac48a5d4ddb8079e544184439ea30b87f652 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 22:51:58 +0200 Subject: [PATCH] an upgrade adds the tables a database predates, and says what it added MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- README.md | 55 +++- dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 14 +- dotnet/OpenWaf.Edge/Program.cs | 2 + .../OpenWaf.Edge/Startup/EdgeStateWarmer.cs | 33 +- .../Startup/SchemaUpgradeReport.cs | 29 ++ .../Persistence/SchemaBaseline.cs | 56 ++++ .../Persistence/SchemaDdl.cs | 90 ++++++ .../Persistence/SchemaUpgrader.cs | 192 ++++++++++++ .../OpenWaf.Tests.Integration/EdgeFixture.cs | 10 +- .../SchemaUpgradeTests.cs | 295 ++++++++++++++++++ .../OpenWaf.Tests.Unit/SchemaBaselineTests.cs | 84 +++++ dotnet/OpenWaf.Tests.Unit/SchemaDdlTests.cs | 101 ++++++ scripts/compose-smoke.sh | 51 +++ 13 files changed, 989 insertions(+), 23 deletions(-) create mode 100644 dotnet/OpenWaf.Edge/Startup/SchemaUpgradeReport.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/SchemaBaseline.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/SchemaDdl.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs create mode 100644 dotnet/OpenWaf.Tests.Integration/SchemaUpgradeTests.cs create mode 100644 dotnet/OpenWaf.Tests.Unit/SchemaBaselineTests.cs create mode 100644 dotnet/OpenWaf.Tests.Unit/SchemaDdlTests.cs diff --git a/README.md b/README.md index 2238176..0dd05e9 100644 --- a/README.md +++ b/README.md @@ -327,6 +327,24 @@ default — there the schema is created from the model at startup. `OPENWAF_SCHE overrides the choice: `migrate`, `ensurecreated`, or `none` when an operator manages the schema themselves. +Both automatic strategies now **finish an upgrade**, because neither used to. +`EnsureCreated` creates a missing database and changes nothing about an existing +one, and `Migrate` cannot help a database that has no `__EFMigrationsHistory` — +it would begin by creating tables that are already there. So 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. At startup the edge now +lists the tables the model describes and the database lacks, creates exactly +those from the model through the provider in use — indexes included, and never a +table that already exists, so an upgrade cannot lose a block list — and on the +`migrate` path it first baselines a database with no history table: a migration +is claimed as applied only when every table its target model describes is +already present, and the claim stops at the first one it cannot confirm. What +happened is on `/admin-api/state`: `schemaStrategy`, `schemaTablesAdded`, +`schemaMigrationsBaselined`, `schemaMigrationsApplied`, and `schemaMissingTables` +— the last one is the invariant, and a non-empty answer names a pillar this build +can run with no storage behind it. `none` changes nothing and reports all of it +the same way. + ## Admin API Requires `X-Admin-Token` (or `?token=`). **No token configured means the admin @@ -912,9 +930,9 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-04 with the -refusal page on it: build 0 warnings / 0 errors, unit **227/227**, integration -**225/225 in 20 s**, console **90 assertions, 0 failed**, smoke **passed 52, -failed 0**, and compose **209 passed, 0 failed** against the built image at +schema upgrade on it: build 0 warnings / 0 errors, unit **240/240**, integration +**230/230 in 22 s**, console **90 assertions, 0 failed**, smoke **passed 52, +failed 0**, and compose **216 passed, 0 failed** against the built image at 261 MB. The smoke count moved by more than its new scene: the edge was being started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the @@ -1112,16 +1130,19 @@ Stated, because a defence that hides its failure modes is not a defence. with its own outage story. Alerts raised while the process was down are never pushed at all. The table is what an operator reads; the push is what makes a 03:00 outage reach something that acts. -* **A database that predates a table does not gain it.** The default schema - step is `EnsureCreated`: it creates a missing database and changes nothing - about an existing one. The migration set is there for the `migrate` path and - now covers `source_streaks` and `request_rules`, but an upgrade that keeps its - database can arrive with every table except the new one. That is why the - snapshot refresh reads the rules in a statement of their own: a missing - `request_rules` costs the rules pillar and says so — `requestRulesAvailable` - and `requestRulesError` on `/admin-api/state`, a NOT READ line over the rules - table — instead of freezing the operator's block list, which is the failure - this file keeps warning about. +* **An upgrade adds tables; it never changes one.** The startup step creates the + tables a database predates, but it recognises a table by its name, so a + migration that *alters* an existing table is not something it can perform or + baseline honestly — that still needs a human decision, and the edge refuses to + guess one rather than applying a migration whose effect it cannot check. The + baseline rule is exact while this project's migrations only add tables, which + both of the ones that exist do; the day one changes a column, the claim has to + be made by hand. Reading a table that is there but unreadable is still reported + rather than papered over: the snapshot refresh reads the rules in a statement + of their own, so a `request_rules` that cannot be read costs the rules pillar + and says so — `requestRulesAvailable` and `requestRulesError` on + `/admin-api/state`, a NOT READ line over the rules table — instead of freezing + the operator's block list, which is the failure this file keeps warning about. * **A browser gets a page, and the page is not the operator's.** The wording is ours, one template, fixed per verdict. An operator who wants their own brand and their own sentence on a block page cannot have one yet — the extension @@ -1142,12 +1163,12 @@ Stated, because a defence that hides its failure modes is not a defence. ``` dotnet/ OpenWaf.Domain/ pure decision core: source key, streak, ordered decision, refusal page - OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo + OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo, in-place schema upgrade OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode - OpenWaf.Tests.Unit/ 227 tests over the decision logic, the budget window, the refusal wording and the durability counters - OpenWaf.Tests.Integration/ 225 tests driving the real pipeline against a fake upstream + OpenWaf.Tests.Unit/ 240 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters + OpenWaf.Tests.Integration/ 230 tests driving the real pipeline against a fake upstream scripts/smoke.sh 52 assertions against a running edge + a real upstream -scripts/compose-smoke.sh 209 assertions against the built image (compose + nginx) +scripts/compose-smoke.sh 216 assertions against the built image (compose + nginx) scripts/console-check.cjs 90 assertions against the page, in a real Chromium scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2) .github/workflows/ci.yml runs the gates on every push diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index c353277..fbfe5c8 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -4,6 +4,7 @@ using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Security; using OpenWaf.Edge.Pipeline; +using OpenWaf.Edge.Startup; using OpenWaf.Infrastructure.Geo; using OpenWaf.Infrastructure.Persistence; @@ -615,7 +616,7 @@ internal static class AdminEndpoints }); }); - group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, HttpContext ctx) => + group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, HttpContext ctx) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; @@ -715,6 +716,17 @@ internal static class AdminEndpoints // and "the rules table is not there" have to be different answers. requestRulesAvailable = state.RulesAvailable, requestRulesError = state.RulesError, + // The schema this edge is serving against (OPEN-55). A database that + // predates a table used to be invisible: the pillar it needs answered + // as if there were nothing to see. These four fields say which step + // ran, what it had to add, and — the invariant — whether anything is + // still missing. Non-empty here names a pillar this build can run + // with no storage behind it. + schemaStrategy = schema.Strategy, + schemaTablesAdded = schema.TablesAdded, + schemaMigrationsBaselined = schema.MigrationsBaselined, + schemaMigrationsApplied = schema.MigrationsApplied, + schemaMissingTables = schema.MissingTables, // The volume pillar (OPEN-56): what the budget is, and whether this // process is counting anything. "No source is over budget" and "the // pillar is off" look identical in a listing, and only one of them is diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index b0da858..c85053b 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -96,6 +96,8 @@ if (string.IsNullOrWhiteSpace(geoPath)) geoPath = Environment.GetEnvironmentVari builder.Services.AddSingleton(sp => new MaxMindGeoIpLookup( geoPath, sp.GetRequiredService>())); +// What the schema step did at startup, read back on /admin-api/state (OPEN-55). +builder.Services.AddSingleton(); builder.Services.AddHostedService(); // Registered as themselves as well as hosted services: the admin surface and // the tests need to reach the writer to force a flush, and AddHostedService diff --git a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs index 6e5ec09..f401016 100644 --- a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs +++ b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs @@ -21,6 +21,8 @@ internal sealed class EdgeStateWarmer( EdgeStateStore state, IStreakTracker streaks, RateTracker rates, + SchemaUpgradeReport schema, + IConfiguration configuration, ILogger log) : IHostedService { public async Task StartAsync(CancellationToken cancellationToken) @@ -33,18 +35,33 @@ internal sealed class EdgeStateWarmer( // SQL, so it is not applied to the SQLite default; there the schema is // created from the model instead. OPENWAF_SCHEMA=none leaves both alone // when an operator manages the schema themselves. + // Read through configuration rather than the environment directly: an + // environment variable still sets it (ASP.NET Core puts the environment + // in the configuration), and a test can now ask for a strategy instead of + // mutating process-wide state that parallel tests share. var isSqlite = string.Equals( - Environment.GetEnvironmentVariable("Database__Provider") ?? "sqlite", - "sqlite", StringComparison.OrdinalIgnoreCase); - var strategy = Environment.GetEnvironmentVariable("OPENWAF_SCHEMA") + configuration["Database:Provider"] ?? "sqlite", "sqlite", StringComparison.OrdinalIgnoreCase); + var strategy = configuration["OPENWAF_SCHEMA"] ?? (isSqlite ? "ensurecreated" : "migrate"); + schema.Strategy = strategy; switch (strategy.ToLowerInvariant()) { case "ensurecreated": await CreateSchemaAsync(db, migrate: false, cancellationToken); + // EnsureCreated is the step that creates a missing database, and + // the step that changes nothing about an existing one. The second + // half is what an upgrade needs: the tables this build expects + // and this database predates, created in place. + schema.TablesAdded = (await SchemaUpgrader.AddMissingTablesAsync(db, log, cancellationToken)).Count; break; case "migrate": + // A database that has tables but no history table cannot be + // migrated: the migration set would start by creating tables that + // are already there. Claim the ones that demonstrably ran, then + // run the rest. + schema.MigrationsBaselined = await SchemaUpgrader.BaselineIfUntrackedAsync(db, log, cancellationToken); + schema.MigrationsApplied = await SchemaUpgrader.PendingMigrationsAsync(db, cancellationToken); await CreateSchemaAsync(db, migrate: true, cancellationToken); break; default: @@ -52,6 +69,16 @@ internal sealed class EdgeStateWarmer( break; } + // Asked after the step rather than instead of it, because the operator + // who manages the schema themselves needs the same answer: a pillar this + // build can run either has its table or it does not. + schema.MissingTables = await SchemaUpgrader.MissingTablesAsync(db, cancellationToken); + if (schema.MissingTables.Count > 0) + log.LogError( + "edge: the database is still missing {Tables} — the pillars that need them report themselves " + + "unavailable on /admin-api/state instead of answering with nothing.", + string.Join(", ", schema.MissingTables)); + await state.WarmUpAsync(cancellationToken); // The map bounds come from the policy, and both trackers read them once diff --git a/dotnet/OpenWaf.Edge/Startup/SchemaUpgradeReport.cs b/dotnet/OpenWaf.Edge/Startup/SchemaUpgradeReport.cs new file mode 100644 index 0000000..91abc97 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Startup/SchemaUpgradeReport.cs @@ -0,0 +1,29 @@ +namespace OpenWaf.Edge.Startup; + +/// +/// What the schema step did when this edge started, kept for the operator to ask +/// about afterwards (OPEN-55). +/// +/// The schema step runs once, before the first request, and its output used to +/// be a log line nobody reads at 03:00. The question it answers — does the +/// database this edge is serving against actually have the tables this build +/// needs — is a live question, so the answer lives on the state surface next to +/// the pillars it explains. +/// +internal sealed class SchemaUpgradeReport +{ + public string Strategy { get; set; } = "not run"; + + /// Tables this start had to create because the database predated them. + public int TablesAdded { get; set; } + + /// Migrations written into a history table the database did not have. + public int MigrationsBaselined { get; set; } + + /// Migrations that then ran. + public int MigrationsApplied { get; set; } + + /// What is still missing after all of it. Empty is the invariant; anything + /// else names a pillar this build can run with no storage behind it. + public IReadOnlyList MissingTables { get; set; } = []; +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SchemaBaseline.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaBaseline.cs new file mode 100644 index 0000000..a45c7b9 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaBaseline.cs @@ -0,0 +1,56 @@ +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Which migrations may be claimed as already applied to a database that has no +/// __EFMigrationsHistory (OPEN-55). +/// +/// The default schema step is EnsureCreated: it creates a missing +/// database and changes nothing about an existing one. So an upgrade keeps a +/// schema with every table except the new ones, and the migration set — the +/// thing that knows how to add them — cannot be used either, because a database +/// EnsureCreated made has no history table and Migrate would try to run +/// the initial migration over tables that are already there. +/// +/// The claim this makes is narrow and checkable: a migration counts as applied +/// when every table its target model describes is already in the database. That +/// is exact while the project's migrations only add tables, which both of the +/// ones that exist do. It is not a general baseline: a migration that changes an +/// existing table cannot be recognised from the table's name, and this refuses +/// rather than guesses — the prefix stops at the first migration it cannot +/// confirm, so a later one is never applied on top of an unclaimed earlier one. +/// +public static class SchemaBaseline +{ + /// the migration id, in the order the migration assembly lists them. + /// every table that migration's target model describes — not + /// only the ones it creates, which is what makes a data-only or index-only + /// migration recognisable too. + public sealed record Migration(string Id, IReadOnlyList Tables); + + /// + /// The migrations to write into the history table before migrating. + /// Empty means "claim nothing": either the database is empty (the migrations + /// will create it and record themselves), or the first thing the migration + /// set describes is missing and nothing can be honestly claimed about the + /// rest. + /// + public static IReadOnlyList Choose(IReadOnlyList migrations, IReadOnlySet existingTables) + { + // An empty database is not an upgrade; it is a first install, and the + // migrations describe it from the beginning. + if (existingTables.Count == 0) return []; + + var claimed = new List(); + foreach (var migration in migrations) + { + if (migration.Tables.Count > 0 && migration.Tables.All(existingTables.Contains)) + { + claimed.Add(migration.Id); + continue; + } + break; + } + + return claimed; + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SchemaDdl.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaDdl.cs new file mode 100644 index 0000000..025d3d8 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaDdl.cs @@ -0,0 +1,90 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// The statements of a model-generated script that belong to a set of tables +/// (OPEN-55). +/// +/// GenerateCreateScript emits the whole schema; an in-place upgrade must +/// run only what is missing, because running the rest would fail on tables that +/// already hold the operator's block list. The input here is EF's own output for +/// the provider in use — not hand-written DDL — so the columns, the types and +/// the indexes of a table added this way are exactly what a fresh database +/// would have got. +/// +/// The shapes recognised are the three EF emits when it creates a table: +/// CREATE TABLE "t" (…), CREATE [UNIQUE] INDEX … ON "t" (…) and +/// ALTER TABLE "t" ADD CONSTRAINT …. Anything else in the script is left +/// out, which is the safe direction: an unrecognised statement means a table +/// stays missing and the edge says so, rather than a statement running against a +/// table that was already there. +/// +public static class SchemaDdl +{ + private static readonly Regex CreateIndexOn = new( + @"^CREATE\s+(?:UNIQUE\s+)?INDEX\s+.+\bON\s+""?(?[A-Za-z0-9_]+)""?", + RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); + + private static readonly Regex CreateOrAlterTable = new( + @"^(?:CREATE\s+TABLE|ALTER\s+TABLE)\s+""?(?
[A-Za-z0-9_]+)""?", + RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); + + public static IReadOnlyList StatementsFor(string script, IReadOnlySet tables) + { + var kept = new List(); + foreach (var statement in Statements(script)) + { + var owner = OwningTable(statement); + if (owner is not null && tables.Contains(owner)) kept.Add(statement); + } + + return kept; + } + + /// + /// One statement at a time. Batches are separated by GO on providers + /// that have the concept (postgres) and by nothing at all on sqlite; a + /// statement ends at a semicolon that closes its line. + /// + public static IReadOnlyList Statements(string script) + { + var statements = new List(); + var buffer = new StringBuilder(); + + foreach (var raw in script.Replace("\r\n", "\n").Split('\n')) + { + var line = raw.TrimEnd(); + if (line.Trim().Equals("GO", StringComparison.OrdinalIgnoreCase)) + { + Add(statements, buffer); + continue; + } + + if (line.Length == 0 && buffer.Length == 0) continue; + + buffer.AppendLine(raw); + if (line.EndsWith(';')) Add(statements, buffer); + } + + Add(statements, buffer); + return statements; + } + + private static void Add(List statements, StringBuilder buffer) + { + var statement = buffer.ToString().Trim(); + if (statement.Length > 0) statements.Add(statement); + buffer.Clear(); + } + + private static string? OwningTable(string statement) + { + var index = CreateIndexOn.Match(statement); + if (index.Success) return index.Groups["table"].Value; + + var table = CreateOrAlterTable.Match(statement); + return table.Success ? table.Groups["table"].Value : null; + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs new file mode 100644 index 0000000..1a1876c --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs @@ -0,0 +1,192 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Logging; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// What this process did to the schema when it started (OPEN-55). +/// +/// A record rather than a log line, because the operator has to be able to ask +/// the running edge whether the tables this build expects are actually in the +/// database it is serving against. Before this, the only symptom of a schema +/// that predates a feature was a pillar that quietly answered nothing. +/// +public sealed record SchemaUpgradeOutcome( + string Strategy, + int TablesAdded, + int MigrationsBaselined, + int MigrationsApplied, + IReadOnlyList MissingTables); + +/// +/// Brings an existing database up to the schema the current build needs. +/// +/// EnsureCreated — the default on sqlite — creates a missing database and +/// changes nothing about an existing one, so an upgrade that keeps its database +/// arrives with every table except the new ones. Migrate — the default on +/// postgres — cannot rescue that database either: it has no history table, so +/// the migration set would begin by creating tables that are already there. Same +/// bug, two faces, and both are fixed here. +/// +/// What is never done is a destructive one. A table that exists is left alone +/// with everything in it; only what is absent is created, and it is created from +/// the model through the provider in use, so an upgraded database and a fresh +/// one have the same shape. +/// +public static class SchemaUpgrader +{ + /// + /// Tables the current model describes that this database does not have. + /// Empty is the invariant; non-empty means a pillar this build can run has + /// no storage behind it. + /// + public static async Task> MissingTablesAsync(OpenWafDbContext db, CancellationToken ct = default) + { + var existing = await ExistingTablesAsync(db, ct); + return ModelTables(db).Where(table => !existing.Contains(table)).ToList(); + } + + /// + /// Create, in place, the tables this database predates. Returns what it + /// added — empty when there was nothing to add, which is every start after + /// the first one. + /// + public static async Task> AddMissingTablesAsync( + OpenWafDbContext db, ILogger log, CancellationToken ct = default) + { + var missing = await MissingTablesAsync(db, ct); + if (missing.Count == 0) return missing; + + var statements = SchemaDdl.StatementsFor( + db.Database.GenerateCreateScript(), + new HashSet(missing, StringComparer.OrdinalIgnoreCase)); + + if (statements.Count == 0) + { + // The model says these tables are missing and the generated script + // has nothing recognisable that creates them. Creating nothing and + // saying so is the only honest move left. + log.LogError( + "edge: the database is missing {Tables} but no statement in the generated schema creates them — " + + "the affected pillars will report themselves unavailable rather than answer with nothing.", + string.Join(", ", missing)); + return []; + } + + foreach (var statement in statements) + await db.Database.ExecuteSqlRawAsync(statement, ct); + + log.LogWarning( + "edge: the database predates the current schema — created {Count} missing table(s) in place: {Tables}. " + + "Nothing that was already in the database was touched, so the operator's lists are intact.", + missing.Count, string.Join(", ", missing)); + + return missing; + } + + /// + /// Give a database that predates the migration set a history table, so the + /// migration then applies only what is genuinely missing. Returns how many + /// migrations were claimed; zero means nothing was claimed — either the + /// database is empty and the migrations will describe it from the beginning, + /// or the claim could not be made honestly and the migration is left to + /// report what it finds. + /// + public static async Task BaselineIfUntrackedAsync(OpenWafDbContext db, ILogger log, CancellationToken ct = default) + { + var history = db.GetService(); + if (await history.ExistsAsync(ct)) return 0; + + var existing = await ExistingTablesAsync(db, ct); + if (existing.Count == 0) return 0; + + var assembly = db.GetService(); + var migrations = new List(); + var productVersions = new Dictionary(StringComparer.Ordinal); + + foreach (var id in db.Database.GetMigrations()) + { + var migration = assembly.CreateMigration(assembly.Migrations[id], db.Database.ProviderName ?? string.Empty); + migrations.Add(new SchemaBaseline.Migration( + id, + migration.TargetModel.GetEntityTypes() + .Select(entity => entity.GetTableName()) + .Where(name => name is not null) + .Select(name => name!) + .Distinct() + .ToList())); + productVersions[id] = migration.TargetModel.FindAnnotation("ProductVersion")?.Value?.ToString() ?? "unknown"; + } + + var claimed = SchemaBaseline.Choose(migrations, existing); + if (claimed.Count == 0) + { + log.LogWarning( + "edge: the database has {Count} table(s) and no migration history, and none of the migrations " + + "can be shown to have run — not baselining, so the migration will run against it and fail loudly " + + "rather than be guessed at.", existing.Count); + return 0; + } + + await db.Database.ExecuteSqlRawAsync(history.GetCreateScript(), ct); + foreach (var id in claimed) + await db.Database.ExecuteSqlRawAsync( + history.GetInsertScript(new HistoryRow(id, productVersions[id])), ct); + + log.LogWarning( + "edge: the database has no migration history — baselined {Claimed} of {Total} migrations " + + "({Migrations} were already applied to it) and will run the rest.", + claimed.Count, migrations.Count, string.Join(", ", claimed)); + + return claimed.Count; + } + + /// + /// How many migrations this database still has to run. + /// + public static async Task PendingMigrationsAsync(OpenWafDbContext db, CancellationToken ct = default) + => (await db.Database.GetPendingMigrationsAsync(ct)).Count(); + + /// + /// The tables this database actually has. Provider-specific because there is + /// no provider-neutral way to ask it, and an empty answer from a query that + /// does not exist on this provider would read as "everything is missing" — + /// which is the one answer that makes an upgrade destructive. + /// + private static async Task> ExistingTablesAsync(OpenWafDbContext db, CancellationToken ct) + { + var sql = db.Database.ProviderName switch + { + "Microsoft.EntityFrameworkCore.Sqlite" => "SELECT name FROM sqlite_master WHERE type = 'table'", + "Npgsql.EntityFrameworkCore.PostgreSQL" => "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = current_schema()", + _ => throw new NotSupportedException( + $"the in-place schema upgrade has no table listing for {db.Database.ProviderName}") + }; + + var tables = new HashSet(StringComparer.OrdinalIgnoreCase); + var connection = db.Database.GetDbConnection(); + var openedHere = connection.State != ConnectionState.Open; + if (openedHere) await db.Database.OpenConnectionAsync(ct); + + try + { + await using var command = connection.CreateCommand(); + command.CommandText = sql; + await using var reader = await command.ExecuteReaderAsync(ct); + while (await reader.ReadAsync(ct)) tables.Add(reader.GetString(0)); + } + finally + { + if (openedHere) await db.Database.CloseConnectionAsync(); + } + + return tables; + } + + private static IReadOnlyList ModelTables(OpenWafDbContext db) + => db.GetService().Model.GetRelationalModel().Tables.Select(table => table.Name).ToList(); +} diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs index 620845b..352577d 100644 --- a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs +++ b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs @@ -42,7 +42,8 @@ internal sealed class EdgeFixture : IAsyncDisposable int? alertWebhookTimeoutSeconds = null, string rate = "Off", int rateLimitPerWindow = 100, - double rateWindowSeconds = 60) + double rateWindowSeconds = 60, + string? schema = null) { _sharedDb = dbPath is not null; _dbPath = dbPath ?? Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db"); @@ -90,7 +91,12 @@ internal sealed class EdgeFixture : IAsyncDisposable 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); + // 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); }); } diff --git a/dotnet/OpenWaf.Tests.Integration/SchemaUpgradeTests.cs b/dotnet/OpenWaf.Tests.Integration/SchemaUpgradeTests.cs new file mode 100644 index 0000000..d6a0d3f --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/SchemaUpgradeTests.cs @@ -0,0 +1,295 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Data.Sqlite; + +namespace OpenWaf.Tests.Integration; + +/// +/// The upgrade path (OPEN-55). The default schema step is EnsureCreated, +/// 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 compose down 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. +/// +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 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; + } + + /// + /// 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. + /// + 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> 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(); + while (await reader.ReadAsync()) names.Add(reader.GetString(0)); + SqliteConnection.ClearAllPools(); + return names; + } + + private static async Task> 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(); + 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()); + // Both migrations are 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. + Assert.Equal(2, 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); + } + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/SchemaBaselineTests.cs b/dotnet/OpenWaf.Tests.Unit/SchemaBaselineTests.cs new file mode 100644 index 0000000..cf92797 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/SchemaBaselineTests.cs @@ -0,0 +1,84 @@ +using OpenWaf.Infrastructure.Persistence; +using Xunit; + +namespace OpenWaf.Tests.Unit; + +/// +/// The claim a baseline is allowed to make (OPEN-55). A database that has no +/// migration history can only be migrated if the migrations that already ran are +/// written down first, and writing down one that did not run is how an upgrade +/// silently skips a table the operator is waiting for. +/// +public class SchemaBaselineTests +{ + private static readonly SchemaBaseline.Migration Initial = new( + "20261001002803_InitialCreate", + ["block_entries", "allow_entries", "country_rules", "edge_alerts", "source_observations", "policy_settings"]); + + private static readonly SchemaBaseline.Migration Rules = new( + "20261004171633_AddRequestRules", + ["block_entries", "allow_entries", "country_rules", "edge_alerts", "source_observations", "policy_settings", + "request_rules", "source_streaks"]); + + private static IReadOnlySet Set(params string[] tables) => tables.ToHashSet(StringComparer.OrdinalIgnoreCase); + + [Fact] + public void An_empty_database_claims_nothing_because_the_migrations_describe_it_from_the_start() + { + Assert.Empty(SchemaBaseline.Choose([Initial, Rules], Set())); + } + + [Fact] + public void A_database_that_predates_a_table_claims_only_the_migration_that_ran() + { + var claimed = SchemaBaseline.Choose([Initial, Rules], Set( + "block_entries", "allow_entries", "country_rules", "edge_alerts", "source_observations", "policy_settings")); + + Assert.Equal([Initial.Id], claimed); + } + + [Fact] + public void A_database_at_the_current_schema_claims_every_migration_so_the_migration_is_a_no_op() + { + var claimed = SchemaBaseline.Choose([Initial, Rules], Set( + "block_entries", "allow_entries", "country_rules", "edge_alerts", "source_observations", "policy_settings", + "request_rules", "source_streaks")); + + Assert.Equal([Initial.Id, Rules.Id], claimed); + } + + [Fact] + public void The_claim_stops_at_the_first_migration_it_cannot_confirm_so_a_later_one_is_never_claimed_alone() + { + // A database holding only what the second migration added cannot have + // had the first one run: claiming the second would let the first be + // skipped forever. + var claimed = SchemaBaseline.Choose([Initial, Rules], Set("request_rules", "source_streaks")); + + Assert.Empty(claimed); + } + + [Fact] + public void Table_names_are_matched_the_way_the_provider_returns_them() + { + var claimed = SchemaBaseline.Choose([Initial, Rules], Set( + "BLOCK_ENTRIES", "Allow_Entries", "Country_Rules", "Edge_Alerts", "Source_Observations", "Policy_Settings")); + + Assert.Equal([Initial.Id], claimed); + } + + [Fact] + public void A_migration_that_adds_nothing_of_its_own_is_still_recognised_by_the_model_it_describes() + { + // The table set is the migration's target model, not the operations it + // performs, so a data-only or index-only migration in the middle of the + // set does not break the chain. + var backfill = new SchemaBaseline.Migration("20261005000000_BackfillNotes", Rules.Tables); + + var claimed = SchemaBaseline.Choose([Initial, Rules, backfill], Set( + "block_entries", "allow_entries", "country_rules", "edge_alerts", "source_observations", "policy_settings", + "request_rules", "source_streaks")); + + Assert.Equal([Initial.Id, Rules.Id, backfill.Id], claimed); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/SchemaDdlTests.cs b/dotnet/OpenWaf.Tests.Unit/SchemaDdlTests.cs new file mode 100644 index 0000000..7ba3d38 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/SchemaDdlTests.cs @@ -0,0 +1,101 @@ +using OpenWaf.Infrastructure.Persistence; +using Xunit; + +namespace OpenWaf.Tests.Unit; + +/// +/// Which statements of a model-generated script may run against a database that +/// already has other tables in it (OPEN-55). Running the whole script is the +/// destructive option — it fails on the tables holding the operator's block list +/// — so the filter has to keep everything that belongs to a missing table, +/// including its indexes, and nothing that belongs to a table that is there. +/// +public class SchemaDdlTests +{ + private const string Script = """ + CREATE TABLE "block_entries" ( + "Id" INTEGER NOT NULL CONSTRAINT "PK_block_entries" PRIMARY KEY AUTOINCREMENT, + "SourceKey" TEXT NOT NULL + ); + + + CREATE TABLE "request_rules" ( + "Id" INTEGER NOT NULL CONSTRAINT "PK_request_rules" PRIMARY KEY AUTOINCREMENT, + "Pattern" TEXT NOT NULL + ); + + + CREATE INDEX "IX_request_rules_ExpiresAt" ON "request_rules" ("ExpiresAt"); + + + CREATE INDEX "IX_block_entries_SourceKey" ON "block_entries" ("SourceKey"); + """; + + private static IReadOnlySet Set(params string[] tables) => tables.ToHashSet(StringComparer.OrdinalIgnoreCase); + + [Fact] + public void A_statement_is_split_at_the_semicolon_that_closes_its_line() + { + Assert.Equal(4, SchemaDdl.Statements(Script).Count); + } + + [Fact] + public void A_postgres_batch_separator_ends_a_statement_rather_than_joining_two() + { + var statements = SchemaDdl.Statements(""" + CREATE TABLE "a" ("Id" int); + GO + CREATE INDEX "ix_b" ON "b" ("Id"); + GO + """); + + Assert.Equal(2, statements.Count); + Assert.Contains("CREATE TABLE \"a\"", statements[0]); + Assert.DoesNotContain("CREATE TABLE", statements[1]); + } + + [Fact] + public void A_missing_table_keeps_its_own_create_and_its_own_index() + { + var kept = SchemaDdl.StatementsFor(Script, Set("request_rules")); + + Assert.Equal(2, kept.Count); + Assert.Contains("CREATE TABLE \"request_rules\"", kept[0]); + Assert.Contains("IX_request_rules_ExpiresAt", kept[1]); + } + + [Fact] + public void A_table_that_is_already_there_is_never_touched_again() + { + var kept = SchemaDdl.StatementsFor(Script, Set("request_rules")); + + Assert.All(kept, statement => Assert.DoesNotContain("block_entries", statement)); + } + + [Fact] + public void A_constraint_added_to_a_missing_table_belongs_to_that_table() + { + var kept = SchemaDdl.StatementsFor(""" + ALTER TABLE "source_streaks" ADD CONSTRAINT "FK_x" FOREIGN KEY ("a") REFERENCES "block_entries" ("Id"); + """, Set("source_streaks")); + + Assert.Single(kept); + } + + [Fact] + public void A_statement_this_filter_does_not_recognise_is_left_out_rather_than_run() + { + // Unrecognised means "do not run it": the safe failure is a table that + // stays missing and is reported, not a statement executed against a + // table that already holds data. + var kept = SchemaDdl.StatementsFor("INSERT INTO \"request_rules\" (\"Pattern\") VALUES ('x');", Set("request_rules")); + + Assert.Empty(kept); + } + + [Fact] + public void Nothing_is_kept_for_a_table_that_is_not_asked_for() + { + Assert.Empty(SchemaDdl.StatementsFor(Script, Set())); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index bb93fd5..893711f 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1318,6 +1318,57 @@ check 'putting the table back brings readiness back' '200' "$OPEN26_READY_BACK" check 'and the listing answers again' '200' \ "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks")" +echo '- a database that predates a table gains it when the edge restarts' +# OPEN-55. The default schema step is EnsureCreated: it 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. This stack is that +# state by construction — its data volume outlives `compose down`, which is how +# the gap was first noticed here. The table is dropped from the volume, the edge +# restarts, and the question is whether the pillar works afterwards. +EDGE_CID=$(docker compose ps -q edge) +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +c.execute("DROP TABLE request_rules") +c.execute("DROP TABLE source_streaks") +print("dropped; tables now:", sorted(r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'"))) +PYSQL +docker compose restart edge >/dev/null 2>&1 +OPEN55_READY='000' +for _ in $(seq 1 12); do + code "$EDGE/no-such-page" >/dev/null + OPEN55_READY=$(code "$EDGE/readyz") + [ "$OPEN55_READY" = "200" ] && break + sleep 3 +done +check 'the restarted edge is ready again' '200' "$OPEN55_READY" +OPEN55_STATE=$(admin "$EDGE/admin-api/state") +OPEN55_ADDED=$(printf '%s' "$OPEN55_STATE" | jval schemaTablesAdded) +printf ' info tables this start had to create: %s\n' "${OPEN55_ADDED:-none}" +check 'the state names the tables it had to add' 'yes' \ + "$([ "${OPEN55_ADDED:-0}" -ge 2 ] && echo yes || echo no)" +check 'and says nothing the build needs is missing now' '[]' \ + "$(printf '%s' "$OPEN55_STATE" | jval schemaMissingTables)" +check 'the rules pillar is reading again' 'true' \ + "$(printf '%s' "$OPEN55_STATE" | jval requestRulesAvailable)" +# A table that exists is worth nothing unless the pillar behind it answers. The +# rule is written after the upgrade, so it can only work if the table it lands in +# is the one the guard reads. +OPEN55_IP="203.0.113.$(( 60 + RANDOM % 30 ))" +OPEN55_RULE_WRITE=$(admin -X POST -H 'Content-Type: application/json' \ + -d "{\"pattern\":\"/upgrade-check*\",\"action\":\"block\",\"note\":\"compose: written after the upgrade\"}" \ + -w '\nCODE%{http_code}' "$EDGE/admin-api/rules") +OPEN55_RULE_CODE=$(printf '%s' "$OPEN55_RULE_WRITE" | sed -n 's/.*CODE//p') +printf ' info the rule write answered: %s %s\n' "$OPEN55_RULE_CODE" \ + "$(printf '%s' "$OPEN55_RULE_WRITE" | sed -n '1s/.*/&/p' | cut -c1-120)" +check 'a rule can be written into the table that was added' '204' "$OPEN55_RULE_CODE" +check 'and it refuses the path on the restarted edge' '403' \ + "$(code -H "X-Forwarded-For: $OPEN55_IP" "$EDGE/upgrade-check")" +OPEN55_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/upgrade-check*'" id) +check 'and the rule is removable again, so the volume is left clean' '204' \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/rules/$OPEN55_RULE")" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ]