Merge pull request 'feat(auth): require initial administrator setup' (#134) from feat/first-admin-setup-wizard into main
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 20m26s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 5m0s
Heimdall Gitea / Build and scan server image (push) Successful in 9m16s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m47s
Heimdall Gitea / CI policy (push) Successful in 1s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 20m26s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 5m0s
Heimdall Gitea / Build and scan server image (push) Successful in 9m16s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m47s
Heimdall Gitea / CI policy (push) Successful in 1s
feat(auth): require initial administrator setup
This commit was merged in pull request #134.
This commit is contained in:
commit
546115e2ea
33 files changed
+563
-694
No files matched your search
@@ -1,5 +1,7 @@
|
||||
# Heimdall contributor rules
|
||||
|
||||
- For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance.
|
||||
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, and project names; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes are gone. Do not skip this recipe silently when Docker is unavailable.
|
||||
- Read `todo.md` before changing code. Update its status and acceptance notes in the same PR as each correction or feature. Remove a completed item only after the behavior is verified; keep a short completion entry for traceability.
|
||||
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
|
||||
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
|
||||
@@ -10,3 +12,4 @@
|
||||
|
||||
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
|
||||
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
|
||||
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
|
||||
@@ -257,6 +257,10 @@ décrit la clé publique locale requise pour les mises à jour natives et Docker
|
||||
| **API Key** | Agents (REST) | `X-API-Key: <key>` |
|
||||
| **2FA TOTP** | Sécurité renforcée | `POST /api/auth/2fa/verify` |
|
||||
|
||||
Au premier démarrage, ouvrez `/setup` pour créer le compte administrateur initial. L’assistant
|
||||
n’est disponible que tant que la base ne contient aucun compte, puis redirige vers la connexion.
|
||||
Les créations de compte suivantes sont réservées aux administrateurs depuis la gestion des utilisateurs.
|
||||
|
||||
Compte par défaut (dev) :
|
||||
- `admin@heimdall.test` / `Admin123!Pass` — Admin
|
||||
|
||||
@@ -266,7 +270,8 @@ Compte par défaut (dev) :
|
||||
|
||||
| Méthode | Endpoint | Auth | Description |
|
||||
|---------|----------|------|-------------|
|
||||
| POST | `/api/auth/register` | - | Créer un compte |
|
||||
| GET | `/api/auth/bootstrap-status` | - | Indiquer si la configuration initiale est requise |
|
||||
| POST | `/api/auth/bootstrap-admin` | - (une seule fois, base vide) | Créer le premier administrateur |
|
||||
| POST | `/api/auth/login` | - | Connexion |
|
||||
| POST | `/api/auth/2fa/verify` | Challenge après mot de passe | Vérification TOTP ou code de récupération |
|
||||
| POST | `/api/auth/refresh` | JWT | Rafraîchir token |
|
||||
@@ -276,9 +281,9 @@ Compte par défaut (dev) :
|
||||
| PUT | `/api/sites/{id}` | JWT | Modifier un site |
|
||||
| DELETE | `/api/sites/{id}` | JWT | Supprimer un site |
|
||||
| POST | `/api/sites/{id}/tokens` | JWT | Générer token agent |
|
||||
| GET | `/api/users` | JWT | Lister utilisateurs |
|
||||
| POST | `/api/users` | JWT | Créer utilisateur |
|
||||
| GET | `/api/users/{id}` | JWT | Détail utilisateur |
|
||||
| GET | `/api/users` | Admin | Lister utilisateurs |
|
||||
| POST | `/api/users` | Admin | Créer utilisateur |
|
||||
| GET | `/api/users/{id}` | Admin | Détail utilisateur |
|
||||
| PUT | `/api/users/{id}/roles` | JWT | Modifier rôles |
|
||||
| POST | `/api/users/{id}/lock` | JWT | Verrouiller compte |
|
||||
| POST | `/api/users/{id}/reset-password` | JWT | Reset mot de passe |
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
name: compose-disposable-recipe
|
||||
description: Build and acceptance-test Heimdall changes in a disposable Docker Compose stack, isolated from deployed data and configuration.
|
||||
---
|
||||
|
||||
# Disposable Compose acceptance
|
||||
|
||||
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
|
||||
|
||||
## Safety and isolation
|
||||
|
||||
- Build from the current source with a unique Compose project name. Do not test against the production hostname, database, image volumes, secrets, or credentials.
|
||||
- Put generated `.env` and secret files under a temporary directory outside the repository. Use synthetic test identities and cryptographically random local passwords.
|
||||
- Use an unused loopback host port and Compose-managed volumes whose names include the unique project name. Do not join production or shared networks.
|
||||
- Never use broad Docker cleanup such as `docker system prune`. Remove only the test project with `docker compose -p <unique-name> down --volumes --remove-orphans`.
|
||||
- After cleanup, check that the test project has no containers or volumes. Remove its temporary files and keep logs free of credentials.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port.
|
||||
2. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml up -d --build`.
|
||||
3. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
|
||||
4. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
|
||||
5. Tear down the named project and its volumes in a cleanup path. Verify removal and delete temporary files.
|
||||
|
||||
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: first-admin-bootstrap
|
||||
description: Implement or diagnose Heimdall's mandatory first administrator setup and restrict later account creation to admins.
|
||||
---
|
||||
|
||||
# First administrator setup
|
||||
|
||||
Use this skill when changing account bootstrap, signup, login routing, user creation, or initial deployment guidance.
|
||||
|
||||
- The first account is created through a dedicated setup assistant that is reachable only while the database has no users. Do not seed a production password or print credentials to logs.
|
||||
- Make first-admin creation one-time and race-safe at the server/API boundary. The UI hiding a link is not an authorization control.
|
||||
- After bootstrap, disable anonymous registration regardless of old public-registration settings. Further accounts are created through authenticated, admin-authorized user-management endpoints only.
|
||||
- Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users.
|
||||
- Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup.
|
||||
- For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available).
|
||||
|
||||
Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs.
|
||||
@@ -0,0 +1,8 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
|
||||
public sealed record BootstrapAdminCommand(string Email, string Password, string DisplayName)
|
||||
: IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -0,0 +1,63 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
|
||||
public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly UserManager<AppUser> _users;
|
||||
private readonly IJwtService _jwt;
|
||||
private readonly IRolePermissionService _permissions;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<BootstrapAdminHandler> _logger;
|
||||
|
||||
public BootstrapAdminHandler(IAuthDataService authData, UserManager<AppUser> users, IJwtService jwt,
|
||||
IRolePermissionService permissions, IPasswordBreachChecker breachChecker,
|
||||
ILogger<BootstrapAdminHandler> logger)
|
||||
{
|
||||
_authData = authData;
|
||||
_users = users;
|
||||
_jwt = jwt;
|
||||
_permissions = permissions;
|
||||
_breachChecker = breachChecker;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(BootstrapAdminCommand request, CancellationToken ct)
|
||||
{
|
||||
if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false))
|
||||
return ServiceResult<AuthResponse>.Failure("This password has appeared in a data breach. Please choose a different password.");
|
||||
|
||||
return await _authData.RunFirstAdminBootstrapTransactionAsync(async token =>
|
||||
{
|
||||
if (await _authData.HasAnyUsersAsync(token).ConfigureAwait(false))
|
||||
return ServiceResult<AuthResponse>.Conflict("Initial administrator setup has already been completed.");
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName,
|
||||
EmailConfirmed = true
|
||||
};
|
||||
var created = await _users.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
if (!created.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", created.Errors.Select(e => e.Description)));
|
||||
|
||||
var role = await _users.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
|
||||
if (!role.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", role.Errors.Select(e => e.Description)));
|
||||
|
||||
await _authData.SetSettingValueAsync("auth.public-registration.enabled", "false", "auth",
|
||||
"Public registration is disabled; accounts are created by administrators.", token).ConfigureAwait(false);
|
||||
_logger.LogInformation("Initial administrator account created for {Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users).ConfigureAwait(false);
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
|
||||
public sealed class BootstrapAdminValidator : AbstractValidator<BootstrapAdminCommand>
|
||||
{
|
||||
public BootstrapAdminValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Password).NotEmpty().MinimumLength(12)
|
||||
.WithMessage("Password must be at least 12 characters");
|
||||
}
|
||||
}
|
||||
@@ -1,184 +1,16 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Localization;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Register;
|
||||
|
||||
public class RegisterHandler : IRequestHandler<RegisterCommand, ServiceResult<AuthResponse>>
|
||||
/// <summary>
|
||||
/// Compatibility handler for the retired anonymous registration command.
|
||||
/// User creation is available only through first-admin bootstrap or authorized admin commands.
|
||||
/// </summary>
|
||||
public sealed class RegisterHandler : IRequestHandler<RegisterCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly IEmailService _emailService;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<RegisterHandler> _logger;
|
||||
|
||||
public RegisterHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IAuthDataService authData,
|
||||
IEmailService emailService,
|
||||
IPasswordBreachChecker breachChecker,
|
||||
ILogger<RegisterHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_authData = authData;
|
||||
_emailService = emailService;
|
||||
_breachChecker = breachChecker;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RegisterCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Register attempt: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
|
||||
|
||||
var existingUser = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
if (existingUser is not null)
|
||||
{
|
||||
_logger.LogWarning("Register: Email={Email} already registered", request.Email);
|
||||
return ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
// HaveIBeenPwned check (spec §4.3) — fail-open: never block registration due to
|
||||
// HIBP outage, but reject known-breached passwords.
|
||||
if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false))
|
||||
{
|
||||
_logger.LogWarning("Register: password has been breached (HIBP) for Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure(
|
||||
"This password has appeared in a data breach. Please choose a different password.");
|
||||
}
|
||||
|
||||
var anyUsers = await _authData.IsFirstUserAsync(ct).ConfigureAwait(false);
|
||||
_logger.LogDebug("Register: anyUsers={AnyUsers}", anyUsers);
|
||||
|
||||
if (!anyUsers)
|
||||
{
|
||||
_logger.LogInformation("Register: First user — creating admin Email={Email}", request.Email);
|
||||
var firstUser = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
ServiceResult<AuthResponse>? firstCreateError = null;
|
||||
try
|
||||
{
|
||||
var createResult = await _userManager.CreateAsync(firstUser, request.Password).ConfigureAwait(false);
|
||||
if (!createResult.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
|
||||
_logger.LogError("Register: First user creation failed: {Errors}", errors);
|
||||
firstCreateError = ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException?.Message.IndexOf("unique", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
_logger.LogWarning("Register: Race condition — first user Email={Email} created by another request", request.Email);
|
||||
firstCreateError = ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
if (firstCreateError is not null)
|
||||
return firstCreateError;
|
||||
|
||||
await _userManager.AddToRoleAsync(firstUser, "Admin").ConfigureAwait(false);
|
||||
// Auto-confirm email pour le premier admin (pas de chicken-and-egg)
|
||||
firstUser.EmailConfirmed = true;
|
||||
await _userManager.UpdateAsync(firstUser).ConfigureAwait(false);
|
||||
_logger.LogInformation("Register: First user created and granted Admin role Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(firstUser, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Register: checking PublicRegistrationEnabled setting");
|
||||
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);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Register: Creating user Email={Email}", request.Email);
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
ServiceResult<AuthResponse>? createError = null;
|
||||
try
|
||||
{
|
||||
var result = await _userManager.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogError("Register: User creation failed: {Errors}", errors);
|
||||
createError = ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException?.Message.Contains("unique", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
_logger.LogWarning("Register: Race condition — Email={Email} was created by another request", request.Email);
|
||||
createError = ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
if (createError is not null)
|
||||
return createError;
|
||||
|
||||
_logger.LogDebug("Register: Assigning Viewer role to Email={Email}", request.Email);
|
||||
await _userManager.AddToRoleAsync(user, "Viewer").ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("Register: User created successfully Email={Email}", request.Email);
|
||||
|
||||
// Send confirmation email if SMTP is configured and confirmation is required
|
||||
await TrySendConfirmationEmailAsync(user, ct).ConfigureAwait(false);
|
||||
var confirmationRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
|
||||
if (string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed)
|
||||
return ServiceResult<AuthResponse>.Failure("Account created. Confirm your email before signing in.", 403);
|
||||
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task TrySendConfirmationEmailAsync(AppUser user, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var required = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
|
||||
if (!string.Equals(required, "true", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);
|
||||
var encodedToken = Uri.EscapeDataString(token);
|
||||
var userId = Uri.EscapeDataString(user.Id.ToString());
|
||||
|
||||
var confirmLink = $"heimdall://confirm-email?userId={userId}&token={encodedToken}";
|
||||
var encodedConfirmLink = HtmlEncoder.Default.Encode(confirmLink);
|
||||
var body = $"""
|
||||
<h2>{ServerText.Get("Auth.Register.Title", user.Language)}</h2>
|
||||
<p>{ServerText.Get("Auth.Register.Intro", user.Language)}</p>
|
||||
<p><a href="{encodedConfirmLink}">{ServerText.Get("Auth.Register.Link", user.Language)}</a></p>
|
||||
<p>{ServerText.Get("Auth.Register.Expiry", user.Language)}</p>
|
||||
""";
|
||||
|
||||
await _emailService.SendEmailAsync(user.Email!,
|
||||
ServerText.Get("Auth.Register.Subject", user.Language), body, ct).ConfigureAwait(false);
|
||||
_logger.LogInformation("Register: Confirmation email sent to {Email}", user.Email);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// L'echec de l envoi d email ne bloque pas l inscription
|
||||
_logger.LogWarning(ex, "Register: Failed to send confirmation email to {Email}", user.Email);
|
||||
}
|
||||
}
|
||||
public Task<ServiceResult<AuthResponse>> Handle(RegisterCommand request, CancellationToken cancellationToken)
|
||||
=> Task.FromResult(ServiceResult<AuthResponse>.Failure(
|
||||
"Anonymous registration is disabled. Ask an administrator to create your account.", 403));
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Queries.CanRegister;
|
||||
|
||||
public record CanRegisterQuery : IRequest<bool>;
|
||||
@@ -0,0 +1,16 @@
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Queries;
|
||||
|
||||
public sealed record GetAdminSetupStatusQuery : IRequest<bool>;
|
||||
|
||||
public sealed class GetAdminSetupStatusHandler : IRequestHandler<GetAdminSetupStatusQuery, bool>
|
||||
{
|
||||
private readonly IAuthDataService _authData;
|
||||
|
||||
public GetAdminSetupStatusHandler(IAuthDataService authData) => _authData = authData;
|
||||
|
||||
public async Task<bool> Handle(GetAdminSetupStatusQuery request, CancellationToken cancellationToken)
|
||||
=> !await _authData.HasAnyUsersAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IAuthDataService
|
||||
{
|
||||
Task<string?> GetSettingValueAsync(string key, CancellationToken ct);
|
||||
Task<bool> IsFirstUserAsync(CancellationToken ct);
|
||||
Task<bool> HasAnyUsersAsync(CancellationToken ct);
|
||||
Task<ServiceResult<AuthResponse>> RunFirstAdminBootstrapTransactionAsync(
|
||||
Func<CancellationToken, Task<ServiceResult<AuthResponse>>> createAdmin,
|
||||
CancellationToken ct);
|
||||
Task<bool> IsRefreshTokenRevokedAsync(string tokenHash, CancellationToken ct);
|
||||
Task RevokeRefreshTokenAsync(string refreshToken, Guid userId, CancellationToken ct);
|
||||
Task SetSettingValueAsync(string key, string value, string category, string? description, CancellationToken ct);
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Data;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
@@ -22,11 +27,63 @@ public class AuthDataService : IAuthDataService
|
||||
return setting?.Value;
|
||||
}
|
||||
|
||||
public async Task<bool> IsFirstUserAsync(CancellationToken ct)
|
||||
public async Task<bool> HasAnyUsersAsync(CancellationToken ct)
|
||||
{
|
||||
return await _db.Users.AnyAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> RunFirstAdminBootstrapTransactionAsync(
|
||||
Func<CancellationToken, Task<ServiceResult<AuthResponse>>> createAdmin,
|
||||
CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(createAdmin);
|
||||
|
||||
const int maxAttempts = 3;
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
await using var transaction = await _db.Database
|
||||
.BeginTransactionAsync(IsolationLevel.Serializable, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var result = await createAdmin(ct).ConfigureAwait(false);
|
||||
if (!result.IsSuccess)
|
||||
{
|
||||
await transaction.RollbackAsync(ct).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
await transaction.CommitAsync(ct).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
// EF Core exception: PostgreSQL serializable isolation may reject a concurrent
|
||||
// first-admin setup with SQLSTATE 40001. Retry the whole check/create transaction
|
||||
// so the retry observes the account committed by the competing request.
|
||||
catch (Exception ex) when (IsSerializationFailure(ex) && attempt < maxAttempts - 1)
|
||||
{
|
||||
try { await transaction.RollbackAsync(ct).ConfigureAwait(false); }
|
||||
catch (Exception) { /* A serialization failure already aborted this transaction. */ }
|
||||
_db.ChangeTracker.Clear();
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(25 * (attempt + 1)), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync(ct).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSerializationFailure(Exception exception)
|
||||
{
|
||||
for (Exception? current = exception; current is not null; current = current.InnerException)
|
||||
{
|
||||
if (current is PostgresException { SqlState: PostgresErrorCodes.SerializationFailure })
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> IsRefreshTokenRevokedAsync(string tokenHash, CancellationToken ct)
|
||||
{
|
||||
return await _db.RevokedRefreshTokens
|
||||
|
||||
@@ -76,12 +76,6 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="auth-footer">
|
||||
<p>
|
||||
@Text["LoginPage_NoAccount"]
|
||||
<a href="/register">@Text["LoginPage_CreateAccount"]</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -98,7 +92,7 @@
|
||||
private Task HandleSubmitAsync() =>
|
||||
_requires2fa ? Verify2faAsync() : LoginAsync();
|
||||
|
||||
protected override void OnInitialized()
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
Logger.LogInformation("Login page initialized. User logged in: {IsLoggedIn}", Auth.IsLoggedIn);
|
||||
|
||||
@@ -109,6 +103,16 @@
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (await Api.IsAdminSetupRequiredAsync())
|
||||
{
|
||||
Navigation.NavigateTo("/setup", replace: true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Logger.LogWarning(ex, "Unable to load initial administrator setup status"); }
|
||||
|
||||
// Extract returnUrl from query string (validate local/relative only)
|
||||
var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
|
||||
var query = QueryHelpers.ParseQuery(uri.Query);
|
||||
|
||||
@@ -1,123 +1,6 @@
|
||||
@page "/register"
|
||||
@layout MudBlazorLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject UiText Text
|
||||
@inject AuthState Auth
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
@inject HeimdallAuthStateProvider AuthStateProvider
|
||||
@inject IJSRuntime JsRuntime
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<div class="auth-header">
|
||||
<div class="auth-icon">
|
||||
<i class="fas fa-user-plus"></i>
|
||||
</div>
|
||||
<h1>@Text["RegisterPage_Title"]</h1>
|
||||
<p>@Text["RegisterPage_Subtitle"]</p>
|
||||
</div>
|
||||
|
||||
<div class="auth-form">
|
||||
<form @onsubmit="RegisterAsync">
|
||||
<MudTextField @bind-Value="_displayName"
|
||||
Label="@Text["RegisterPage_DisplayName"]"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mb-4"
|
||||
Required="true"
|
||||
Immediate="true"
|
||||
Autocomplete="name" />
|
||||
<MudTextField @bind-Value="_email"
|
||||
Label="@Text["LoginPage_Email"]"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mb-4"
|
||||
Required="true"
|
||||
Immediate="true"
|
||||
Autocomplete="email" />
|
||||
<MudTextField @bind-Value="_password"
|
||||
Label="@Text["LoginPage_Password"]"
|
||||
Variant="Variant.Outlined"
|
||||
InputType="InputType.Password"
|
||||
Class="mb-4"
|
||||
Required="true"
|
||||
Immediate="true"
|
||||
HelperText="@Text["RegisterPage_PasswordMinimum"]"
|
||||
Autocomplete="new-password" />
|
||||
|
||||
<div class="auth-error">
|
||||
@if (!string.IsNullOrEmpty(_errorMessage))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">@_errorMessage</MudAlert>
|
||||
}
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
FullWidth="true"
|
||||
ButtonType="ButtonType.Submit"
|
||||
Disabled="@_loading"
|
||||
Class="auth-submit-btn">
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Class="mr-2" Color="Color.Inherit" />
|
||||
}
|
||||
@(_loading ? Text["RegisterPage_Loading"] : Text["RegisterPage_Submit"])
|
||||
</MudButton>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="auth-footer">
|
||||
<p>
|
||||
@Text["RegisterPage_AlreadyAccount"]
|
||||
<a href="/login">@Text["LoginPage_SignIn"]</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string _email = "";
|
||||
private string _password = "";
|
||||
private string _displayName = "";
|
||||
private bool _loading;
|
||||
private string _errorMessage = "";
|
||||
|
||||
private async Task RegisterAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.RegisterAsync(_email, _password, _displayName);
|
||||
if (result is null)
|
||||
{
|
||||
_errorMessage = Text["RegisterPage_Failed"];
|
||||
return;
|
||||
}
|
||||
|
||||
// Update Blazor-level auth state
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
|
||||
// Create middleware-level auth cookie
|
||||
var cookieOk = true;
|
||||
if (!string.IsNullOrEmpty(result.AccessToken))
|
||||
{
|
||||
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
|
||||
AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
}
|
||||
|
||||
if (!cookieOk)
|
||||
{
|
||||
_errorMessage = Text["RegisterPage_AutoLoginFailed"];
|
||||
return;
|
||||
}
|
||||
|
||||
Snackbar.Add(Text["RegisterPage_Succeeded"], Severity.Success);
|
||||
Navigation.NavigateTo("/dashboard");
|
||||
}
|
||||
catch {
|
||||
_errorMessage = UiErrors.OperationFailed();
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
protected override void OnInitialized() => Navigation.NavigateTo("/setup", replace: true);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@page "/setup"
|
||||
@layout MudBlazorLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject UiText Text
|
||||
@inject HeimdallAuthStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
@inject IJSRuntime JsRuntime
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<div class="auth-header">
|
||||
<div class="auth-icon"><i class="fas fa-user-shield"></i></div>
|
||||
<h1>@Text["SetupAdmin_Title"]</h1>
|
||||
<p>@Text["SetupAdmin_Subtitle"]</p>
|
||||
</div>
|
||||
@if (_checking)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Color="Color.Primary" />
|
||||
}
|
||||
else if (_unavailable)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">@Text["SetupAdmin_Unavailable"]</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="auth-form">
|
||||
<form @onsubmit="CreateAdminAsync">
|
||||
<MudTextField @bind-Value="_displayName" Label="@Text["SetupAdmin_DisplayName"]"
|
||||
Variant="Variant.Outlined" Class="mb-4" Required="true" Immediate="true" Autocomplete="name" />
|
||||
<MudTextField @bind-Value="_email" Label="@Text["LoginPage_Email"]"
|
||||
Variant="Variant.Outlined" Class="mb-4" Required="true" Immediate="true" Autocomplete="email" />
|
||||
<MudTextField @bind-Value="_password" Label="@Text["LoginPage_Password"]"
|
||||
Variant="Variant.Outlined" InputType="InputType.Password" Class="mb-4"
|
||||
Required="true" Immediate="true" Autocomplete="new-password"
|
||||
HelperText="@Text["SetupAdmin_PasswordMinimum"]" />
|
||||
<MudTextField @bind-Value="_confirmPassword" Label="@Text["SetupAdmin_ConfirmPassword"]"
|
||||
Variant="Variant.Outlined" InputType="InputType.Password" Class="mb-4"
|
||||
Required="true" Immediate="true" Autocomplete="new-password" />
|
||||
@if (!string.IsNullOrEmpty(_error))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_error</MudAlert>
|
||||
}
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true"
|
||||
ButtonType="ButtonType.Submit" Disabled="@_loading" Class="auth-submit-btn">
|
||||
@(_loading ? Text["SetupAdmin_Loading"] : Text["SetupAdmin_Submit"])
|
||||
</MudButton>
|
||||
</form>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string _displayName = "";
|
||||
private string _email = "";
|
||||
private string _password = "";
|
||||
private string _confirmPassword = "";
|
||||
private string _error = "";
|
||||
private bool _checking = true;
|
||||
private bool _unavailable;
|
||||
private bool _loading;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await Api.IsAdminSetupRequiredAsync())
|
||||
{
|
||||
Navigation.NavigateTo("/login", replace: true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_unavailable = true;
|
||||
}
|
||||
finally { _checking = false; }
|
||||
}
|
||||
|
||||
private async Task CreateAdminAsync()
|
||||
{
|
||||
if (_password != _confirmPassword)
|
||||
{
|
||||
_error = Text["SetupAdmin_PasswordMismatch"];
|
||||
return;
|
||||
}
|
||||
_loading = true;
|
||||
_error = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.BootstrapAdminAsync(_email, _password, _displayName);
|
||||
if (result is null)
|
||||
{
|
||||
_error = Text["SetupAdmin_Failed"];
|
||||
return;
|
||||
}
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
var cookieOk = !string.IsNullOrEmpty(result.AccessToken) && await AuthHelper.SignInAsync(
|
||||
JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
if (!cookieOk)
|
||||
{
|
||||
_error = Text["SetupAdmin_AutoLoginFailed"];
|
||||
return;
|
||||
}
|
||||
Navigation.NavigateTo("/dashboard", replace: true);
|
||||
}
|
||||
catch { _error = UiErrors.OperationFailed(); }
|
||||
finally { _password = ""; _confirmPassword = ""; _loading = false; }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Auth.Commands.Register;
|
||||
using Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
using Heimdall.Application.Auth.Commands.Login;
|
||||
using Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
using Heimdall.Application.Auth.Commands.RefreshToken;
|
||||
@@ -11,6 +11,7 @@ using Heimdall.Application.Auth.Commands.ResetPassword;
|
||||
using Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Logout;
|
||||
using Heimdall.Application.Auth.Queries;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
@@ -35,24 +36,28 @@ public class AuthController : ControllerBase
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Register a new user.</summary>
|
||||
/// <summary>Returns whether the mandatory initial administrator setup is required.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
[HttpGet("bootstrap-status")]
|
||||
public async Task<IActionResult> GetBootstrapStatus(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Register attempt for {Email}", request.Email);
|
||||
var command = new RegisterCommand(request.Email, request.Password, request.DisplayName);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
var setupRequired = await _mediator.Send(new GetAdminSetupStatusQuery(), ct);
|
||||
return Ok(new { setupRequired });
|
||||
}
|
||||
|
||||
/// <summary>Create the one-time first administrator account.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("bootstrap-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> BootstrapAdmin([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(
|
||||
new BootstrapAdminCommand(request.Email, request.Password, request.DisplayName), ct);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("User registered successfully: {Email}", request.Email);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
_logger.LogWarning("User registration failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("First administrator setup failed for {Email}: {Error}", request.Email, result.Error);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
|
||||
@@ -4056,4 +4056,15 @@
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
<data name="SetupAdmin_Title" xml:space="preserve"><value>Set up your administrator account</value></data>
|
||||
<data name="SetupAdmin_Subtitle" xml:space="preserve"><value>Create the first account. This one-time setup closes after the administrator is created.</value></data>
|
||||
<data name="SetupAdmin_DisplayName" xml:space="preserve"><value>Name</value></data>
|
||||
<data name="SetupAdmin_ConfirmPassword" xml:space="preserve"><value>Confirm password</value></data>
|
||||
<data name="SetupAdmin_PasswordMinimum" xml:space="preserve"><value>Use at least 12 characters.</value></data>
|
||||
<data name="SetupAdmin_Loading" xml:space="preserve"><value>Creating account…</value></data>
|
||||
<data name="SetupAdmin_Submit" xml:space="preserve"><value>Create administrator</value></data>
|
||||
<data name="SetupAdmin_PasswordMismatch" xml:space="preserve"><value>The passwords do not match.</value></data>
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>Setup could not be completed. The setup may already have been completed; refresh the page and sign in.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>The administrator was created, but automatic sign-in failed. Please sign in.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Setup status could not be loaded. Check the server connection and try again.</value></data>
|
||||
</root>
|
||||
@@ -4056,4 +4056,15 @@
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
<data name="SetupAdmin_Title" xml:space="preserve"><value>Configurer le compte administrateur</value></data>
|
||||
<data name="SetupAdmin_Subtitle" xml:space="preserve"><value>Créez le premier compte. Cet assistant ne sera plus accessible après sa création.</value></data>
|
||||
<data name="SetupAdmin_DisplayName" xml:space="preserve"><value>Nom</value></data>
|
||||
<data name="SetupAdmin_ConfirmPassword" xml:space="preserve"><value>Confirmer le mot de passe</value></data>
|
||||
<data name="SetupAdmin_PasswordMinimum" xml:space="preserve"><value>Utilisez au moins 12 caractères.</value></data>
|
||||
<data name="SetupAdmin_Loading" xml:space="preserve"><value>Création du compte…</value></data>
|
||||
<data name="SetupAdmin_Submit" xml:space="preserve"><value>Créer l’administrateur</value></data>
|
||||
<data name="SetupAdmin_PasswordMismatch" xml:space="preserve"><value>Les mots de passe ne correspondent pas.</value></data>
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>La configuration a échoué. Elle est peut-être déjà terminée ; actualisez la page et connectez-vous.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>L’administrateur a été créé, mais la connexion automatique a échoué. Connectez-vous.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Impossible de vérifier l’état de configuration. Vérifiez la connexion au serveur et réessayez.</value></data>
|
||||
</root>
|
||||
@@ -4056,4 +4056,15 @@
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
<data name="SetupAdmin_Title" xml:space="preserve"><value>Set up your administrator account</value></data>
|
||||
<data name="SetupAdmin_Subtitle" xml:space="preserve"><value>Create the first account. This one-time setup closes after the administrator is created.</value></data>
|
||||
<data name="SetupAdmin_DisplayName" xml:space="preserve"><value>Name</value></data>
|
||||
<data name="SetupAdmin_ConfirmPassword" xml:space="preserve"><value>Confirm password</value></data>
|
||||
<data name="SetupAdmin_PasswordMinimum" xml:space="preserve"><value>Use at least 12 characters.</value></data>
|
||||
<data name="SetupAdmin_Loading" xml:space="preserve"><value>Creating account…</value></data>
|
||||
<data name="SetupAdmin_Submit" xml:space="preserve"><value>Create administrator</value></data>
|
||||
<data name="SetupAdmin_PasswordMismatch" xml:space="preserve"><value>The passwords do not match.</value></data>
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>Setup could not be completed. Refresh and sign in if it was already completed.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>The administrator was created, but automatic sign-in failed. Please sign in.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Setup status could not be loaded. Check the server connection and try again.</value></data>
|
||||
</root>
|
||||
@@ -256,10 +256,17 @@ public class HeimdallApiClient : IDisposable
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<AuthResponse?> RegisterAsync(string email, string password, string displayName)
|
||||
public async Task<bool> IsAdminSetupRequiredAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register",
|
||||
var result = await client.GetFromJsonAsync<BootstrapStatus>("api/auth/bootstrap-status", Json);
|
||||
return result?.SetupRequired ?? throw new InvalidOperationException("Invalid bootstrap status response.");
|
||||
}
|
||||
|
||||
public async Task<AuthResponse?> BootstrapAdminAsync(string email, string password, string displayName)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/bootstrap-admin",
|
||||
new { email, password, displayName });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
|
||||
@@ -267,6 +274,8 @@ public class HeimdallApiClient : IDisposable
|
||||
return result;
|
||||
}
|
||||
|
||||
private sealed record BootstrapStatus(bool SetupRequired);
|
||||
|
||||
public async Task<AuthResponse?> Verify2faAsync(string challengeId, string code)
|
||||
{
|
||||
var client = CreateClient();
|
||||
|
||||
@@ -1,104 +1,19 @@
|
||||
using Heimdall.Application.Auth.Commands.Register;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.Auth;
|
||||
|
||||
public class RegisterHandlerTests
|
||||
public sealed class RegisterHandlerTests
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly IEmailService _emailService;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<RegisterHandler> _logger;
|
||||
private readonly RegisterHandler _handler;
|
||||
|
||||
public RegisterHandlerTests()
|
||||
{
|
||||
var userStore = Substitute.For<IUserStore<AppUser>>();
|
||||
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
|
||||
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
|
||||
_jwtService = Substitute.For<IJwtService>();
|
||||
_rolePermissionService = Substitute.For<IRolePermissionService>();
|
||||
_authData = Substitute.For<IAuthDataService>();
|
||||
_emailService = Substitute.For<IEmailService>();
|
||||
_breachChecker = Substitute.For<IPasswordBreachChecker>();
|
||||
_logger = Substitute.For<ILogger<RegisterHandler>>();
|
||||
_handler = new RegisterHandler(_userManager, _jwtService, _rolePermissionService, _authData, _emailService, _breachChecker, _logger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_with_existing_email_should_return_conflict()
|
||||
public async Task Anonymous_registration_is_rejected()
|
||||
{
|
||||
_userManager.FindByEmailAsync("existing@test.com").Returns(new AppUser());
|
||||
var handler = new RegisterHandler();
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new RegisterCommand("existing@test.com", "password", "Existing"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(409);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_as_first_user_should_create_admin()
|
||||
{
|
||||
_userManager.FindByEmailAsync("first@test.com").Returns((AppUser?)null);
|
||||
_authData.IsFirstUserAsync(Arg.Any<CancellationToken>()).Returns(false);
|
||||
_userManager.CreateAsync(Arg.Any<AppUser>(), "password")
|
||||
.Returns(IdentityResult.Success);
|
||||
_userManager.GetRolesAsync(Arg.Any<AppUser>()).Returns(["Admin"]);
|
||||
_jwtService.GenerateAccessToken(Arg.Any<AppUser>(), Arg.Any<IList<string>>(), Arg.Any<IList<string>>())
|
||||
.Returns(("access-token", DateTime.UtcNow.AddHours(1)));
|
||||
_jwtService.GenerateRefreshToken(Arg.Any<AppUser>()).Returns(("refresh-token", DateTime.UtcNow.AddDays(7)));
|
||||
_rolePermissionService.GetPermissionsForRoles(Arg.Any<IList<string>>()).Returns([]);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new RegisterCommand("first@test.com", "password", "First User"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
await _userManager.Received(1).AddToRoleAsync(Arg.Any<AppUser>(), "Admin");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_when_public_registration_disabled_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("false");
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new RegisterCommand("user@test.com", "password", "User"), CancellationToken.None);
|
||||
var result = await handler.Handle(
|
||||
new RegisterCommand("user@example.test", "LongTestPassword123!", "User"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(403);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_when_public_registration_enabled_should_create_viewer()
|
||||
{
|
||||
_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("true");
|
||||
_userManager.CreateAsync(Arg.Any<AppUser>(), "password")
|
||||
.Returns(IdentityResult.Success);
|
||||
_userManager.GetRolesAsync(Arg.Any<AppUser>()).Returns(["Viewer"]);
|
||||
_jwtService.GenerateAccessToken(Arg.Any<AppUser>(), Arg.Any<IList<string>>(), Arg.Any<IList<string>>())
|
||||
.Returns(("access-token", DateTime.UtcNow.AddHours(1)));
|
||||
_jwtService.GenerateRefreshToken(Arg.Any<AppUser>()).Returns(("refresh-token", DateTime.UtcNow.AddDays(7)));
|
||||
_rolePermissionService.GetPermissionsForRoles(Arg.Any<IList<string>>()).Returns([]);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new RegisterCommand("user@test.com", "password", "User"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
await _userManager.Received(1).AddToRoleAsync(Arg.Any<AppUser>(), "Viewer");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Playwright;
|
||||
using Shouldly;
|
||||
|
||||
@@ -9,7 +11,7 @@ namespace Heimdall.E2E.Tests.Pages;
|
||||
/// <summary>
|
||||
/// Full authentication flow tests driven through the real Blazor UI:
|
||||
/// login success/failure, validation, logout, protected-route redirects
|
||||
/// and public registration (with the feature flag enabled).
|
||||
/// and the one-time administrator setup gate.
|
||||
/// </summary>
|
||||
public class AuthFlowTests : E2ETestBase
|
||||
{
|
||||
@@ -23,7 +25,47 @@ public class AuthFlowTests : E2ETestBase
|
||||
|
||||
(await Page.Locator("h1").TextContentAsync())!.ShouldContain("Heimdall");
|
||||
var regCount = await Page.Locator("a[href='/register']").CountAsync();
|
||||
regCount.ShouldBeGreaterThanOrEqualTo(1);
|
||||
regCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task First_run_requires_setup_and_creates_the_initial_admin()
|
||||
{
|
||||
using (var scope = App.Services.CreateScope())
|
||||
{
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
|
||||
foreach (var user in users.Users.ToList())
|
||||
{
|
||||
var deleted = await users.DeleteAsync(user);
|
||||
deleted.Succeeded.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Page.GotoAsync($"{BaseUrl}/login");
|
||||
await Page.WaitForURLAsync("**/setup**", new() { Timeout = 15000 });
|
||||
await GotoWithCircuitAsync("/setup");
|
||||
await Page.FillAsync("input[autocomplete='name']", "Initial Admin");
|
||||
await Page.FillAsync("input[autocomplete='email']", $"bootstrap-{Guid.NewGuid():N}@heimdall.test");
|
||||
var passwordFields = Page.Locator("input[autocomplete='new-password']");
|
||||
await passwordFields.Nth(0).FillAsync("FirstAdmin!Pass123456");
|
||||
await passwordFields.Nth(1).FillAsync("FirstAdmin!Pass123456");
|
||||
await Page.ClickAsync("button:has-text('Créer l’administrateur')");
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var status = await http.GetFromJsonAsync<BootstrapStatus>("/api/auth/bootstrap-status");
|
||||
status!.SetupRequired.ShouldBeFalse();
|
||||
}
|
||||
finally
|
||||
{
|
||||
using var scope = App.Services.CreateScope();
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
|
||||
foreach (var user in users.Users.ToList())
|
||||
await users.DeleteAsync(user);
|
||||
await Program.SeedAsync(App, App.Configuration);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -89,65 +131,24 @@ public class AuthFlowTests : E2ETestBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_creates_account_when_public_registration_enabled()
|
||||
public async Task Register_route_redirects_to_login_after_initial_setup()
|
||||
{
|
||||
// Enable the public-registration feature flag as admin via the API
|
||||
var token = await LoginViaApiAsync();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var setResp = await http.PostAsJsonAsync("/api/settings", new
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
category = "auth",
|
||||
description = "Public registration enabled",
|
||||
valueType = "bool"
|
||||
});
|
||||
setResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
|
||||
|
||||
var email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test";
|
||||
await GotoWithCircuitAsync("/register");
|
||||
await Page.FillAsync("input[autocomplete='name']", "E2E Register");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
|
||||
await Page.ClickAsync("button:has-text('S’inscrire')");
|
||||
|
||||
// New viewer account lands on the dashboard
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
|
||||
Page.Url.ShouldContain("/dashboard");
|
||||
|
||||
// Clean up: disable the flag again so other tests see the default state
|
||||
var delResp = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
|
||||
delResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
|
||||
await Page.GotoAsync($"{BaseUrl}/register");
|
||||
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_is_blocked_when_public_registration_disabled()
|
||||
public async Task AnonymousRegistrationApi_route_is_not_available()
|
||||
{
|
||||
var email = $"e2e-blocked-{Guid.NewGuid():N}@heimdall.test";
|
||||
|
||||
// The E2E suite shares one Postgres container; a previous test may have
|
||||
// enabled public registration. Ensure the setting is OFF for this test.
|
||||
var token = await LoginViaApiAsync();
|
||||
using (var http = new HttpClient { BaseAddress = new Uri(BaseUrl) })
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var response = await http.PostAsJsonAsync("/api/auth/register", new
|
||||
{
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var del = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
|
||||
del.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
await GotoWithCircuitAsync("/register");
|
||||
await Page.FillAsync("input[autocomplete='name']", "E2E Blocked");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
|
||||
await Page.ClickAsync("button:has-text('S’inscrire')");
|
||||
|
||||
// The UI shows a generic error and stays on the register page when the
|
||||
// backend rejects the signup (public registration disabled).
|
||||
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
|
||||
var errorText = (await Page.Locator(".auth-error").TextContentAsync())!;
|
||||
errorText.ShouldNotBeNullOrWhiteSpace();
|
||||
Page.Url.ShouldContain("/register");
|
||||
email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test",
|
||||
password = "RegisterPass123!",
|
||||
displayName = "E2E Register"
|
||||
});
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
private sealed record BootstrapStatus(bool SetupRequired);
|
||||
}
|
||||
@@ -62,18 +62,18 @@ public class AuthDataServiceTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsFirstUserAsync_NoUsers_ReturnsFalse()
|
||||
public async Task HasAnyUsersAsync_NoUsers_ReturnsFalse()
|
||||
{
|
||||
using var db = CreateDbContext();
|
||||
var service = new AuthDataService(db);
|
||||
|
||||
var result = await service.IsFirstUserAsync(CancellationToken.None);
|
||||
var result = await service.HasAnyUsersAsync(CancellationToken.None);
|
||||
|
||||
result.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsFirstUserAsync_WithUsers_ReturnsTrue()
|
||||
public async Task HasAnyUsersAsync_WithUsers_ReturnsTrue()
|
||||
{
|
||||
using (var db = CreateDbContext())
|
||||
{
|
||||
@@ -84,7 +84,7 @@ public class AuthDataServiceTests : IDisposable
|
||||
using var dbRead = CreateDbContext();
|
||||
var service = new AuthDataService(dbRead);
|
||||
|
||||
var result = await service.IsFirstUserAsync(CancellationToken.None);
|
||||
var result = await service.HasAnyUsersAsync(CancellationToken.None);
|
||||
|
||||
result.ShouldBeTrue();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Shouldly;
|
||||
@@ -11,6 +10,7 @@ public class AuthControllerTests : PostgresTestBase
|
||||
private HttpClient Client => _client ?? throw new InvalidOperationException("Client not initialized");
|
||||
private static readonly SemaphoreSlim _seedLock = new(1, 1);
|
||||
private static bool _seeded;
|
||||
private static string _adminEmail = "";
|
||||
|
||||
public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
@@ -28,11 +28,10 @@ public class AuthControllerTests : PostgresTestBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the public registration setting so non-first-user registrations work.
|
||||
/// Registers the first admin user and creates the AppSetting via the API.
|
||||
/// Creates the first admin through the one-time setup endpoint.
|
||||
/// Runs once per test class (factory is shared).
|
||||
/// </summary>
|
||||
private async Task EnsurePublicRegistrationAsync()
|
||||
private async Task EnsureAdminCreatedAsync()
|
||||
{
|
||||
if (_seeded) return;
|
||||
await _seedLock.WaitAsync();
|
||||
@@ -42,7 +41,8 @@ public class AuthControllerTests : PostgresTestBase
|
||||
|
||||
// First registration is auto-admin (no prior users in the DB)
|
||||
var adminEmail = $"admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var regResponse = await Client.PostAsJsonAsync("api/auth/register", new
|
||||
_adminEmail = adminEmail;
|
||||
var regResponse = await Client.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email = adminEmail,
|
||||
password = "TestPassword123!",
|
||||
@@ -54,21 +54,6 @@ public class AuthControllerTests : PostgresTestBase
|
||||
var authResult = await regResponse.Content.ReadFromJsonAsync<AuthTestResponse>();
|
||||
authResult.ShouldNotBeNull();
|
||||
|
||||
// Use admin token to create the public registration setting
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, "api/settings")
|
||||
{
|
||||
Content = JsonContent.Create(new
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "bool",
|
||||
category = "Auth",
|
||||
description = "Enable public registration"
|
||||
})
|
||||
};
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
|
||||
var settingResponse = await Client.SendAsync(request);
|
||||
|
||||
_seeded = true;
|
||||
}
|
||||
finally
|
||||
@@ -78,9 +63,9 @@ public class AuthControllerTests : PostgresTestBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_ValidRequest_ReturnsOk()
|
||||
public async Task AnonymousRegistrationRoute_IsRemoved()
|
||||
{
|
||||
await EnsurePublicRegistrationAsync();
|
||||
await EnsureAdminCreatedAsync();
|
||||
|
||||
var response = await Client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
@@ -89,25 +74,17 @@ public class AuthControllerTests : PostgresTestBase
|
||||
displayName = "Test User"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_DuplicateEmail_ReturnsConflict()
|
||||
public async Task BootstrapAdmin_AfterSetup_ReturnsConflict()
|
||||
{
|
||||
await EnsurePublicRegistrationAsync();
|
||||
await EnsureAdminCreatedAsync();
|
||||
|
||||
var email = $"dup-{Guid.NewGuid()}@heimdall.test";
|
||||
|
||||
var first = await Client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "User 1"
|
||||
});
|
||||
first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var second = await Client.PostAsJsonAsync("api/auth/register", new
|
||||
var second = await Client.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
@@ -117,18 +94,28 @@ public class AuthControllerTests : PostgresTestBase
|
||||
second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentBootstrapRequests_CreateExactlyOneAdministrator()
|
||||
{
|
||||
var requests = Enumerable.Range(0, 3).Select(index =>
|
||||
Client.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email = $"concurrent-{index}-{Guid.NewGuid():N}@heimdall.test",
|
||||
password = "ConcurrentTest!Password123",
|
||||
displayName = $"Admin {index}"
|
||||
}));
|
||||
|
||||
var responses = await Task.WhenAll(requests);
|
||||
responses.Count(response => response.StatusCode == System.Net.HttpStatusCode.OK).ShouldBe(1);
|
||||
responses.Count(response => response.StatusCode == System.Net.HttpStatusCode.Conflict).ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_ValidCredentials_ReturnsOk()
|
||||
{
|
||||
await EnsurePublicRegistrationAsync();
|
||||
await EnsureAdminCreatedAsync();
|
||||
|
||||
var email = $"login-{Guid.NewGuid()}@heimdall.test";
|
||||
await Client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "Login User"
|
||||
});
|
||||
var email = _adminEmail;
|
||||
|
||||
var response = await Client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
@@ -142,15 +129,9 @@ public class AuthControllerTests : PostgresTestBase
|
||||
[Fact]
|
||||
public async Task Login_InvalidPassword_ReturnsUnauthorized()
|
||||
{
|
||||
await EnsurePublicRegistrationAsync();
|
||||
await EnsureAdminCreatedAsync();
|
||||
|
||||
var email = $"badpwd-{Guid.NewGuid()}@heimdall.test";
|
||||
await Client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "Bad Pwd User"
|
||||
});
|
||||
var email = _adminEmail;
|
||||
|
||||
var response = await Client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
|
||||
@@ -124,10 +124,10 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register endpoint must return 400 for invalid password (too short/minimal requirements).
|
||||
/// The removed anonymous account creation endpoint stays unavailable.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Register_WithWeakPassword_ReturnsBadRequest()
|
||||
public async Task AnonymousRegistrationRoute_IsRemoved()
|
||||
{
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("/api/auth/register", new
|
||||
@@ -137,13 +137,13 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
displayName = "Weak Password User"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
/* ─── Full auth flow test ──────────────────────────────────── */
|
||||
|
||||
/// <summary>
|
||||
/// End-to-end: register admin via test endpoint → get JWT → access protected API.
|
||||
/// End-to-end: bootstrap admin → get JWT → access protected API.
|
||||
/// This validates the complete auth pipeline works end-to-end.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
@@ -153,9 +153,9 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
var password = "E2eTestPwd123!";
|
||||
var client = Factory.CreateClient();
|
||||
|
||||
// Step 1: Register first user (becomes admin automatically) to bootstrap
|
||||
// Step 1: Bootstrap the first admin.
|
||||
var bootEmail = "boot-admin@heimdall.test";
|
||||
var bootResponse = await client.PostAsJsonAsync("/api/auth/register", new
|
||||
var bootResponse = await client.PostAsJsonAsync("/api/auth/bootstrap-admin", new
|
||||
{
|
||||
email = bootEmail,
|
||||
password = "BootAdminPwd123!",
|
||||
@@ -213,16 +213,16 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register a user and verify the endpoint returns a valid AuthResponse.
|
||||
/// Bootstrap the initial user and verify the endpoint returns an AuthResponse.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Register_ReturnsValidAuthResponse()
|
||||
public async Task BootstrapAdmin_ReturnsValidAuthResponse()
|
||||
{
|
||||
var email = $"user-{Guid.NewGuid()}@heimdall.test";
|
||||
var password = "UserRegPwd123!";
|
||||
var client = Factory.CreateClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/auth/register", new
|
||||
var response = await client.PostAsJsonAsync("/api/auth/bootstrap-admin", new
|
||||
{
|
||||
email,
|
||||
password,
|
||||
|
||||
@@ -31,7 +31,6 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
await base.InitializeAsync();
|
||||
_adminToken = null;
|
||||
_viewerToken = null;
|
||||
_seeded = false;
|
||||
}
|
||||
|
||||
/// <summary>Get a shared admin-authenticated HttpClient (lazy, cached token).</summary>
|
||||
@@ -67,14 +66,14 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bootstrap an admin token: the first registered user becomes Admin
|
||||
/// Bootstrap an admin token: the first created user becomes Admin
|
||||
/// automatically. (register-admin itself requires an existing admin token.)
|
||||
/// </summary>
|
||||
private async Task<string> RegisterAdminAsync()
|
||||
{
|
||||
var email = $"admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
var response = await client.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email,
|
||||
password = "AdminPwd123!",
|
||||
@@ -86,55 +85,26 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
|
||||
private async Task<string> RegisterViewerAsync()
|
||||
{
|
||||
// Ensure public registration is enabled (seed via an admin)
|
||||
await EnsurePublicRegistrationAsync();
|
||||
|
||||
var email = $"viewer-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
var admin = await GetAdminClientAsync();
|
||||
var createResponse = await admin.PostAsJsonAsync("api/users", new
|
||||
{
|
||||
email,
|
||||
password = "ViewerPwd123!",
|
||||
displayName = "Settings Viewer"
|
||||
displayName = "Settings Viewer",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
return content.GetProperty("accessToken").GetString()!;
|
||||
}
|
||||
|
||||
private static bool _seeded;
|
||||
private static readonly object _seedLock = new();
|
||||
|
||||
/// <summary>Seeds the public registration setting via admin API (runs once per test class).</summary>
|
||||
private async Task EnsurePublicRegistrationAsync()
|
||||
{
|
||||
if (_seeded) return;
|
||||
lock (_seedLock) { if (_seeded) return; }
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var client = Factory.CreateClient();
|
||||
|
||||
// First registration is auto-admin (no prior users in the DB)
|
||||
var adminEmail = $"seed-admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var regResponse = await client.PostAsJsonAsync("api/auth/register", new
|
||||
var response = await client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
email = adminEmail,
|
||||
password = "AdminPwd123!",
|
||||
displayName = "Seed Admin"
|
||||
email,
|
||||
password = "ViewerPwd123!"
|
||||
});
|
||||
var content = await regResponse.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
var token = content.GetProperty("accessToken").GetString()!;
|
||||
|
||||
// Use admin token to create the public registration setting
|
||||
var adminClient = Factory.CreateClient();
|
||||
adminClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
await adminClient.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "bool",
|
||||
category = "Auth"
|
||||
});
|
||||
|
||||
_seeded = true;
|
||||
response.EnsureSuccessStatusCode();
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
return content.GetProperty("accessToken").GetString()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -12,22 +12,15 @@ public static class TestHelpers
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Register a new admin user and return an authenticated HttpClient.
|
||||
/// Uses the test-only register-admin endpoint.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Bootstrap an admin user and return an authenticated HttpClient.
|
||||
/// First user registered becomes Admin automatically.
|
||||
/// Also enables the auth.public-registration.enabled flag so viewer users can be created.
|
||||
/// </summary>
|
||||
public static async Task<HttpClient> CreateAdminClientAsync(this HeimdallWebApplicationFactory factory)
|
||||
{
|
||||
var email = $"admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = factory.CreateClient();
|
||||
|
||||
// Le premier utilisateur enregistré devient automatiquement Admin
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
var response = await client.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email,
|
||||
password = "TestAdminPwd123!",
|
||||
@@ -41,8 +34,6 @@ public static class TestHelpers
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", token);
|
||||
|
||||
// Activer les feature flags pour les autres tests
|
||||
await EnableSetting(client, "auth.public-registration.enabled", "true");
|
||||
await EnableSetting(client, "auth.admin-registration.enabled", "true");
|
||||
|
||||
return client;
|
||||
@@ -59,27 +50,30 @@ public static class TestHelpers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bootstrap a viewer-authenticated HttpClient (second registered user,
|
||||
/// default role = Viewer). Requires an admin to have been created first
|
||||
/// (which enables public registration).
|
||||
/// Create a Viewer as an admin, then return a Viewer-authenticated client.
|
||||
/// </summary>
|
||||
public static async Task<HttpClient> CreateViewerClientAsync(this HeimdallWebApplicationFactory factory)
|
||||
public static async Task<HttpClient> CreateViewerClientAsync(
|
||||
this HeimdallWebApplicationFactory factory, HttpClient? existingAdminClient = null)
|
||||
{
|
||||
// Bootstrap an admin first: the FIRST registered user becomes Admin.
|
||||
// Without this, the "viewer" below would become the first user (Admin),
|
||||
// which breaks role-based assertions.
|
||||
await CreateAdminClientAsync(factory);
|
||||
var adminClient = existingAdminClient ?? await CreateAdminClientAsync(factory);
|
||||
|
||||
var email = $"viewer-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
var createResponse = await adminClient.PostAsJsonAsync("api/users", new
|
||||
{
|
||||
email,
|
||||
password = "ViewerPwd123!",
|
||||
displayName = "Test Viewer"
|
||||
displayName = "Test Viewer",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var client = factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
email,
|
||||
password = "ViewerPwd123!"
|
||||
});
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(Json);
|
||||
var token = content.GetProperty("accessToken").GetString()!;
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory<Program>
|
||||
|
||||
// Stub HIBP: integration tests must never depend on an external breach-check
|
||||
// API nor on a test password that happens not to be in the HIBP database
|
||||
// (that made `api/auth/register` return 400: "password has appeared in a
|
||||
// (that made the registration command return 400: "password has appeared in a
|
||||
// data breach"). Force "not breached" in tests only — production code path
|
||||
// (HaveIBeenPwnedBreachChecker) is untouched.
|
||||
builder.ConfigureServices(services =>
|
||||
|
||||
@@ -15,7 +15,7 @@ public sealed class CameraAuthorizationScenarios : PostgresTestBase
|
||||
public async Task Direct_camera_grant_is_scoped_and_soft_delete_revokes_api_access()
|
||||
{
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
var viewer = await Factory.CreateViewerClientAsync();
|
||||
var viewer = await Factory.CreateViewerClientAsync(admin);
|
||||
var viewerId = UserIdFromAccessToken(viewer);
|
||||
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
|
||||
@@ -1,80 +1,20 @@
|
||||
using Bunit;
|
||||
using Bunit.TestDoubles;
|
||||
using Heimdall.Web.Components.Pages;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
public class RegisterTests : PageTestBase
|
||||
public sealed class RegisterTests : PageTestBase
|
||||
{
|
||||
private static AuthResponse SuccessResponse() => new(
|
||||
"access-token", "refresh-token", DateTime.UtcNow.AddHours(1), false,
|
||||
new UserInfo(Guid.NewGuid(), "user@heimdall.local", "Nouvel Utilisateur", ["Viewer"]));
|
||||
|
||||
private BunitNavigationManager Navigate()
|
||||
=> Services.GetRequiredService<BunitNavigationManager>();
|
||||
|
||||
[Fact]
|
||||
public void RegisterPage_AfficheFormulaire()
|
||||
public void Retired_register_route_redirects_to_initial_setup()
|
||||
{
|
||||
var cut = RenderPage<Register>();
|
||||
var nav = Services.GetRequiredService<BunitNavigationManager>();
|
||||
|
||||
cut.Markup.ShouldContain("Créer un compte");
|
||||
cut.Markup.ShouldContain("Nom d’affichage");
|
||||
cut.Markup.ShouldContain("Email");
|
||||
cut.Markup.ShouldContain("Mot de passe");
|
||||
cut.Markup.ShouldContain("S’inscrire");
|
||||
cut.FindAll("input").Count.ShouldBe(3);
|
||||
}
|
||||
RenderPage<Register>();
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterPage_EchecInscription_AfficheErreur()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/register", System.Net.HttpStatusCode.BadRequest);
|
||||
var cut = RenderPage<Register>();
|
||||
|
||||
cut.FindAll("input")[0].Input("Nouvel Utilisateur");
|
||||
cut.FindAll("input")[1].Input("user@heimdall.local");
|
||||
cut.FindAll("input")[2].Input("motdepasse-securise");
|
||||
await cut.InvokeAsync(() => cut.Find("form").Submit());
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
cut.Markup.ShouldContain("Erreur lors de l’inscription"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterPage_Succes_NavigueVersDashboard()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/register", SuccessResponse());
|
||||
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
|
||||
|
||||
var nav = Navigate();
|
||||
var cut = RenderPage<Register>();
|
||||
|
||||
cut.FindAll("input")[0].Input("Nouvel Utilisateur");
|
||||
cut.FindAll("input")[1].Input("user@heimdall.local");
|
||||
cut.FindAll("input")[2].Input("motdepasse-securise");
|
||||
await cut.InvokeAsync(() => cut.Find("form").Submit());
|
||||
|
||||
cut.WaitForAssertion(() => nav.Uri.ShouldBe("http://localhost/dashboard"));
|
||||
await AuthProvider.Received(1).NotifyLoginAsync(Arg.Any<AuthResponse>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterPage_Exception_AfficheErreur()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/register",
|
||||
() => throw new InvalidOperationException("boom"));
|
||||
var cut = RenderPage<Register>();
|
||||
|
||||
cut.FindAll("input")[0].Input("Nouvel Utilisateur");
|
||||
cut.FindAll("input")[1].Input("user@heimdall.local");
|
||||
cut.FindAll("input")[2].Input("motdepasse-securise");
|
||||
await cut.InvokeAsync(() => cut.Find("form").Submit());
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Erreur lors de l'opération"));
|
||||
nav.Uri.ShouldBe("http://localhost/setup");
|
||||
}
|
||||
}
|
||||
@@ -720,24 +720,24 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable
|
||||
// ── 2FA ─────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterAsync_WhenSuccess_ReturnsAuthResponse()
|
||||
public async Task BootstrapAdminAsync_WhenSuccess_ReturnsAuthResponse()
|
||||
{
|
||||
var expected = new AuthResponse("access", "refresh", DateTime.UtcNow.AddHours(1), false,
|
||||
new UserInfo(Guid.NewGuid(), "a@b.com", "A", null));
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.RegisterAsync("a@b.com", "pwd", "Display");
|
||||
var result = await _sut.BootstrapAdminAsync("a@b.com", "pwd", "Display");
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("access", result.AccessToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterAsync_WhenFails_ReturnsNull()
|
||||
public async Task BootstrapAdminAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.RegisterAsync("bad", "", "");
|
||||
var result = await _sut.BootstrapAdminAsync("bad", "", "");
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
|
||||
|
||||
## P1 — parcours caméra, agent et données
|
||||
|
||||
- [x] **AUTH-BOOTSTRAP** L’assistant /setup crée le premier compte Admin uniquement lorsque la base est vide; la transaction EF/PostgreSQL sérialisable empêche deux bootstraps concurrents. La page login ouvre l’assistant au premier lancement, l’ancienne route d’inscription redirige et l’API publique /api/auth/register n’existe plus; le handler historique rejette aussi les inscriptions même si l’ancien réglage public est activé. Les comptes suivants passent par /api/users protégé par AdminUsers. Recette Compose jetable du 27 octobre 2026 : base vide→bootstrap Admin→statut fermé→second bootstrap 409→inscription historique 404→création anonyme 401→création Admin 200→connexion 200; après redémarrage, le statut reste fermé. Playwright première installation 1/1, Intégration PostgreSQL 156/156 (dont cinq tests AuthController, AuthFlow + Settings, viewers créés par admin et trois bootstraps simultanés avec un seul succès), Application 518/518, Web 411/411, Infrastructure AuthDataService 7/7; build du projet E2E réussi. Skill dédiée skills/first-admin-bootstrap/ et recette skills/compose-disposable-recipe/. Le déploiement public actuel doit encore être réessayé après correction de la réponse 401 observée sur toutes ses routes, vraisemblablement par l’authentification du reverse proxy.
|
||||
|
||||
- [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`).
|
||||
|
||||
- [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées.
|
||||
|
||||
Reference in new issue
Block a user