using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations.Operations; using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations; namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations; /// /// SQL Server tests for the RemoveAuditLogHashChain migration (2026-11-15): at head the /// hash-chain columns, tables, indexes and chainer role are gone and the purger keeps only its /// original grants; Down restores what AddAuditLogHashChain + AuditMaintenanceGrants /// created; and Up is re-runnable and drops a chainer role that still has members. /// /// /// The tests in this class migrate the fixture database down and back up, so they own their /// fixture (one database per test class) and every test leaves the database fully migrated. /// public sealed class RemoveAuditLogHashChainMigrationTests : IClassFixture { private const string RemoveMigration = "20261115221558_RemoveAuditLogHashChain"; private static readonly string PreviousMigration = MigrationBefore(RemoveMigration); private readonly MsSqlMigrationFixture _fixture; /// Creates the test class with its own migrated SQL Server database. /// The per-class migration fixture. public RemoveAuditLogHashChainMigrationTests(MsSqlMigrationFixture fixture) => _fixture = fixture; /// At head nothing of the hash chain or the maintenance grants is left. /// A task that represents the asynchronous operation. [SkippableFact] public async Task AtHead_TheChainSchema_AndTheMaintenanceGrants_AreGone() { Skip.IfNot(_fixture.Available, _fixture.SkipReason); await AssertRemovedAsync(); } /// /// Down restores the chain schema exactly (columns, tables, indexes, chainer role and grants, /// the purger's maintenance grants); Up then drops it again, also when the chainer role has a /// member; and re-running Up's SQL on the migrated schema changes nothing. /// /// A task that represents the asynchronous operation. [SkippableFact] public async Task DownUp_RoundTrips_DropsAChainerRoleWithMembers_AndIsReRunnable() { Skip.IfNot(_fixture.Available, _fixture.SkipReason); await MigrateToAsync(PreviousMigration); try { Assert.True(await ScalarAsync("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','ChainSeq') IS NULL THEN 0 ELSE 1 END;") == 1); Assert.True(await ScalarAsync("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','RowHash') IS NULL THEN 0 ELSE 1 END;") == 1); Assert.True(await ScalarAsync("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainHead','U') IS NULL THEN 0 ELSE 1 END;") == 1); Assert.True(await ScalarAsync("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainTombstone','U') IS NULL THEN 0 ELSE 1 END;") == 1); Assert.Equal(2, await ScalarAsync( "SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AuditLog') AND name IN ('IX_AuditLog_Unchained','IX_AuditLog_ChainSeq');")); Assert.Contains("scadabridge_audit_chainer|UPDATE|GRANT|ChainSeq", await ReadAuditLogGrantsAsync()); Assert.Contains("scadabridge_audit_purger|UPDATE|GRANT|SourceNode", await ReadAuditLogGrantsAsync()); Assert.Equal(1, await ScalarAsync( "SELECT COUNT(*) FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id " + "WHERE pr.name = 'scadabridge_audit_purger' AND p.class = 0 AND p.permission_name = 'ALTER ANY DATASPACE' AND p.state_desc = 'GRANT';")); // A login was put in the chainer role (the hardened two-login setup): Up must still drop the role. await ExecAsync("IF DATABASE_PRINCIPAL_ID('rm_chain_test_user') IS NULL CREATE USER rm_chain_test_user WITHOUT LOGIN;" + "ALTER ROLE scadabridge_audit_chainer ADD MEMBER rm_chain_test_user;"); } finally { await MigrateToHeadAsync(); } await AssertRemovedAsync(); Assert.Equal(1, await ScalarAsync("SELECT CASE WHEN DATABASE_PRINCIPAL_ID('rm_chain_test_user') IS NULL THEN 0 ELSE 1 END;")); // Re-run Up's SQL against the migrated schema: every statement is guarded. foreach (var op in new RemoveAuditLogHashChain().UpOperations.OfType()) { await ExecAsync(op.Sql); } await AssertRemovedAsync(); } private async Task AssertRemovedAsync() { Assert.Equal(0, await ScalarAsync("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','ChainSeq') IS NULL THEN 0 ELSE 1 END;")); Assert.Equal(0, await ScalarAsync("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','RowHash') IS NULL THEN 0 ELSE 1 END;")); Assert.Equal(0, await ScalarAsync("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainHead','U') IS NULL THEN 0 ELSE 1 END;")); Assert.Equal(0, await ScalarAsync("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainTombstone','U') IS NULL THEN 0 ELSE 1 END;")); Assert.Equal(0, await ScalarAsync( "SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AuditLog') AND name IN ('IX_AuditLog_Unchained','IX_AuditLog_ChainSeq');")); Assert.Equal(0, await ScalarAsync("SELECT CASE WHEN DATABASE_PRINCIPAL_ID('scadabridge_audit_chainer') IS NULL THEN 0 ELSE 1 END;")); Assert.Equal(0, await ScalarAsync( "SELECT COUNT(*) FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id " + "WHERE pr.name = 'scadabridge_audit_purger' AND p.class = 0 AND p.permission_name = 'ALTER ANY DATASPACE';")); // The roles that predate the chain stay, with exactly their original AuditLog grants. Assert.Equal( new[] { "scadabridge_audit_purger|DELETE|GRANT|", "scadabridge_audit_purger|SELECT|GRANT|", "scadabridge_audit_writer|DELETE|DENY|", "scadabridge_audit_writer|INSERT|GRANT|", "scadabridge_audit_writer|SELECT|GRANT|", "scadabridge_audit_writer|UPDATE|DENY|", }, await ReadAuditLogGrantsAsync()); } private async Task ScalarAsync(string sql) { await using var conn = _fixture.OpenConnection(); await using var cmd = new SqlCommand(sql, conn); return (T)Convert.ChangeType((await cmd.ExecuteScalarAsync())!, typeof(T), System.Globalization.CultureInfo.InvariantCulture); } private async Task ExecAsync(string sql) { await using var conn = _fixture.OpenConnection(); await using var cmd = new SqlCommand(sql, conn) { CommandTimeout = 300 }; await cmd.ExecuteNonQueryAsync(); } private async Task ReadAuditLogGrantsAsync() { await using var conn = _fixture.OpenConnection(); await using var cmd = new SqlCommand(@" SELECT pr.name, p.permission_name, p.state_desc, COL_NAME(p.major_id, p.minor_id) FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id WHERE p.major_id = OBJECT_ID('dbo.AuditLog') AND p.class = 1;", conn); var list = new List(); await using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { list.Add($"{reader.GetString(0)}|{reader.GetString(1)}|{reader.GetString(2)}|{(reader.IsDBNull(3) ? "" : reader.GetString(3))}"); } return list.Order(StringComparer.Ordinal).ToArray(); } private async Task MigrateToAsync(string migration) { await using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder() .UseSqlServer(_fixture.ConnectionString, sql => sql.CommandTimeout(600)).Options); await ctx.GetService().MigrateAsync(migration); } private async Task MigrateToHeadAsync() { await using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder() .UseSqlServer(_fixture.ConnectionString, sql => sql.CommandTimeout(600)).Options); await ctx.GetService().MigrateAsync(); } private static string MigrationBefore(string migration) { using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder() .UseSqlServer("Server=unused;Database=unused").Options); var all = ctx.Database.GetMigrations().ToList(); return all[all.IndexOf(migration) - 1]; } }