fix: harden owner bootstrap and auth persistence
This commit is contained in:
@@ -15,6 +15,10 @@ public static class ApplicationBuilderExtensions
|
||||
/// Applies pending EF Core migrations and seeds the initial owner account if none exist.
|
||||
/// Uses a <see cref="SeedAudit"/> guard so the owner is never re-created even if all users
|
||||
/// are deleted — the DB is the single source of truth for the owner password after first seed.
|
||||
///
|
||||
/// Single-transaction guarantee: if the seed block is entered at all (user creation needed
|
||||
/// or just the audit-log write), the SeedAudit row is written inside the same transaction
|
||||
/// so that a crash mid-way can never leave the DB in a re-seedable state.
|
||||
/// </summary>
|
||||
public static async Task EnsureDatabaseAsync(this WebApplication app)
|
||||
{
|
||||
@@ -30,46 +34,49 @@ public static class ApplicationBuilderExtensions
|
||||
if (alreadySeeded)
|
||||
return;
|
||||
|
||||
var ownerEmail = configuration["Owner:Email"]?.Trim().ToLowerInvariant();
|
||||
var ownerPassword = configuration["Owner:Password"];
|
||||
var ownerDisplayName = configuration["Owner:DisplayName"]?.Trim();
|
||||
var ownerEmail = configuration["Bootstrap:OwnerEmail"]?.Trim().ToLowerInvariant();
|
||||
var hasUsers = await db.Users.AnyAsync();
|
||||
|
||||
if (!hasUsers)
|
||||
// ── Double-check SeedAudit after the migration — if another pod wrote it
|
||||
// while we were reading, bail out early. ──
|
||||
alreadySeeded = await db.SeedAudits.AnyAsync(s => s.Key == seedKey);
|
||||
if (alreadySeeded)
|
||||
return;
|
||||
|
||||
// ── Use a strategy-based transaction so the user + audit row are
|
||||
// persisted atomically. If the DB crashes after SaveChanges the
|
||||
// entire transaction is rolled back, preventing partial-seed states.
|
||||
var strategy = db.Database.CreateExecutionStrategy();
|
||||
await strategy.ExecuteAsync(async () =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ownerEmail))
|
||||
throw new InvalidOperationException("Owner:Email is required for initial setup.");
|
||||
await using var tx = await db.Database.BeginTransactionAsync();
|
||||
|
||||
var initialDisplayName = string.IsNullOrWhiteSpace(ownerDisplayName)
|
||||
? PasswordHelper.BuildOwnerDisplayName(ownerEmail)
|
||||
: ownerDisplayName;
|
||||
var initialPassword = string.IsNullOrWhiteSpace(ownerPassword)
|
||||
? PasswordHelper.GenerateTemporaryPassword()
|
||||
: ownerPassword;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(ownerPassword) && ownerPassword.Length < 10)
|
||||
throw new InvalidOperationException("Owner:Password must be at least 10 characters when provided explicitly.");
|
||||
|
||||
db.Users.Add(new NexusUser
|
||||
if (!hasUsers)
|
||||
{
|
||||
Email = ownerEmail,
|
||||
NormalizedEmail = AuthService.NormalizeEmail(ownerEmail),
|
||||
DisplayName = initialDisplayName,
|
||||
PasswordHash = PasswordSecurity.Hash(initialPassword),
|
||||
Role = "owner"
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
if (string.IsNullOrWhiteSpace(ownerEmail))
|
||||
throw new InvalidOperationException("Bootstrap:OwnerEmail is required for initial setup.");
|
||||
|
||||
var initialDisplayName = PasswordHelper.BuildOwnerDisplayName(ownerEmail);
|
||||
var initialPassword = PasswordHelper.GenerateTemporaryPassword();
|
||||
|
||||
db.Users.Add(new NexusUser
|
||||
{
|
||||
Email = ownerEmail,
|
||||
NormalizedEmail = AuthService.NormalizeEmail(ownerEmail),
|
||||
DisplayName = initialDisplayName,
|
||||
PasswordHash = PasswordSecurity.Hash(initialPassword),
|
||||
Role = "owner"
|
||||
});
|
||||
|
||||
if (string.IsNullOrWhiteSpace(ownerPassword))
|
||||
{
|
||||
Console.Error.WriteLine($"[nexus] Initial owner credentials generated: displayName={initialDisplayName}, password={initialPassword}");
|
||||
}
|
||||
}
|
||||
|
||||
// Record the seed attempt regardless of whether users already existed.
|
||||
// This prevents re-seeding even if the Users table is wiped.
|
||||
db.SeedAudits.Add(new SeedAudit { Key = seedKey });
|
||||
await db.SaveChangesAsync();
|
||||
// Record the seed attempt regardless of whether users already existed.
|
||||
// This prevents re-seeding even if the Users table is wiped.
|
||||
db.SeedAudits.Add(new SeedAudit { Key = seedKey });
|
||||
await db.SaveChangesAsync();
|
||||
await tx.CommitAsync();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,11 @@ public sealed class AuthService : IAuthService
|
||||
user.LastLoginAt = DateTimeOffset.UtcNow;
|
||||
user.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
|
||||
// Persist user changes (password upgrade, login timestamp) immediately.
|
||||
// Relying solely on RemoveExpiredTokensAsync / AddRefreshTokenAsync to
|
||||
// trigger SaveChangesAsync is fragile — if zero tokens are expired the
|
||||
// tracked changes might not be flushed before the response is produced.
|
||||
await _users.UpdateAsync(user, ct);
|
||||
await _users.RemoveExpiredTokensAsync(user.Id, ct);
|
||||
return await CreateSessionAsync(user, Guid.NewGuid(), null, ct);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user