Files
Khaemhat/tests/Khaemhat.Data.Tests/MigrationTests.cs
T
Alby96andClaude Opus 5.5 032c602b49
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:29:24 +01:00

158 lines
6.6 KiB
C#

using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
using Khaemhat.Data.SystemDatabase;
using Khaemhat.Data.Tests.Support;
namespace Khaemhat.Data.Tests;
[TestClass]
public sealed class MigrationTests
{
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task SystemMigrations_FromZero_ThenReapplied_DoNothing(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
var catalog = MigrationCatalog.ForSystem();
var runner = new MigrationRunner(db.Context);
var first = await runner.RunAsync(db.Target, catalog);
var second = await runner.RunAsync(db.Target, catalog);
Assert.HasCount(catalog.Migrations.Count, first.Applied);
Assert.AreEqual(0, first.AlreadyApplied);
Assert.IsEmpty(second.Applied);
Assert.AreEqual(catalog.Migrations.Count, second.AlreadyApplied);
Assert.IsEmpty(second.Warnings);
await using var unitOfWork = await db.OpenAsync();
var applied = await SchemaVersionStore.ReadAsync(unitOfWork);
CollectionAssert.AreEqual(
catalog.Migrations.Select(m => (m.Module, m.Version, m.Name)).ToArray(),
applied.Select(a => (a.Module, a.Version, a.Name)).ToArray());
Assert.IsTrue(applied.All(a => a.Checksum.Length == 64));
// The tables work through their maps.
var settings = unitOfWork.Repository<Core.Instance.SystemSetting, long>();
await settings.InsertAsync(new Core.Instance.SystemSetting { Key = "smtp.host", Value = "mail.example.com" });
Assert.AreEqual(1, await settings.CountAsync(Querying.Query.For<Core.Instance.SystemSetting>()));
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task UnknownAppliedVersion_IsRefused(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
var runner = new MigrationRunner(db.Context);
await runner.RunAsync(db.Target, MigrationCatalog.ForSystem());
await using (var unitOfWork = await db.OpenAsync())
{
await SchemaVersionStore.RecordAsync(unitOfWork, new AppliedMigration("core", 20991231_001, "from_the_future", DateTime.UtcNow, new string('0', 64)));
}
var error = await Assert.ThrowsExactlyAsync<MigrationException>(() => runner.RunAsync(db.Target, MigrationCatalog.ForSystem()));
StringAssert.Contains(error.Message, "20991231001 from_the_future");
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task FailingMigration_LeavesNoTrace(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
var catalog = MigrationCatalog.Discover(MigrationTarget.Company, [typeof(MigrationTests).Assembly]);
var runner = new MigrationRunner(db.Context);
await Assert.ThrowsAsync<System.Data.Common.DbException>(() => runner.RunAsync(db.Target, catalog));
await using var unitOfWork = await db.OpenAsync();
Assert.IsEmpty(await SchemaVersionStore.ReadAsync(unitOfWork));
var exists = await unitOfWork.QueryAsync<long>(
SqlFragment.Of($"SELECT COUNT(*) FROM test_failing")).ContinueWith(t => t.IsCompletedSuccessfully, TaskScheduler.Default);
Assert.IsFalse(exists, "the table of the failed migration was rolled back");
}
[TestMethod]
public void Catalog_IsOrdered_AndVersionsAreValid()
{
var catalog = MigrationCatalog.ForSystem();
Assert.IsGreaterThanOrEqualTo(2, catalog.Migrations.Count);
CollectionAssert.AreEqual(catalog.Migrations.OrderBy(m => m.Version).ToArray(), catalog.Migrations.ToArray());
Assert.IsTrue(catalog.Migrations.All(m => m.Target == MigrationTarget.System));
}
[TestMethod]
public void Maps_AgreeWithTheMigratedSchema()
{
var systemModel = MigrationCatalog.ForSystem().BuildModel();
var companyModel = MigrationCatalog.ForCompany().BuildModel();
var maps = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly);
var problems = new List<string>();
foreach (var map in maps.Maps)
{
// System tables carry the sys_ prefix (SPEC 5.4); every other table lives in the company databases.
var model = map.Table.StartsWith("sys_", StringComparison.Ordinal) ? systemModel : companyModel;
var table = model.Table(map.Table);
if (table is null)
{
problems.Add($"{map.Table}: no migration creates it");
continue;
}
foreach (var column in map.Columns)
{
var definition = table.Column(column.ColumnName);
if (definition is null)
{
problems.Add($"{map.Table}.{column.ColumnName}: missing in the schema");
}
else if (definition.TypeDescription != column.TypeDescription || definition.IsNullable != column.IsNullable)
{
problems.Add(
$"{map.Table}.{column.ColumnName}: map {column.TypeDescription} null={column.IsNullable}, schema {definition.TypeDescription} null={definition.IsNullable}");
}
}
problems.AddRange(table.Columns.Where(c => map.FindByColumn(c.Name) is null).Select(c => $"{map.Table}.{c.Name}: not mapped"));
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
[TestMethod]
public void InvalidMigrations_AreRejectedByTheCatalog()
{
Assert.ThrowsExactly<InvalidOperationException>(
() => MigrationCatalog.Discover(MigrationTarget.System, [typeof(MigrationTests).Assembly]));
}
}
/// <summary>Creates a table, then fails: used by <see cref="MigrationTests.FailingMigration_LeavesNoTrace"/>.</summary>
[Migration(20261111_001, "failing_on_purpose", Module = "tests")]
public sealed class M20261111_001_FailingOnPurpose : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("test_failing", t => t.Id());
schema.Sql(_ => "SELECT * FROM table_that_does_not_exist");
}
}
/// <summary>A badly numbered system migration: used by <see cref="MigrationTests.InvalidMigrations_AreRejectedByTheCatalog"/>.</summary>
[Migration(2026_001, "bad_version", Target = MigrationTarget.System, Module = "tests")]
public sealed class BadlyNumberedMigration : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
}
}