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;
///
/// 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;
}
///
/// 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.
///
private static int MigrationCount() =>
typeof(OpenWafDbContext).Assembly
.GetTypes()
.Count(t => !t.IsAbstract
&& typeof(Migration).IsAssignableFrom(t)
&& t.GetCustomAttribute() is not null);
///
/// 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());
// 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);
}
}
}