2026-10-20 07:21:28 +02:00
|
|
|
using Heimdall.Domain.Entities;
|
|
|
|
|
using Heimdall.Infrastructure.Data;
|
|
|
|
|
using Heimdall.Infrastructure.Data.Interceptors;
|
|
|
|
|
using Heimdall.TestCommon;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
|
|
|
using Microsoft.EntityFrameworkCore.Migrations;
|
|
|
|
|
using Npgsql;
|
|
|
|
|
using Shouldly;
|
2026-11-04 13:33:30 +01:00
|
|
|
using Heimdall.Infrastructure.Identity;
|
2026-10-20 07:21:28 +02:00
|
|
|
|
|
|
|
|
namespace Heimdall.Infrastructure.Tests;
|
|
|
|
|
|
|
|
|
|
[Collection("PostgresInfra")]
|
|
|
|
|
public class AuthMigrationCompatibilityTests(PostgreSqlContainerFixture postgres)
|
|
|
|
|
{
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Upgrade_and_rollback_preserve_existing_identity_accounts()
|
|
|
|
|
{
|
|
|
|
|
var database = $"auth_migration_{Guid.NewGuid():N}";
|
|
|
|
|
await using var admin = new NpgsqlConnection(postgres.ConnectionString);
|
|
|
|
|
await admin.OpenAsync();
|
|
|
|
|
await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", admin))
|
|
|
|
|
await create.ExecuteNonQueryAsync();
|
|
|
|
|
var connectionString = new NpgsqlConnectionStringBuilder(postgres.ConnectionString) { Database = database }.ConnectionString;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var options = new DbContextOptionsBuilder<AppDbContext>().UseNpgsql(connectionString).Options;
|
|
|
|
|
await using var db = new AppDbContext(options, new AuditInterceptor());
|
|
|
|
|
db.Database.HasPendingModelChanges().ShouldBeFalse();
|
|
|
|
|
var prior = db.Database.GetMigrations().Last(x => string.CompareOrdinal(x, "20261020002409") < 0);
|
|
|
|
|
var migrator = db.GetService<IMigrator>();
|
|
|
|
|
await migrator.MigrateAsync(prior);
|
2026-11-04 13:33:30 +01:00
|
|
|
var user = new IdentityAppUser { Id = Guid.NewGuid(), Email = "existing@example.test", UserName = "existing", SecurityStamp = "preserved" };
|
2026-10-20 07:21:28 +02:00
|
|
|
db.Users.Add(user);
|
|
|
|
|
await db.SaveChangesAsync();
|
|
|
|
|
await migrator.MigrateAsync();
|
|
|
|
|
(await db.Users.AsNoTracking().SingleAsync()).SecurityStamp.ShouldBe("preserved");
|
|
|
|
|
db.Set<LoginChallenge>().Add(new LoginChallenge
|
|
|
|
|
{
|
|
|
|
|
Id = new string('a', 64), UserId = user.Id, SecurityStamp = user.SecurityStamp, ExpiresAt = DateTime.UtcNow.AddMinutes(5)
|
|
|
|
|
});
|
|
|
|
|
await db.SaveChangesAsync();
|
|
|
|
|
await migrator.MigrateAsync(prior);
|
|
|
|
|
(await db.Users.AsNoTracking().SingleAsync()).Id.ShouldBe(user.Id);
|
|
|
|
|
await migrator.MigrateAsync();
|
|
|
|
|
(await db.Set<LoginChallenge>().CountAsync()).ShouldBe(0);
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
NpgsqlConnection.ClearAllPools();
|
|
|
|
|
await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", admin);
|
|
|
|
|
await drop.ExecuteNonQueryAsync();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|