- Replace IsDevelopment() guard with Seed:DemoOnStartup config flag (default: true, disable via SEED__DEMO_ON_STARTUP=false) - Add Seed:AdminLogin (env SEED__ADMIN_LOGIN) to customize demo admin email - Add Seed:AdminDisplayName (env SEED__ADMIN_DISPLAYNAME) to customize display name - Add Sentry__Dsn env var to docker-compose files (matches .env convention) - Increase Heimdall log level to Debug for startup diagnostics - Add [DIAG] startup logs for Sentry DSN, Data Protection keys, environment - Add Data Protection key directory diagnostic in DependencyInjection
17 KiB
Admin Bootstrap — Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Replace Dev-only admin seeding with a universal first-launch bootstrap that creates an admin with random password (logged once), and disable public registration by default.
Architecture: Bootstrap runs inline in Program.cs after role/group seeding. A new CanRegister CQRS query checks the auth.public-registration.enabled setting. The RegisterHandler default flips from "absent = enabled" to "absent = disabled". UI hides the register link conditionally.
Tech Stack: .NET 10, ASP.NET Core Identity, Blazor Server, CQRS (MediatR), C# 13
Global Constraints
IAuthDataServicemust be injectable via DI (it's already inDependencyInjection.csline 115)- Must use
RandomNumberGeneratorfor cryptographically secure random password (notSystem.Random) - Must log password via
ILoggerbeforeapp.Run()— visible in Docker logs - Password must satisfy Identity rules: min 12 chars, digit + lower + upper + non-alphanumeric
- Bootstrap admin user has
MustChangePassword = true BOOTSTRAP_ADMIN_EMAILread from config or env var, fallback toadmin@heimdall.local- Setting
auth.public-registration.enabledinserted as AppSetting record (not just checked)
Task 1: Add SetSettingValueAsync to IAuthDataService and AuthDataService
Files:
- Modify:
src/Heimdall.Application/Services/IAuthDataService.cs:8 - Modify:
src/Heimdall.Infrastructure/Security/AuthDataService.cs:28-36
Interfaces:
-
Consumes:
AppDbContext,AppSettingentity -
Produces:
Task SetSettingValueAsync(string key, string value, CancellationToken ct) -
Step 1: Add method to interface
// In IAuthDataService.cs, after IsRefreshTokenRevokedAsync
Task SetSettingValueAsync(string key, string value, string category, string? description, CancellationToken ct);
- Step 2: Implement in AuthDataService
public async Task SetSettingValueAsync(string key, string value, string category, string? description, CancellationToken ct)
{
var existing = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == key, ct);
if (existing is not null)
{
existing.UpdateValue(value);
}
else
{
_db.AppSettings.Add(new AppSetting(key, value, category, description));
}
await _db.SaveChangesWithRetryAsync(ct: ct);
}
- Step 3: Build to verify
Run: dotnet build src/Heimdall.Infrastructure/
Expected: 0 errors, 0 warnings
- Step 4: Commit
git add src/Heimdall.Application/Services/IAuthDataService.cs src/Heimdall.Infrastructure/Security/AuthDataService.cs
git commit -m "feat: add SetSettingValueAsync to IAuthDataService"
Task 2: Create CanRegister CQRS Query
Files:
- Create:
src/Heimdall.Application/Auth/Queries/CanRegister/CanRegisterQuery.cs - Create:
src/Heimdall.Application/Auth/Queries/CanRegister/CanRegisterHandler.cs
Interfaces:
-
Consumes:
IAuthDataService.GetSettingValueAsync("auth.public-registration.enabled", ct) -
Produces:
CanRegisterQuery : IRequest<bool>,CanRegisterHandler : IRequestHandler<CanRegisterQuery, bool> -
Step 1: Create CanRegisterQuery record
// src/Heimdall.Application/Auth/Queries/CanRegister/CanRegisterQuery.cs
using MediatR;
namespace Heimdall.Application.Auth.Queries.CanRegister;
public record CanRegisterQuery : IRequest<bool>;
- Step 2: Create CanRegisterHandler
// src/Heimdall.Application/Auth/Queries/CanRegister/CanRegisterHandler.cs
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Auth.Queries.CanRegister;
public class CanRegisterHandler : IRequestHandler<CanRegisterQuery, bool>
{
private readonly IAuthDataService _authData;
public CanRegisterHandler(IAuthDataService authData)
{
_authData = authData;
}
public async Task<bool> Handle(CanRegisterQuery request, CancellationToken ct)
{
var setting = await _authData.GetSettingValueAsync("auth.public-registration.enabled", ct);
return string.Equals(setting, "true", StringComparison.OrdinalIgnoreCase);
}
}
- Step 3: Build to verify
Run: dotnet build src/Heimdall.Application/
Expected: 0 errors, 0 warnings
- Step 4: Commit
git add src/Heimdall.Application/Auth/Queries/CanRegister/
git commit -m "feat: add CanRegister CQRS query"
Task 3: Add GET /api/auth/can-register endpoint
Files:
- Modify:
src/Heimdall.Web/Controllers/AuthController.cs:24
Interfaces:
-
Consumes:
IMediator.Send(new CanRegisterQuery(), ct) -
Produces:
GET /api/auth/can-registerreturns{ "canRegister": true | false } -
Step 1: Add endpoint to AuthController
using Heimdall.Application.Auth.Queries.CanRegister; // add to existing usings
// After the Register endpoint (before Login)
/// <summary>Check whether public registration is enabled.</summary>
[AllowAnonymous]
[HttpGet("can-register")]
[ProducesResponseType(typeof(CanRegisterResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> CanRegister(CancellationToken ct)
{
var canRegister = await _mediator.Send(new CanRegisterQuery(), ct);
return Ok(new CanRegisterResponse(canRegister));
}
- Step 2: Add response DTO at bottom of AuthController.cs
internal sealed record CanRegisterResponse(bool CanRegister);
- Step 3: Build to verify
Run: dotnet build src/Heimdall.Web/
Expected: 0 errors, 0 warnings
- Step 4: Commit
git add src/Heimdall.Web/Controllers/AuthController.cs
git commit -m "feat: add GET /api/auth/can-register endpoint"
Task 4: Add CanRegisterAsync() to HeimdallApiClient
Files:
-
Modify:
src/Heimdall.Web/Services/HeimdallApiClient.cs:167(after RegisterAsync) -
Step 1: Add CanRegisterAsync method
// In HeimdallApiClient.cs, after RegisterAsync
public async Task<bool> CanRegisterAsync()
{
var client = _httpFactory.CreateClient("HeimdallApi");
try
{
var response = await client.GetFromJsonAsync<CanRegisterResult>("api/auth/can-register");
return response?.CanRegister ?? false;
}
catch
{
return false; // if API unreachable, assume registration disabled
}
}
// DTO at bottom of the file (alongside other DTOs)
public record CanRegisterResult([property: JsonPropertyName("canRegister")] bool CanRegister);
- Step 2: Build to verify
Run: dotnet build src/Heimdall.Web/
Expected: 0 errors, 0 warnings
- Step 3: Commit
git add src/Heimdall.Web/Services/HeimdallApiClient.cs
git commit -m "feat: add CanRegisterAsync to HeimdallApiClient"
Task 5: Update Login.razor to conditionally show registration link
Files:
-
Modify:
src/Heimdall.Web/Components/Pages/Login.razor:78-84 -
Step 1: Inject HeimdallApiClient in Login.razor
Add to the inject directives (after line 8):
@inject HeimdallApiClient Api
(Already injected at line 3 — just use the existing one)
- Step 2: Add
_canRegisterfield and initialize in OnInitializedAsync
@code {
// ... existing fields
private bool _canRegister;
protected override async Task OnInitializedAsync()
{
// ... existing code (check Auth.IsLoggedIn, returnUrl) ...
// Check if registration is allowed
try
{
_canRegister = await Api.CanRegisterAsync();
}
catch
{
_canRegister = false;
}
}
Note: The existing OnInitialized is synchronous (protected override void OnInitialized). Change to OnInitializedAsync and make the existing logic async-compatible, or call the API from OnInitializedAsync and keep existing sync logic there.
Better approach: add a separate OnInitializedAsync that runs after OnInitialized:
protected override async Task OnInitializedAsync()
{
try
{
_canRegister = await Api.CanRegisterAsync();
}
catch
{
_canRegister = false;
}
}
- Step 3: Conditionally render the register link
@if (_canRegister)
{
<div class="auth-footer">
<p>
Pas encore de compte ?
<a href="/register">Créer un compte</a>
</p>
</div>
}
- Step 4: Build to verify
Run: dotnet build src/Heimdall.Web/
Expected: 0 errors, 0 warnings
- Step 5: Commit
git add src/Heimdall.Web/Components/Pages/Login.razor
git commit -m "feat: hide register link on login page unless registration enabled"
Task 6: Update RegisterHandler default to disabled
Files:
-
Modify:
src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs:71-77 -
Step 1: Invert the registration check
Change lines 71-77 from:
var setting = await _authData.GetSettingValueAsync("auth.public-registration.enabled", ct).ConfigureAwait(false);
if (setting is not null &&
!string.Equals(setting, "true", StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning("Register: Public registration disabled (setting={Value})", setting);
return ServiceResult<AuthResponse>.Failure("Public registration is disabled. Contact an administrator.", 403);
}
To:
var setting = await _authData.GetSettingValueAsync("auth.public-registration.enabled", ct).ConfigureAwait(false);
if (!string.Equals(setting, "true", StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning("Register: Public registration disabled (setting={Value})", setting);
return ServiceResult<AuthResponse>.Failure("Public registration is disabled. Contact an administrator.", 403);
}
Key change: removed setting is not null && condition. Now null = disabled.
- Step 2: Build to verify
Run: dotnet build src/Heimdall.Application/
Expected: 0 errors, 0 warnings
- Step 3: Commit
git add src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs
git commit -m "fix: public registration disabled by default (null setting = disabled)"
Task 7: Add bootstrap logic in Program.cs
Files:
-
Modify:
src/Heimdall.Web/Program.cs:138-165(remove Dev block, add bootstrap) -
Step 1: Remove the entire
if (app.Environment.IsDevelopment())block (lines 138-164) -
Step 2: Add bootstrap after group seeding (line 136)
After await groupDb.SaveChangesWithRetryAsync(); and before the closing brace of the seeding scope, add:
// ── Bootstrap: create admin on first launch ───────────────────
var anyUsers = await userManager.Users.AnyAsync();
if (!anyUsers)
{
var bootstrapEmail = builder.Configuration["Bootstrap:AdminEmail"]
?? Environment.GetEnvironmentVariable("BOOTSTRAP_ADMIN_EMAIL")
?? "admin@heimdall.local";
// Generate a cryptographically random password (24 chars)
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+";
var randomBytes = RandomNumberGenerator.GetBytes(24);
var password = string.Create(24, randomBytes, (span, bytes) =>
{
for (int i = 0; i < 24; i++)
span[i] = chars[bytes[i] % chars.Length];
});
var adminUser = new Heimdall.Domain.Entities.AppUser
{
UserName = bootstrapEmail,
Email = bootstrapEmail,
DisplayName = "Administrateur",
MustChangePassword = true
};
var createResult = await userManager.CreateAsync(adminUser, password);
if (createResult.Succeeded)
{
await userManager.AddToRoleAsync(adminUser, AppRoles.Admin);
// Disable public registration by default
var authData = seedScope.ServiceProvider.GetRequiredService<IAuthDataService>();
await authData.SetSettingValueAsync("auth.public-registration.enabled", "false",
"Auth", "Allow new users to register themselves", ct);
var logger = seedScope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogWarning(
"╔══════════════════════════════════════════════════╗\n" +
"║ HEIMDALL — PREMIER DÉMARRAGE ║\n" +
"╠══════════════════════════════════════════════════╣\n" +
"║ Administrateur créé : {Email,-23} ║\n" +
"║ Mot de passe : {Password,-25} ║\n" +
"║ Rôle : {"Admin",-36} ║\n" +
"║ ║\n" +
"║ ⚠️ Ce mot de passe ne sera plus affiché. ║\n" +
"║ Veuillez le noter et le changer après connexion. ║\n" +
"╚══════════════════════════════════════════════════╝",
bootstrapEmail, password);
}
else
{
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
var logger = seedScope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogCritical("Admin bootstrap failed: {Errors}", errors);
}
}
Note: The ct variable needs to be available. We can use CancellationToken.None or add app.Lifetime.ApplicationStarted if we need a proper token. Since this runs at startup before app.Run(), CancellationToken.None is fine.
Also need to add usings:
using System.Security.Cryptography;(already available in the file context, but check)using Heimdall.Application.Services;(for IAuthDataService)
Let me check what usings exist in Program.cs.
Actually, RandomNumberGenerator is in System.Security.Cryptography which may already be imported. IAuthDataService is in Heimdall.Application.Services.
- Step 3: Build to verify
Run: dotnet build src/Heimdall.Web/
Expected: 0 errors, 0 warnings
- Step 4: Commit
git add src/Heimdall.Web/Program.cs
git commit -m "feat: add first-launch admin bootstrap with random password"
Task 8: Update Register.razor to show message when disabled
Files:
-
Modify:
src/Heimdall.Web/Components/Pages/Register.razor:77-122 -
Step 1: Check registration on page load and show message if disabled
@code {
private string _email = "";
private string _password = "";
private string _displayName = "";
private bool _loading;
private string _errorMessage = "";
private bool _canRegister = true;
protected override async Task OnInitializedAsync()
{
try
{
_canRegister = await Api.CanRegisterAsync();
}
catch
{
_canRegister = false;
}
if (!_canRegister)
{
_errorMessage = "L'inscription publique est désactivée. Contactez un administrateur.";
}
}
- Step 2: Disable the form when registration is not allowed
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
FullWidth="true"
ButtonType="ButtonType.Submit"
Disabled="@_loading || !_canRegister"
Class="auth-submit-btn">
- Step 3: Build to verify
Run: dotnet build src/Heimdall.Web/
Expected: 0 errors, 0 warnings
- Step 4: Commit
git add src/Heimdall.Web/Components/Pages/Register.razor
git commit -m "feat: show message on register page when registration disabled"
Task 9: Update existing tests
Files:
-
Modify:
tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs -
Step 1: Update the "disabled" test to expect null = blocked
The test at line 64-77 Register_when_public_registration_disabled_should_return_403 already sets the mock to return "false" which still works. But add a new test:
[Fact]
public async Task Register_when_setting_absent_should_return_403()
{
_userManager.FindByEmailAsync("user@test.com").Returns((AppUser?)null);
_authData.IsFirstUserAsync(Arg.Any<CancellationToken>()).Returns(true);
_authData.GetSettingValueAsync("auth.public-registration.enabled", Arg.Any<CancellationToken>())
.Returns((string?)null); // setting absent
var result = await _handler.Handle(
new RegisterCommand("user@test.com", "password", "User"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(403);
}
- Step 2: Run tests to verify
Run: dotnet test tests/Heimdall.Application.Tests/ --no-build --filter "FullyQualifiedName~RegisterHandler"
Expected: 5 tests pass (3 existing + 2 new)
- Step 3: Commit
git add tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs
git commit -m "test: add test for absent registration setting = disabled"
Task 10: Integration smoke test
- Step 1: Full build + test run
Run: dotnet build && dotnet test
Expected: 0 errors, all tests pass
- Step 2: Final commit
git add -A && git commit -m "chore: finalize admin bootstrap implementation"
git push origin HEAD