fix: resolve demo admin seeding, Sentry DSN pass-through, and add startup diagnostics

- 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
This commit is contained in:
Arnaud Dartois committed 2026-07-29 14:21:16 +00:00
1 parent 100e230af5
commit afc1b2e032
7 files changed
+579 -7

No files matched your search

+1
View File
@@ -56,3 +56,4 @@ EMAIL__USE_SSL=true
# ntfy push notifications
NTFY__BASE_URL=http://ntfy:80
NTFY__TOKEN=
SENTRY_DSN=${Sentry__Dsn}
+2
View File
@@ -89,6 +89,7 @@ services:
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
# Error tracking
SENTRY_DSN: ${SENTRY_DSN}
Sentry__Dsn: ${Sentry__Dsn}
ports:
- "${WEB_PORT:-5000}:8080"
volumes:
@@ -130,6 +131,7 @@ services:
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
Agent__StateDirectory: /var/lib/heimdall
SENTRY_DSN: ${SENTRY_DSN}
Sentry__Dsn: ${Sentry__Dsn}
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
interval: 30s
+2
View File
@@ -89,6 +89,7 @@ services:
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
# Error tracking
SENTRY_DSN: ${SENTRY_DSN}
Sentry__Dsn: ${Sentry__Dsn}
ports:
- "${WEB_PORT:-5000}:8080"
depends_on:
@@ -134,6 +135,7 @@ services:
Agent__StateDirectory: /var/lib/heimdall
Agent__RegistrationMaxRetries: ${HEIMDALL_REGISTRATION_RETRIES:-5}
SENTRY_DSN: ${SENTRY_DSN}
Sentry__Dsn: ${Sentry__Dsn}
volumes:
- agent_state:/var/lib/heimdall
healthcheck:
@@ -0,0 +1,551 @@
# 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
- `IAuthDataService` must be injectable via DI (it's already in `DependencyInjection.cs` line 115)
- Must use `RandomNumberGenerator` for cryptographically secure random password (not `System.Random`)
- Must log password via `ILogger` before `app.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_EMAIL` read from config or env var, fallback to `admin@heimdall.local`
- Setting `auth.public-registration.enabled` inserted 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`, `AppSetting` entity
- Produces: `Task SetSettingValueAsync(string key, string value, CancellationToken ct)`
- [ ] **Step 1: Add method to interface**
```csharp
// In IAuthDataService.cs, after IsRefreshTokenRevokedAsync
Task SetSettingValueAsync(string key, string value, string category, string? description, CancellationToken ct);
```
- [ ] **Step 2: Implement in AuthDataService**
```csharp
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**
```bash
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**
```csharp
// 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**
```csharp
// 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**
```bash
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-register` returns `{ "canRegister": true | false }`
- [ ] **Step 1: Add endpoint to AuthController**
```csharp
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**
```csharp
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**
```bash
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**
```csharp
// 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**
```bash
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):
```razor
@inject HeimdallApiClient Api
```
(Already injected at line 3 — just use the existing one)
- [ ] **Step 2: Add `_canRegister` field and initialize in OnInitializedAsync**
```razor
@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`:
```razor
protected override async Task OnInitializedAsync()
{
try
{
_canRegister = await Api.CanRegisterAsync();
}
catch
{
_canRegister = false;
}
}
```
- [ ] **Step 3: Conditionally render the register link**
```razor
@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**
```bash
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:
```csharp
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:
```csharp
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**
```bash
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:
```csharp
// ── 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**
```bash
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**
```razor
@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**
```razor
<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**
```bash
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:
```csharp
[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**
```bash
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**
```bash
git add -A && git commit -m "chore: finalize admin bootstrap implementation"
git push origin HEAD
```
@@ -62,6 +62,7 @@ public static class DependencyInjection
// Tests: use ephemeral keys (no persistence, no certificate encryption)
services.AddDataProtection()
.SetApplicationName("Heimdall");
Console.WriteLine("[DIAG] Data Protection: mode=Ephemeral (no key persistence)");
}
else
{
@@ -94,10 +95,12 @@ public static class DependencyInjection
DateTimeOffset.UtcNow.AddDays(-1),
DateTimeOffset.UtcNow.AddYears(10));
File.WriteAllBytes(certFile.FullName, cert.Export(X509ContentType.Pfx, ""));
Console.WriteLine($"[DIAG] Data Protection: new self-signed cert generated at {certFile.FullName}");
}
#pragma warning disable SYSLIB0057 // X509Certificate2(string, string) is obsolete — X509CertificateLoader not available in this SDK
var dpCert = new X509Certificate2(certFile.FullName, "");
Console.WriteLine($"[DIAG] Data Protection: mode=Persisted, keys dir={dpDir.FullName}, cert exists={certFile.Exists}");
#pragma warning restore SYSLIB0057
dpBuilder.ProtectKeysWithCertificate(dpCert);
}
+17 -6
View File
@@ -138,20 +138,21 @@ using (var seedScope = app.Services.CreateScope())
await groupDb.SaveChangesWithRetryAsync();
// Seed demo admin + demo site in Development only
if (app.Environment.IsDevelopment())
if (builder.Configuration.GetValue<bool>("Seed:DemoOnStartup", true))
{
var testAdmin = await userManager.FindByEmailAsync("admin@heimdall.test");
var adminLogin = builder.Configuration.GetValue<string>("Seed:AdminLogin") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN") ?? "admin@heimdall.test";
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
if (testAdmin is null)
{
testAdmin = new Heimdall.Domain.Entities.AppUser
{
UserName = "admin@heimdall.test",
Email = "admin@heimdall.test",
DisplayName = "Admin"
UserName = adminLogin,
Email = adminLogin,
DisplayName = builder.Configuration.GetValue<string>("Seed:AdminDisplayName") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME") ?? "Admin"
};
var adminPassword = builder.Configuration["Seed:AdminPassword"]
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. This is only needed for Development seeding.");
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
await userManager.CreateAsync(testAdmin, adminPassword);
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
}
@@ -291,6 +292,16 @@ public partial class Program {
});
}
// ── Startup diagnostics ────────────────────────────────────────
var sentryStatus = string.IsNullOrEmpty(sentryDsn)
? "NOT CONFIGURED — errors will NOT be reported to GlitchTip"
: "configured (" + sentryDsn[..sentryDsn.IndexOf('@')] + "@...)";
Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}");
Console.WriteLine($"[DIAG] Environment: {builder.Environment.EnvironmentName}");
Console.WriteLine($"[DIAG] Data Protection keys dir: /var/lib/heimdall/dp-keys");
Console.WriteLine($"[DIAG] Demo seeding: {(builder.Configuration.GetValue<bool>("Seed:DemoOnStartup", true) ? "enabled (set Seed:DemoOnStartup=false to disable)" : "disabled")}");
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
+3 -1
View File
@@ -2,7 +2,9 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Heimdall": "Debug",
"Program": "Debug"
}
},
"AllowedHosts": "*",