fix(identity): harden user lifecycle and permissions
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s

This commit is contained in:
arnaud.dartois committed 2026-11-04 10:26:07 +01:00
1 parent ea5f0b7589
commit 2bf3dbc95b
80 files changed
+1208 -507

No files matched your search

+7 -3
View File
@@ -245,7 +245,7 @@ Interfaces, DTOs, validateurs.
| Service | Méthodes |
|---------|----------|
| `IAuthService` | Register, Login, Verify2fa, RefreshToken, RegisterAdmin |
| `IAuthService` | BootstrapAdmin, Login, Verify2fa, RefreshToken, ChangePassword |
| `ISiteService` | Create, GetById, List, Update, Delete, GenerateToken |
| `IAgentService` | Register, Heartbeat, GetById, ListBySite |
| `IUserService` | List, GetById, Create, Update, AssignRoles, AssignSites, ResetPassword, Lock, Unlock |
@@ -285,11 +285,15 @@ Authentification AVANT d'exposer l'API.
| Méthode | Route | Auth | Status |
|---|---|---|---|
| `POST` | `/api/auth/register` | — | ✅ |
| `GET` | `/api/auth/bootstrap-status` | — | ✅ |
| `POST` | `/api/auth/bootstrap-admin` | — (first account only) | ✅ |
| `POST` | `/api/auth/login` | — | ✅ |
| `POST` | `/api/auth/2fa/verify` | — | ✅ |
| `POST` | `/api/auth/refresh` | — | ✅ |
| `POST` | `/api/auth/register-admin` | Test/Dev only | ✅ |
| `POST` | `/api/auth/register` | Retired (404) | ✅ |
| `POST` | `/api/auth/register-admin` | Retired (404) | ✅ |
| `/api/users/*` | User creation and lifecycle | Admin.Users; surfaced in `/users` UI | ✅ |
| `PUT` | `/api/roles/{name}/permissions` | Admin.Manage; surfaced in `/admin/claims` UI (Admin role fixed) | ✅ |
---
+7 -1
View File
@@ -1 +1,7 @@
{"sdk":{"version":"10.0.402","rollForward":"disable","allowPrerelease":false}}
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature",
"allowPrerelease": false
}
}
+25
View File
@@ -0,0 +1,25 @@
---
name: heimdall-identity
description: Implement and review Heimdall account, password, session, email confirmation, lockout, and two-factor authentication flows built on ASP.NET Core Identity.
---
# Heimdall Identity workflow
Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
- Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success.
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
- Keep the three supported role names seeded by Identity. Seed their default permission claims once using a durable role-claim marker; the Admin permission set stays immutable. Manage Supervisor/Viewer permission claims from `/admin/claims`, then include those persisted claims in login, refresh, cookie, and 2FA auth responses.
- When role membership or role permissions change, rotate every affected user's security stamp and record the acting administrator in the audit log. Protect last-admin demotion, deletion, and lockout based on unlocked Admin accounts.
- Apply `[Collection("E2E")]` on each concrete Playwright test class deriving from `E2ETestBase`; xUnit does not reliably inherit the PostgreSQL fixture attribute from its abstract base.
- Configure Identity options explicitly and review changes to password, unique email, confirmed email, lockout, cookie, token-provider, and Data Protection behavior.
- Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update `todo.md`, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
+8 -5
View File
@@ -13,10 +13,11 @@ internal static class AuthHelper
IJwtService jwtService,
IRolePermissionService rolePermissionService,
UserManager<AppUser> userManager,
DateTime? sessionStarted = null)
DateTime? sessionStarted = null,
CancellationToken ct = default)
{
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
var permissions = rolePermissionService.GetPermissionsForRoles(roles);
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
var (accessToken, expiresAt) = sessionStarted is null
? jwtService.GenerateAccessToken(user, roles, permissions)
@@ -30,12 +31,14 @@ internal static class AuthHelper
refreshToken,
expiresAt,
false,
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles])));
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions])));
}
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager)
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager,
IRolePermissionService rolePermissionService, CancellationToken ct)
{
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles]);
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions]);
}
}
@@ -48,16 +48,23 @@ public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminComman
};
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)));
{
_logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.Errors.Select(e => e.Code)));
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
}
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 _users.DeleteAsync(user).ConfigureAwait(false);
_logger.LogWarning("Identity rejected initial administrator role assignment with codes {Codes}", string.Join(',', role.Errors.Select(e => e.Code)));
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
}
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);
_logger.LogInformation("Initial administrator account created");
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users, ct: token).ConfigureAwait(false);
}, ct).ConfigureAwait(false);
}
}
@@ -45,9 +45,15 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword).ConfigureAwait(false);
if (!result.Succeeded)
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
_logger.LogError("ChangePassword: Failed UserId={UserId}: {Errors}", request.UserId, errors);
return ServiceResult.Failure(errors);
_logger.LogWarning("Identity rejected password change with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
return ServiceResult.Failure("Password change failed");
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
{
_logger.LogError("Identity could not revoke sessions after password change for user {UserId}", request.UserId);
return ServiceResult.Failure("Password changed but active sessions could not be revoked", 500);
}
_logger.LogInformation("ChangePassword: Success UserId={UserId}", request.UserId);
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
public sealed record Complete2faSetupCommand(Guid UserId, string Code) : IRequest<ServiceResult<Complete2faSetupResponse>>;
@@ -0,0 +1,69 @@
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCommand, ServiceResult<Complete2faSetupResponse>>
{
private readonly UserManager<AppUser> _users;
private readonly IApplicationDbContext _db;
private readonly ILogger<Complete2faSetupHandler> _logger;
public Complete2faSetupHandler(UserManager<AppUser> users, IApplicationDbContext db, ILogger<Complete2faSetupHandler> logger)
{
_users = users;
_db = db;
_logger = logger;
}
public async Task<ServiceResult<Complete2faSetupResponse>> Handle(Complete2faSetupCommand request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Code) || request.Code.Trim().Length != 6)
return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
var user = await _users.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
if (user is null) return ServiceResult<Complete2faSetupResponse>.NotFound("User not found");
if (await _users.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
return ServiceResult<Complete2faSetupResponse>.Conflict("Two-factor authentication is already enabled");
var valid = await _users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, request.Code.Trim()).ConfigureAwait(false);
if (!valid) return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
var oldCodes = await _db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync(ct).ConfigureAwait(false);
if (oldCodes.Count > 0) _db.UserRecoveryCodes.RemoveRange(oldCodes);
var codes = RecoveryCodeService.Generate(10);
foreach (var code in codes) _db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code)));
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
var result = await _users.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogWarning("Identity rejected enabling two-factor authentication for user {UserId}", request.UserId);
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to enable two-factor authentication");
}
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
{
await _users.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
_logger.LogError("Identity could not revoke existing sessions after enabling two-factor authentication for user {UserId}", user.Id);
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to complete two-factor setup");
}
return ServiceResult<Complete2faSetupResponse>.Success(new Complete2faSetupResponse(codes, codes.Count));
}
private async Task RemoveRecoveryCodesAsync(Guid userId, CancellationToken ct)
{
var codes = await _db.UserRecoveryCodes.Where(x => x.UserId == userId).ToListAsync(ct).ConfigureAwait(false);
if (codes.Count == 0) return;
_db.UserRecoveryCodes.RemoveRange(codes);
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
}
}
@@ -0,0 +1,8 @@
using FluentValidation;
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
public sealed class Complete2faSetupValidator : AbstractValidator<Complete2faSetupCommand>
{
public Complete2faSetupValidator() => RuleFor(x => x.Code).NotEmpty().Length(6);
}
@@ -44,9 +44,8 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
var result = await _userManager.ConfirmEmailAsync(user, decodedToken).ConfigureAwait(false);
if (!result.Succeeded)
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
_logger.LogWarning("ConfirmEmail: Failed UserId={UserId}: {Errors}", request.UserId, errors);
return ServiceResult.Failure(errors);
_logger.LogWarning("Identity rejected email confirmation with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
return ServiceResult.Failure("Email confirmation failed");
}
_logger.LogInformation("ConfirmEmail: Confirmed successfully UserId={UserId}", request.UserId);
@@ -3,4 +3,4 @@ using MediatR;
namespace Heimdall.Application.Auth.Commands.Disable2fa;
public record Disable2faCommand(Guid UserId) : IRequest<ServiceResult>;
public record Disable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult>;
@@ -31,6 +31,10 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
return ServiceResult.NotFound("User not found");
}
if (string.IsNullOrEmpty(request.CurrentPassword)
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
return ServiceResult.Failure("Current password is incorrect", 400);
var result = await _userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
if (!result.Succeeded)
{
@@ -38,6 +42,9 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
return ServiceResult.Failure("Failed to disable 2FA");
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
// Purger les codes de récupération — ils ne sont plus valables
var codes = await _db.UserRecoveryCodes
.Where(r => r.UserId == request.UserId)
@@ -4,4 +4,4 @@ using MediatR;
namespace Heimdall.Application.Auth.Commands.Enable2fa;
public record Enable2faCommand(Guid UserId) : IRequest<ServiceResult<Enable2faResponse>>;
public record Enable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult<Enable2faResponse>>;
@@ -33,16 +33,18 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
return ServiceResult<Enable2faResponse>.NotFound("User not found");
}
var result = await _userManager.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogError("Enable2fa: Failed UserId={UserId}", request.UserId);
return ServiceResult<Enable2faResponse>.Failure("Failed to enable 2FA");
}
if (string.IsNullOrEmpty(request.CurrentPassword)
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.Failure("Current password is incorrect", 400);
if (await _userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.Conflict("Two-factor authentication is already enabled");
// Generate authenticator key for the QR code setup (l'utilisateur doit scanner le code avec son app)
// Note: key is generated AFTER enabling 2FA so it's available immediately
await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
var reset = await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
if (!reset.Succeeded)
return ServiceResult<Enable2faResponse>.Failure("Unable to initialize authenticator setup");
var key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
if (string.IsNullOrEmpty(key))
{
@@ -50,16 +52,8 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
return ServiceResult<Enable2faResponse>.Failure("Failed to generate 2FA key");
}
// Générer 10 codes de récupération (P0 spec 4.3) — affichés UNE seule fois, stockés hashés
var recoveryCodes = RecoveryCodeService.Generate(10);
foreach (var code in recoveryCodes)
{
_db.UserRecoveryCodes.Add(new UserRecoveryCode(request.UserId, RecoveryCodeService.Hash(code)));
}
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30";
_logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count);
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count));
_logger.LogInformation("Authenticator setup initialized for user {UserId}; confirmation is still required", request.UserId);
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
}
}
@@ -27,13 +27,13 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
public async Task<ServiceResult> Handle(ForgotPasswordCommand request, CancellationToken ct)
{
_logger.LogInformation("ForgotPassword: Email={Email}", request.Email);
_logger.LogInformation("Password reset request received");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
// Ne pas divulguer si l'email existe ou pas
if (user is null || !await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false))
{
_logger.LogInformation("ForgotPassword: No action for Email={Email} (not found or unconfirmed)", request.Email);
_logger.LogInformation("Password reset request completed without an eligible account");
return ServiceResult.Success();
}
@@ -54,7 +54,7 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
await _emailService.SendEmailAsync(request.Email,
ServerText.Get("Auth.ForgotPassword.Subject", language), body, ct).ConfigureAwait(false);
_logger.LogInformation("ForgotPassword: Reset link sent to Email={Email}", request.Email);
_logger.LogInformation("Password reset message sent");
return ServiceResult.Success();
}
}
@@ -43,30 +43,30 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
public async Task<ServiceResult<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
{
_logger.LogInformation("Login attempt: Email={Email}", request.Email);
_logger.LogInformation("Login attempt received");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Login: User not found Email={Email}", request.Email);
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", request.Email, null, "User not found", ct).ConfigureAwait(false);
_logger.LogWarning("Login rejected: account unavailable");
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", null, null, "Authentication failed", ct).ConfigureAwait(false);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
if (await _userManager.IsLockedOutAsync(user))
{
_logger.LogWarning("Login: Account locked Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
_logger.LogWarning("Login rejected: account unavailable");
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
if (result.ResultType == SignInResultType.LockedOut)
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
if (result.ResultType != SignInResultType.Success
&& !(result.ResultType == SignInResultType.RequiresTwoFactor && twoFactorEnabled))
{
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
_logger.LogWarning("Login rejected: credentials invalid");
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
@@ -74,8 +74,8 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
var emailConfirmRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
if (string.Equals(emailConfirmRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed)
{
_logger.LogWarning("Login: Email not confirmed Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403);
_logger.LogWarning("Login rejected: account does not meet current sign-in policy");
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
if (twoFactorEnabled)
@@ -83,10 +83,10 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
var challengeId = await LoginChallengeService.CreateAsync(_db, user, ct);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
string.Empty, string.Empty, DateTime.UtcNow, true,
await AuthHelper.MapUserInfoAsync(user, _userManager), challengeId));
await AuthHelper.MapUserInfoAsync(user, _userManager, _rolePermissionService, ct), challengeId));
}
_logger.LogInformation("Login: Success Email={Email}", request.Email);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
_logger.LogInformation("Login succeeded");
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
}
}
@@ -86,6 +86,6 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
return ServiceResult<AuthResponse>.Unauthorized("Refresh token already consumed");
}
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started).ConfigureAwait(false);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started, ct).ConfigureAwait(false);
}
}
@@ -1,7 +0,0 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
public record RegisterAdminCommand(string Email, string Password, string DisplayName) : IRequest<ServiceResult<AuthResponse>>;
@@ -1,86 +0,0 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
public class RegisterAdminHandler : IRequestHandler<RegisterAdminCommand, ServiceResult<AuthResponse>>
{
private readonly IAuthDataService _authData;
private readonly UserManager<AppUser> _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IPasswordBreachChecker _breachChecker;
private readonly ILogger<RegisterAdminHandler> _logger;
public RegisterAdminHandler(
IAuthDataService authData,
UserManager<AppUser> userManager,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
IPasswordBreachChecker breachChecker,
ILogger<RegisterAdminHandler> logger)
{
_authData = authData;
_userManager = userManager;
_jwtService = jwtService;
_rolePermissionService = rolePermissionService;
_breachChecker = breachChecker;
_logger = logger;
}
public async Task<ServiceResult<AuthResponse>> Handle(RegisterAdminCommand request, CancellationToken ct)
{
_logger.LogInformation("RegisterAdmin: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
// Vérifier le feature flag auth.admin-registration.enabled
var flag = await _authData.GetSettingValueAsync("auth.admin-registration.enabled", ct).ConfigureAwait(false);
if (!string.Equals(flag, "true", StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning("RegisterAdmin: Disabled by feature flag Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Admin registration is disabled", 403);
}
var existing = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
if (existing is not null)
{
_logger.LogWarning("RegisterAdmin: Already exists Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Conflict("Email already registered");
}
// HaveIBeenPwned check (spec §4.3)
if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false))
{
_logger.LogWarning("RegisterAdmin: 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 user = new AppUser
{
UserName = request.Email,
Email = request.Email,
DisplayName = request.DisplayName
};
var createResult = await _userManager.CreateAsync(user, request.Password).ConfigureAwait(false);
if (!createResult.Succeeded)
{
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
_logger.LogWarning("RegisterAdmin: Creation failed: {Errors}", errors);
return ServiceResult<AuthResponse>.Failure(errors);
}
// Assign Admin role
await _userManager.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
user.EmailConfirmed = true;
await _userManager.UpdateAsync(user).ConfigureAwait(false);
_logger.LogInformation("RegisterAdmin: Admin user created Email={Email}", request.Email);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
}
@@ -1,14 +0,0 @@
using FluentValidation;
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
public class RegisterAdminValidator : AbstractValidator<RegisterAdminCommand>
{
public RegisterAdminValidator()
{
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");
}
}
@@ -19,25 +19,31 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
public async Task<ServiceResult> Handle(ResetPasswordCommand request, CancellationToken ct)
{
_logger.LogInformation("ResetPassword: Email={Email}", request.Email);
_logger.LogInformation("Password reset completion requested");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("ResetPassword: User not found Email={Email}", request.Email);
return ServiceResult.NotFound("User not found");
_logger.LogWarning("Password reset completion rejected");
return ServiceResult.Failure("Invalid or expired reset request", 400);
}
var decodedToken = Uri.UnescapeDataString(request.Token);
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword).ConfigureAwait(false);
if (!result.Succeeded)
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
_logger.LogWarning("ResetPassword: Failed Email={Email}: {Errors}", request.Email, errors);
return ServiceResult.Failure(errors);
_logger.LogWarning("Identity rejected password reset with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
return ServiceResult.Failure("Invalid or expired reset request", 400);
}
_logger.LogInformation("ResetPassword: Success Email={Email}", request.Email);
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
{
_logger.LogError("Identity could not revoke sessions after password reset");
return ServiceResult.Failure("Password reset failed", 500);
}
_logger.LogInformation("Password reset completed successfully");
return ServiceResult.Success();
}
}
@@ -64,6 +64,12 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stampUpdate.Succeeded)
{
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
}
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
}
@@ -71,7 +77,7 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
await _userManager.ResetAccessFailedCountAsync(user);
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
}
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
+11 -4
View File
@@ -20,7 +20,8 @@ public record UserInfo(
Guid Id,
string Email,
string DisplayName,
IList<string> Roles);
IList<string> Roles,
IList<string>? Permissions = null);
public record ApiKeyResponse(
Guid Id,
@@ -44,9 +45,15 @@ public record LogoutRequest(string RefreshToken);
public record Enable2faResponse(
string SharedKey,
string QrCodeUri,
IReadOnlyList<string>? RecoveryCodes = null,
int RecoveryCodesRemaining = 0);
string QrCodeUri);
public record Complete2faSetupRequest(string Code);
public record Complete2faSetupResponse(IReadOnlyList<string> RecoveryCodes, int RecoveryCodesRemaining);
public record Disable2faRequest(string CurrentPassword);
public record Enable2faRequest(string CurrentPassword);
public record ConfirmEmailRequest(string UserId, string Token);
public record ForgotPasswordRequest(string Email);
@@ -1,6 +1,14 @@
using Heimdall.Application.Common;
namespace Heimdall.Application.Services;
public interface IRolePermissionService
{
IList<string> GetPermissionsForRoles(IList<string> roles);
Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roles, CancellationToken ct);
Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct);
Task<ServiceResult> SetPermissionsAsync(string role, IReadOnlyCollection<string> permissions,
Guid actorId, CancellationToken ct);
Task EnsureDefaultsAsync(CancellationToken ct);
}
public sealed record RolePermissionInfo(string Name, IReadOnlyList<string> Permissions);
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignRoles;
public record AssignRolesCommand(
Guid UserId,
IList<string> Roles) : IRequest<ServiceResult>;
IList<string> Roles,
Guid? ActorId = null) : IRequest<ServiceResult>;
@@ -35,11 +35,34 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
"Promote another user to Admin first.", 400);
}
await _userManager.RemoveFromRolesAsync(user, currentRoles).ConfigureAwait(false);
await _userManager.AddToRolesAsync(user, command.Roles).ConfigureAwait(false);
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
var rolesToAdd = command.Roles.Except(currentRoles, StringComparer.OrdinalIgnoreCase).ToArray();
var rolesToRemove = currentRoles.Except(command.Roles, StringComparer.OrdinalIgnoreCase).ToArray();
if (rolesToAdd.Length > 0)
{
var added = await _userManager.AddToRolesAsync(user, rolesToAdd).ConfigureAwait(false);
if (!added.Succeeded) return ServiceResult.Failure("Unable to update user roles");
}
if (rolesToRemove.Length > 0)
{
var removed = await _userManager.RemoveFromRolesAsync(user, rolesToRemove).ConfigureAwait(false);
if (!removed.Succeeded)
{
if (rolesToAdd.Length > 0)
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
return ServiceResult.Failure("Unable to update user roles");
}
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
{
if (rolesToRemove.Length > 0)
await _userManager.AddToRolesAsync(user, rolesToRemove).ConfigureAwait(false);
if (rolesToAdd.Length > 0)
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
return ServiceResult.Failure("Unable to revoke existing sessions");
}
await _repository.AddAuditLogAsync(null, "UserRolesUpdated", "User",
await _repository.AddAuditLogAsync(command.ActorId, "UserRolesUpdated", "User",
command.UserId.ToString(),
string.Join(",", currentRoles),
string.Join(",", command.Roles),
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignSites;
public record AssignSitesCommand(
Guid UserId,
IList<Guid> SiteIds) : IRequest<ServiceResult>;
IList<Guid> SiteIds,
Guid? ActorId = null) : IRequest<ServiceResult>;
@@ -24,6 +24,8 @@ public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceRes
return ServiceResult.NotFound("User not found");
await _repository.SetUserSitesAsync(command.UserId, command.SiteIds, ct).ConfigureAwait(false);
await _repository.AddAuditLogAsync(command.ActorId, "UserSitesUpdated", "User", command.UserId.ToString(),
null, string.Join(',', command.SiteIds), ct).ConfigureAwait(false);
return ServiceResult.Success();
}
@@ -8,4 +8,5 @@ public record CreateUserCommand(
string Email,
string Password,
string DisplayName,
IList<string>? Roles) : IRequest<ServiceResult<UserResponse>>;
IList<string>? Roles,
Guid? ActorId = null) : IRequest<ServiceResult<UserResponse>>;
@@ -37,9 +37,14 @@ public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResul
string.Join(", ", result.Errors.Select(e => e.Description)));
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
var assignment = await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
if (!assignment.Succeeded)
{
await _userManager.DeleteAsync(user).ConfigureAwait(false);
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
}
await _repository.AddAuditLogAsync(null, "UserCreated", "User", user.Id.ToString(),
await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(),
null, null, ct);
var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false);
@@ -3,4 +3,4 @@ using MediatR;
namespace Heimdall.Application.Users.Commands.LockUser;
public record LockUserCommand(Guid UserId) : IRequest<ServiceResult>;
public record LockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
@@ -23,10 +23,17 @@ public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
if (user is null)
return ServiceResult.NotFound("User not found");
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
if (roles.Contains("Admin", StringComparer.OrdinalIgnoreCase)
&& await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false) <= 1)
return ServiceResult.Failure("Cannot lock the last administrator account.", 400);
await _repository.AddAuditLogAsync(null, "UserLocked", "User",
var lockout = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
if (!lockout.Succeeded) return ServiceResult.Failure("Unable to lock account");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
await _repository.AddAuditLogAsync(command.ActorId, "UserLocked", "User",
command.UserId.ToString(), null, null, ct);
return ServiceResult.Success();
@@ -4,4 +4,4 @@ using MediatR;
namespace Heimdall.Application.Users.Commands.ResetPassword;
public record ResetPasswordCommand(Guid UserId) : IRequest<ServiceResult<ResetPasswordResponse>>;
public record ResetPasswordCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult<ResetPasswordResponse>>;
@@ -30,13 +30,15 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult<ResetPasswordResponse>.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
user.MustChangePassword = true;
await _userManager.UpdateAsync(user).ConfigureAwait(false);
var updated = await _userManager.UpdateAsync(user).ConfigureAwait(false);
if (!updated.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
await _repository.AddAuditLogAsync(null, "UserPasswordReset", "User",
await _repository.AddAuditLogAsync(command.ActorId, "UserPasswordReset", "User",
command.UserId.ToString(), null, null, ct);
return ServiceResult<ResetPasswordResponse>.Success(
@@ -3,4 +3,4 @@ using MediatR;
namespace Heimdall.Application.Users.Commands.UnlockUser;
public record UnlockUserCommand(Guid UserId) : IRequest<ServiceResult>;
public record UnlockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
@@ -23,10 +23,14 @@ public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResul
if (user is null)
return ServiceResult.NotFound("User not found");
await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
var unlock = await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
if (!unlock.Succeeded) return ServiceResult.Failure("Unable to unlock account");
var reset = await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
if (!reset.Succeeded) return ServiceResult.Failure("Unable to reset failed sign-in count");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
await _repository.AddAuditLogAsync(null, "UserUnlocked", "User",
await _repository.AddAuditLogAsync(command.ActorId, "UserUnlocked", "User",
command.UserId.ToString(), null, null, ct);
return ServiceResult.Success();
@@ -60,6 +60,13 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
return ServiceResult<UserResponse>.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
if (emailChanged)
{
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
return ServiceResult<UserResponse>.Failure("Email updated but existing sessions could not be revoked", 500);
}
if (emailChanged)
{
await _repository.AddAuditLogAsync(command.ActorId, "User.EmailUpdated", "User", user.Id.ToString(),
@@ -62,6 +62,9 @@ public static class DependencyInjection
// Identity
services.AddIdentity<AppUser, AppRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = false; // Heimdall enforces the configurable policy at its auth boundary.
options.Lockout.AllowedForNewUsers = true;
options.Password.RequiredLength = 12;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
@@ -90,8 +90,13 @@ public class UserRepository : IUserRepository
var adminRole = await _db.Roles.FirstOrDefaultAsync(r => r.Name == AppRoles.Admin, ct).ConfigureAwait(false);
if (adminRole is null) return 0;
return await _db.Set<IdentityUserRole<Guid>>()
.CountAsync(ur => ur.RoleId == adminRole.Id, ct);
var now = DateTimeOffset.UtcNow;
return await (from membership in _db.Set<IdentityUserRole<Guid>>()
join user in _db.Users on membership.UserId equals user.Id
where membership.RoleId == adminRole.Id
&& (!user.LockoutEnabled || user.LockoutEnd == null || user.LockoutEnd <= now)
select membership.UserId)
.CountAsync(ct).ConfigureAwait(false);
}
public async Task AddAuditLogAsync(Guid? userId, string action, string resourceType,
@@ -1,20 +1,166 @@
using System.Security.Claims;
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Infrastructure.Security;
public class RolePermissionService : IRolePermissionService
public sealed class RolePermissionService : IRolePermissionService
{
public IList<string> GetPermissionsForRoles(IList<string> roles)
private const string PermissionClaim = "permission";
private const string ConfiguredClaim = "heimdall:permissions-configured";
private readonly RoleManager<AppRole> _roles;
private readonly UserManager<AppUser> _users;
private readonly IUserRepository _userRepository;
public RolePermissionService(RoleManager<AppRole> roles, UserManager<AppUser> users, IUserRepository userRepository)
{
var permissions = new List<string>();
foreach (var role in roles)
_roles = roles;
_users = users;
_userRepository = userRepository;
}
public async Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roleNames, CancellationToken ct)
{
var permissions = new HashSet<string>(StringComparer.Ordinal);
foreach (var name in roleNames)
{
if (AppPermissions.RolePermissions.TryGetValue(role, out var rolePerms))
ct.ThrowIfCancellationRequested();
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
if (role is null) continue;
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
foreach (var claim in claims.Where(c => c.Type == PermissionClaim))
if (claim.Value.Length > 0) permissions.Add(claim.Value);
}
return permissions.Order(StringComparer.Ordinal).ToList();
}
public async Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct)
{
var result = new List<RolePermissionInfo>(AppRoles.All.Length);
foreach (var name in AppRoles.All)
{
ct.ThrowIfCancellationRequested();
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
if (role is null) continue;
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
result.Add(new RolePermissionInfo(name, claims.Where(c => c.Type == PermissionClaim)
.Select(c => c.Value).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()));
}
return result;
}
public async Task<ServiceResult> SetPermissionsAsync(string roleName, IReadOnlyCollection<string> permissions,
Guid actorId, CancellationToken ct)
{
if (!AppRoles.All.Contains(roleName, StringComparer.Ordinal))
return ServiceResult.NotFound("Role not found");
if (roleName == AppRoles.Admin)
return ServiceResult.Failure("The Admin role permissions are fixed to preserve full administrative recovery.", 400);
var allowed = AppPermissions.RolePermissions.Values.SelectMany(p => p).ToHashSet(StringComparer.Ordinal);
var requested = permissions.ToHashSet(StringComparer.Ordinal);
if (requested.Count != permissions.Count || requested.Any(p => !allowed.Contains(p)))
return ServiceResult.Failure("The permission list contains duplicate or unknown permissions.", 400);
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
if (role is null) return ServiceResult.NotFound("Role not found");
var current = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
var currentPermissions = current.Where(c => c.Type == PermissionClaim).Select(c => c.Value)
.ToHashSet(StringComparer.Ordinal);
var additions = requested.Except(currentPermissions, StringComparer.Ordinal).ToArray();
var removals = current.Where(c => c.Type == PermissionClaim && !requested.Contains(c.Value)).ToArray();
if (additions.Length == 0 && removals.Length == 0) return ServiceResult.Success();
if (additions.Length > 0)
{
if (!await AddClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false))
return ServiceResult.Failure("Unable to update role permissions", 500);
}
if (removals.Length > 0)
{
if (!await RemoveClaimsAsync(role, removals).ConfigureAwait(false))
{
permissions.AddRange(rolePerms);
if (additions.Length > 0)
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
return ServiceResult.Failure("Unable to update role permissions", 500);
}
}
return permissions.Distinct().ToList();
var members = await _users.GetUsersInRoleAsync(roleName).ConfigureAwait(false);
foreach (var user in members)
{
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
{
// Earlier stamp rotations only revoke sessions early; restoring role claims
// guarantees subsequent logins still receive the previous permission set.
if (removals.Length > 0) await AddClaimsAsync(role, removals).ConfigureAwait(false);
if (additions.Length > 0)
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
return ServiceResult.Failure("Unable to revoke sessions after changing role permissions", 500);
}
}
await _userRepository.AddAuditLogAsync(actorId, "RolePermissionsUpdated", "Role", roleName,
string.Join(',', currentPermissions.Order(StringComparer.Ordinal)),
string.Join(',', requested.Order(StringComparer.Ordinal)), ct).ConfigureAwait(false);
return ServiceResult.Success();
}
public async Task EnsureDefaultsAsync(CancellationToken ct)
{
foreach (var roleName in AppRoles.All)
{
ct.ThrowIfCancellationRequested();
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
if (role is null) continue;
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
if (claims.Any(c => c.Type == ConfiguredClaim)) continue;
var defaults = AppPermissions.RolePermissions[roleName]
.Select(permission => new Claim(PermissionClaim, permission))
.Where(permission => !claims.Contains(permission)).ToList();
defaults.Add(new Claim(ConfiguredClaim, "true"));
if (!await AddClaimsAsync(role, defaults).ConfigureAwait(false))
throw new InvalidOperationException($"Could not initialize permissions for role {roleName}.");
}
}
private async Task<bool> AddClaimsAsync(AppRole role, IEnumerable<Claim> claims)
{
var added = new List<Claim>();
foreach (var claim in claims)
{
var result = await _roles.AddClaimAsync(role, claim).ConfigureAwait(false);
if (result.Succeeded)
{
added.Add(claim);
continue;
}
foreach (var rollback in added)
await _roles.RemoveClaimAsync(role, rollback).ConfigureAwait(false);
return false;
}
return true;
}
private async Task<bool> RemoveClaimsAsync(AppRole role, IEnumerable<Claim> claims)
{
var removed = new List<Claim>();
foreach (var claim in claims)
{
var result = await _roles.RemoveClaimAsync(role, claim).ConfigureAwait(false);
if (result.Succeeded)
{
removed.Add(claim);
continue;
}
foreach (var rollback in removed)
await _roles.AddClaimAsync(role, rollback).ConfigureAwait(false);
return false;
}
return true;
}
}
@@ -27,6 +27,9 @@ else if (_error)
}
else
{
<MudAlert Severity="Severity.Info" Class="mb-4">
@Text["AdminClaims_EditableInfo"]
</MudAlert>
@foreach (var category in _groupedPermissions)
{
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4" @key="category.Key">
@@ -40,7 +43,20 @@ else
<MudTh>@Text["AdminClaims_Description"]</MudTh>
@foreach (var role in _roles)
{
<MudTh Class="text-center" @key="role.Name">@role.Name</MudTh>
<MudTh Class="text-center" @key="role.Name">
@role.Name
@if (role.Name == "Admin")
{
<MudText Typo="Typo.caption">@Text["AdminClaims_AdminImmutable"]</MudText>
}
else
{
<MudButton Size="Size.Small" Variant="Variant.Text" Disabled="@(_savingRole == role.Name)"
OnClick="@(() => SavePermissions(role.Name))">
@(_savingRole == role.Name ? Text["Saving"] : Text["Save"])
</MudButton>
}
</MudTh>
}
</HeaderContent>
<RowTemplate>
@@ -52,11 +68,11 @@ else
</MudTd>
@foreach (var role in _roles)
{
var hasPermission = role.Permissions.Contains(context.Name);
var hasPermission = _selectedPermissions.GetValueOrDefault(role.Name)?.Contains(context.Name) == true;
<MudTd DataLabel="@role.Name" Class="text-center" @key="role.Name">
<MudIcon Icon="@(hasPermission ? Icons.Material.Filled.Check : Icons.Material.Filled.Remove)"
Color="@(hasPermission ? Color.Success : Color.Default)"
Size="Size.Small" />
<MudCheckBox T="bool" Value="@hasPermission" Disabled="@(role.Name == "Admin" || _savingRole == role.Name)"
ValueChanged="@((bool enabled) => SetPermission(role.Name, context.Name, enabled))"
Color="Color.Primary" />
</MudTd>
}
</RowTemplate>
@@ -70,9 +86,11 @@ else
@code {
private List<PermissionItem>? _permissions;
private List<RoleItem> _roles = [];
private readonly Dictionary<string, HashSet<string>> _selectedPermissions = new(StringComparer.Ordinal);
private Dictionary<string, List<PermissionItem>> _groupedPermissions = new();
private bool _loading = true;
private bool _error;
private string? _savingRole;
protected override async Task OnInitializedAsync()
{
@@ -95,6 +113,9 @@ else
_permissions = await permissionsTask;
_roles = await rolesTask;
_selectedPermissions.Clear();
foreach (var role in _roles)
_selectedPermissions[role.Name] = role.Permissions.ToHashSet(StringComparer.Ordinal);
_groupedPermissions = _permissions
.GroupBy(p => string.IsNullOrEmpty(p.Category) ? "General" : p.Category)
@@ -107,6 +128,31 @@ else
}
finally { _loading = false; }
}
private void SetPermission(string role, string permission, bool enabled)
{
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
if (enabled) selected.Add(permission);
else selected.Remove(permission);
}
private async Task SavePermissions(string role)
{
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
_savingRole = role;
try
{
if (!await Api.UpdateRolePermissionsAsync(role, selected.Order(StringComparer.Ordinal).ToArray()))
{
Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error);
return;
}
Snackbar.Add(Text["AdminClaims_Saved"], Severity.Success);
await LoadData();
}
catch { Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error); }
finally { _savingRole = null; }
}
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
public void Dispose() => Language.LanguageChanged -= OnLanguageChanged;
}
+109 -8
View File
@@ -3,6 +3,7 @@
@layout MainLayout
@implements IDisposable
@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse
@using Complete2faSetupResponse = Heimdall.Application.DTOs.Complete2faSetupResponse
@inject HeimdallApiClient Api
@inject AuthState Auth
@inject UiLanguageService Language
@@ -105,6 +106,12 @@ else if (_profile is not null)
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
@Text["DisableTwoFactor"]
</MudButton>
@if (_confirmDisable2fa)
{
<MudTextField @bind-Value="_disable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
<MudButton Color="Color.Error" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmDisable2fa">@Text["ConfirmDisableTwoFactor"]</MudButton>
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelDisable2fa">@Text["Cancel"]</MudButton>
}
}
else
{
@@ -113,6 +120,12 @@ else if (_profile is not null)
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
@Text["EnableTwoFactor"]
</MudButton>
@if (_confirmEnable2fa)
{
<MudTextField @bind-Value="_enable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="StartEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelEnable2fa">@Text["Cancel"]</MudButton>
}
}
</MudItem>
<MudItem xs="12" sm="6">
@@ -285,7 +298,7 @@ else if (_profile is not null)
}
</MudAlert>
@if (_2faSetup.RecoveryCodes is { Count: > 0 })
@if (_completed2faSetup is { RecoveryCodes.Count: > 0 })
{
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
<MudText Typo="Typo.body2" Class="mb-1">
@@ -295,7 +308,7 @@ else if (_profile is not null)
</MudAlert>
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
<div class="d-flex flex-wrap">
@foreach (var rc in _2faSetup.RecoveryCodes)
@foreach (var rc in _completed2faSetup.RecoveryCodes)
{
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
@rc
@@ -303,12 +316,17 @@ else if (_profile is not null)
}
</div>
</MudPaper>
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label="@Text["RecoveryCodesSaved"]" Class="mb-2" />
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label='@Text["RecoveryCodesSaved"]' Class="mb-2" />
}
else
{
<MudTextField @bind-Value="_authenticatorCode" Label='@Text["AuthenticatorCode"]' Variant="Variant.Outlined" />
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
}
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _show2faDialog = false)">@Text["Close"]</MudButton>
<MudButton Variant="Variant.Text" OnClick="Close2faDialog" Disabled="@(_completed2faSetup is not null && !_recoveryCodesConfirmed)">@Text["Close"]</MudButton>
</DialogActions>
</MudDialog>
@@ -333,8 +351,14 @@ else if (_profile is not null)
// Section 2FA
private bool _toggling2fa;
private bool _confirmDisable2fa;
private string _disable2faPassword = "";
private bool _confirmEnable2fa;
private string _enable2faPassword = "";
private bool _show2faDialog;
private Enable2faResponse? _2faSetup;
private Complete2faSetupResponse? _completed2faSetup;
private string _authenticatorCode = "";
private string? _2faError;
private bool _recoveryCodesConfirmed;
@@ -404,21 +428,55 @@ else if (_profile is not null)
// ─── Section 3: Changer le mot de passe ───────────────────────
private async Task Enable2fa()
private Task Enable2fa()
{
_confirmEnable2fa = true;
return Task.CompletedTask;
}
private void CancelEnable2fa()
{
_confirmEnable2fa = false;
_enable2faPassword = "";
}
private async Task StartEnable2fa()
{
_toggling2fa = true;
_2faError = null;
_2faSetup = null;
_completed2faSetup = null;
_authenticatorCode = "";
_recoveryCodesConfirmed = false;
var currentPassword = _enable2faPassword;
_confirmEnable2fa = false;
try
{
var setup = await Api.Enable2faAsync();
var setup = await Api.Enable2faAsync(currentPassword);
if (setup is null)
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
// ResetAuthenticatorKeyAsync rotates the security stamp. Reissue both
// the Blazor token state and middleware cookie before confirming setup.
var renewedSession = await Api.LoginAsync(_profile!.Email, currentPassword);
if (renewedSession is null || string.IsNullOrEmpty(renewedSession.AccessToken))
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
await AuthProvider.NotifyLoginAsync(renewedSession);
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
_2faSetup = setup;
_show2faDialog = true;
}
@@ -429,17 +487,59 @@ else if (_profile is not null)
}
finally
{
_enable2faPassword = "";
_toggling2fa = false;
await LoadProfile();
}
}
private async Task Disable2fa()
private void Close2faDialog()
{
_show2faDialog = false;
_2faSetup = null;
_completed2faSetup = null;
_authenticatorCode = "";
_recoveryCodesConfirmed = false;
}
private async Task ConfirmEnable2fa()
{
_toggling2fa = true;
try
{
var ok = await Api.Disable2faAsync();
var completed = await Api.ConfirmEnable2faAsync(_authenticatorCode);
if (completed is null)
{
_2faError = "Code invalide ou activation impossible";
return;
}
_completed2faSetup = completed;
_2faError = null;
}
catch { _2faError = Text["OperationFailed"]; }
finally { _toggling2fa = false; await LoadProfile(); }
}
private Task Disable2fa()
{
_confirmDisable2fa = true;
return Task.CompletedTask;
}
private void CancelDisable2fa()
{
_confirmDisable2fa = false;
_disable2faPassword = "";
}
private async Task ConfirmDisable2fa()
{
_toggling2fa = true;
var disabled = false;
try
{
var ok = await Api.Disable2faAsync(_disable2faPassword);
disabled = ok;
if (ok)
{
Snackbar.Add(Text["TwoFactorDisabled"], Severity.Success);
@@ -456,6 +556,7 @@ else if (_profile is not null)
finally
{
_toggling2fa = false;
if (disabled) CancelDisable2fa();
await LoadProfile();
}
}
+27 -36
View File
@@ -4,12 +4,12 @@ using Heimdall.Application.Auth.Commands.Login;
using Heimdall.Application.Auth.Commands.Verify2fa;
using Heimdall.Application.Auth.Commands.RefreshToken;
using Heimdall.Application.Auth.Commands.ChangePassword;
using Heimdall.Application.Auth.Commands.RegisterAdmin;
using Heimdall.Application.Auth.Commands.ConfirmEmail;
using Heimdall.Application.Auth.Commands.ForgotPassword;
using Heimdall.Application.Auth.Commands.ResetPassword;
using Heimdall.Application.Auth.Commands.Enable2fa;
using Heimdall.Application.Auth.Commands.Disable2fa;
using Heimdall.Application.Auth.Commands.Complete2faSetup;
using Heimdall.Application.Auth.Commands.Logout;
using Heimdall.Application.Auth.Queries;
using Heimdall.Application.Common;
@@ -57,7 +57,7 @@ public class AuthController : ControllerBase
if (result.IsSuccess)
return Ok(result.Data);
_logger.LogWarning("First administrator setup failed for {Email}: {Error}", request.Email, result.Error);
_logger.LogWarning("First administrator setup failed with status {StatusCode}", result.StatusCode);
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
@@ -68,17 +68,17 @@ public class AuthController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
{
_logger.LogInformation("Login attempt for {Email}", request.Email);
_logger.LogInformation("Login attempt received");
var command = new LoginCommand(request.Email, request.Password);
var result = await _mediator.Send(command, ct);
if (result.IsSuccess)
{
_logger.LogInformation("Login successful for {Email}", request.Email);
_logger.LogInformation("Login succeeded");
return Ok(result.Data);
}
_logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error);
_logger.LogWarning("Login failed with status {StatusCode}", result.StatusCode);
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
@@ -154,34 +154,12 @@ public class AuthController : ControllerBase
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = "AdminUsers")]
[HttpPost("register-admin")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status403Forbidden)]
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
{
_logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email);
var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName);
var result = await _mediator.Send(command, ct);
if (result.IsSuccess)
{
_logger.LogInformation("Admin user registered successfully: {Email}", request.Email);
return Ok(result.Data);
}
_logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error);
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Enable 2FA for the current user. Returns the shared key and QR code URI for setup.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
[HttpPost("2fa/enable")]
[ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Enable2fa(CancellationToken ct)
public async Task<IActionResult> Enable2fa([FromBody] Enable2faRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
@@ -191,11 +169,11 @@ public class AuthController : ControllerBase
}
_logger.LogInformation("2FA enable attempt for user {UserId}", userId);
var result = await _mediator.Send(new Enable2faCommand(userId), ct);
var result = await _mediator.Send(new Enable2faCommand(userId, request.CurrentPassword), ct);
if (result.IsSuccess)
{
_logger.LogInformation("2FA enabled successfully for user {UserId}", userId);
_logger.LogInformation("Authenticator setup initialized; code confirmation is required");
return Ok(result.Data);
}
@@ -203,12 +181,25 @@ public class AuthController : ControllerBase
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Confirm authenticator setup and return one-time recovery codes.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
[EnableRateLimiting("TwoFactor")]
[HttpPost("2fa/enable/confirm")]
[ProducesResponseType(typeof(Complete2faSetupResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> ConfirmEnable2fa([FromBody] Complete2faSetupRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!Guid.TryParse(userIdClaim, out var userId)) return Unauthorized();
var result = await _mediator.Send(new Complete2faSetupCommand(userId, request.Code), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Disable 2FA for the current user.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
[HttpPost("2fa/disable")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Disable2fa(CancellationToken ct)
public async Task<IActionResult> Disable2fa([FromBody] Disable2faRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
@@ -218,7 +209,7 @@ public class AuthController : ControllerBase
}
_logger.LogInformation("2FA disable attempt for user {UserId}", userId);
var result = await _mediator.Send(new Disable2faCommand(userId), ct);
var result = await _mediator.Send(new Disable2faCommand(userId, request.CurrentPassword), ct);
if (result.IsSuccess)
{
@@ -260,7 +251,7 @@ public class AuthController : ControllerBase
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest request, CancellationToken ct)
{
_logger.LogInformation("ForgotPassword request for {Email}", request.Email);
_logger.LogInformation("Password reset request received");
await _mediator.Send(new ForgotPasswordCommand(request.Email), ct);
return Ok(new { message = "If the email exists, a reset link has been sent." });
}
@@ -272,16 +263,16 @@ public class AuthController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct)
{
_logger.LogInformation("ResetPassword attempt for {Email}", request.Email);
_logger.LogInformation("Password reset completion requested");
var result = await _mediator.Send(new ResetPasswordCommand(request.Email, request.Token, request.NewPassword), ct);
if (result.IsSuccess)
{
_logger.LogInformation("Password reset successfully for {Email}", request.Email);
_logger.LogInformation("Password reset completed successfully");
return Ok(new { message = "Password reset successfully" });
}
_logger.LogWarning("Password reset failed for {Email}: {Error}", request.Email, result.Error);
_logger.LogWarning("Password reset failed with status {StatusCode}", result.StatusCode);
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
@@ -1,4 +1,6 @@
using Heimdall.Infrastructure.Security;
using Heimdall.Application.Services;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
@@ -10,6 +12,7 @@ public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
/// <summary>Response DTO for a list of roles.</summary>
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
public record UpdateRolePermissionsRequest(IReadOnlyList<string> Permissions);
[ApiController]
[Route("api/roles")]
@@ -17,16 +20,18 @@ public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
[EnableRateLimiting("Api")]
public class RolesController : ControllerBase
{
private readonly IRolePermissionService _permissions;
public RolesController(IRolePermissionService permissions) => _permissions = permissions;
/// <summary>Returns all roles with their associated permissions.</summary>
[HttpGet]
[ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult List()
public async Task<IActionResult> List(CancellationToken ct)
{
var roles = AppPermissions.RolePermissions
.Select(kvp => new RoleResponse(kvp.Key, kvp.Value))
.ToList();
var roles = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
.Select(role => new RoleResponse(role.Name, role.Permissions)).ToList();
return Ok(new RolesListResponse(roles));
}
@@ -35,11 +40,26 @@ public class RolesController : ControllerBase
[ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult GetByName(string name)
public async Task<IActionResult> GetByName(string name, CancellationToken ct)
{
if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions))
var role = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase));
if (role is null)
return NotFound(new { error = $"Role '{name}' not found" });
return Ok(new RoleResponse(role.Name, role.Permissions));
}
return Ok(new RoleResponse(name, permissions));
/// <summary>Replace the permission set for a non-Admin role.</summary>
[HttpPut("{name}/permissions")]
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UpdatePermissions(string name,
[FromBody] UpdateRolePermissionsRequest request, CancellationToken ct)
{
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _permissions.SetPermissionsAsync(name, request.Permissions, actorId, ct)
.ConfigureAwait(false);
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -103,7 +103,8 @@ public class UsersController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
{
var command = new CreateUserCommand(request.Email, request.Password, request.DisplayName, request.Roles);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var command = new CreateUserCommand(request.Email, request.Password, request.DisplayName, request.Roles, actorId);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok(result.Data)
@@ -138,7 +139,8 @@ public class UsersController : ControllerBase
public async Task<IActionResult> AssignRoles(
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
{
var result = await _mediator.Send(new AssignRolesCommand(id, request.Roles), ct);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new AssignRolesCommand(id, request.Roles, actorId), ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
@@ -152,7 +154,8 @@ public class UsersController : ControllerBase
public async Task<IActionResult> AssignSites(
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
{
var result = await _mediator.Send(new AssignSitesCommand(id, request.SiteIds), ct);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new AssignSitesCommand(id, request.SiteIds, actorId), ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
@@ -165,7 +168,8 @@ public class UsersController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
{
var result = await _mediator.Send(new ResetPasswordCommand(id), ct);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new ResetPasswordCommand(id, actorId), ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
@@ -197,7 +201,8 @@ public class UsersController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
{
var result = await _mediator.Send(new LockUserCommand(id), ct);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new LockUserCommand(id, actorId), ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
@@ -210,7 +215,8 @@ public class UsersController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
{
var result = await _mediator.Send(new UnlockUserCommand(id), ct);
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new UnlockUserCommand(id, actorId), ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
@@ -549,6 +549,9 @@
<data name="TwoFactorKey">
<value>Key:</value>
</data>
<data name="AuthenticatorCode"><value>Authenticator app code</value></data>
<data name="ConfirmTwoFactor"><value>Confirm setup</value></data>
<data name="ConfirmDisableTwoFactor"><value>Confirm disable</value></data>
<data name="SetupLink">
<value>Setup link:</value>
</data>
@@ -4067,4 +4070,9 @@
<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>
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Edit Supervisor and Viewer permissions, then save each role. Changes revoke their active sessions.</value></data>
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixed</value></data>
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Could not save the role permissions.</value></data>
<data name="AdminClaims_Saved" xml:space="preserve"><value>Role permissions saved. Affected users must sign in again.</value></data>
<data name="Saving" xml:space="preserve"><value>Saving…</value></data>
</root>
@@ -549,6 +549,9 @@
<data name="TwoFactorKey">
<value>Clé :</value>
</data>
<data name="AuthenticatorCode"><value>Code de l’application d’authentification</value></data>
<data name="ConfirmTwoFactor"><value>Confirmer l’activation</value></data>
<data name="ConfirmDisableTwoFactor"><value>Confirmer la désactivation</value></data>
<data name="SetupLink">
<value>Lien de configuration :</value>
</data>
@@ -4067,4 +4070,9 @@
<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>
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Modifiez les droits de Supervisor et Viewer, puis enregistrez chaque rôle. Les changements révoquent leurs sessions actives.</value></data>
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixe</value></data>
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Impossible d’enregistrer les droits du rôle.</value></data>
<data name="AdminClaims_Saved" xml:space="preserve"><value>Droits du rôle enregistrés. Les utilisateurs concernés devront se reconnecter.</value></data>
<data name="Saving" xml:space="preserve"><value>Enregistrement…</value></data>
</root>
@@ -549,6 +549,9 @@
<data name="TwoFactorKey">
<value>Clé :</value>
</data>
<data name="AuthenticatorCode"><value>Authenticator app code</value></data>
<data name="ConfirmTwoFactor"><value>Confirm setup</value></data>
<data name="ConfirmDisableTwoFactor"><value>Confirm disable</value></data>
<data name="SetupLink">
<value>Lien de configuration :</value>
</data>
@@ -4067,4 +4070,9 @@
<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>
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Edit Supervisor and Viewer permissions, then save each role. Changes revoke their active sessions.</value></data>
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixed</value></data>
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Could not save the role permissions.</value></data>
<data name="AdminClaims_Saved" xml:space="preserve"><value>Role permissions saved. Affected users must sign in again.</value></data>
<data name="Saving" xml:space="preserve"><value>Saving…</value></data>
</root>
+12 -4
View File
@@ -215,6 +215,8 @@ public partial class Program
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
await SeedRolesAsync(roleManager);
await seedScope.ServiceProvider.GetRequiredService<IRolePermissionService>()
.EnsureDefaultsAsync(CancellationToken.None);
await SeedGroupsAsync(groupDb);
var existingKeys = await GetExistingSettingKeysAsync(groupDb);
await SeedStorageSettingsAsync(groupDb, existingKeys);
@@ -403,8 +405,15 @@ public partial class Program
var adminPassword = configuration["Seed:AdminPassword"]
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
?? 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);
var created = await userManager.CreateAsync(testAdmin, adminPassword);
if (!created.Succeeded)
throw new InvalidOperationException("Configured demo administrator could not be created: " + string.Join(',', created.Errors.Select(e => e.Code)));
var assigned = await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
if (!assigned.Succeeded)
{
await userManager.DeleteAsync(testAdmin);
throw new InvalidOperationException("Configured demo administrator role could not be assigned: " + string.Join(',', assigned.Errors.Select(e => e.Code)));
}
}
var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
@@ -715,8 +724,7 @@ public partial class Program
foreach (var permission in allPermissions)
options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission));
// Policy used by AuthController (register-admin, user management).
// Not a permission claim but a role-based gate for admin-only actions.
// Legacy role-based policy retained for administrative endpoints.
options.AddPolicy("AdminUsers", policy => policy.RequireRole(AppRoles.Admin));
});
}
+9 -8
View File
@@ -36,9 +36,10 @@ public class AuthState
AuthCookie = null;
// Resolve permissions from roles (same mapping as JWT + cookie auth)
Permissions = response.User?.Roles?
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
.ToHashSet() ?? new HashSet<string>();
Permissions = response.User?.Permissions?.ToHashSet(StringComparer.Ordinal)
?? response.User?.Roles?.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
.ToHashSet(StringComparer.Ordinal)
?? new HashSet<string>(StringComparer.Ordinal);
}
/// <summary>
@@ -61,11 +62,10 @@ public class AuthState
AccessToken = null;
RefreshToken = null;
User = new UserInfo(id, email, displayName, roles);
var permissions = principal.FindAll("permission").Select(c => c.Value).Distinct(StringComparer.Ordinal).ToList();
User = new UserInfo(id, email, displayName, roles, permissions);
Permissions = roles
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
.ToHashSet();
Permissions = permissions.ToHashSet(StringComparer.Ordinal);
}
public void Logout()
@@ -92,7 +92,8 @@ public record UserInfo(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("email")] string Email,
[property: JsonPropertyName("displayName")] string DisplayName,
[property: JsonPropertyName("roles")] IList<string>? Roles);
[property: JsonPropertyName("roles")] IList<string>? Roles,
[property: JsonPropertyName("permissions")] IList<string>? Permissions = null);
public record SiteItem(
[property: JsonPropertyName("id")] Guid Id,
+20 -4
View File
@@ -159,6 +159,14 @@ public class HeimdallApiClient : IDisposable
return response?.Roles.ToList() ?? [];
}
public async Task<bool> UpdateRolePermissionsAsync(string role, IReadOnlyList<string> permissions)
{
var client = CreateClient();
var response = await client.PutAsJsonAsync($"api/roles/{Uri.EscapeDataString(role)}/permissions",
new { permissions }, Json);
return response.IsSuccessStatusCode;
}
// ─── Permissions ──────────────────────────────────────────────
public async Task<List<PermissionItem>> GetPermissionsAsync()
@@ -286,18 +294,26 @@ public class HeimdallApiClient : IDisposable
return result;
}
public async Task<Enable2faResponse?> Enable2faAsync()
public async Task<Enable2faResponse?> Enable2faAsync(string currentPassword)
{
var client = CreateClient();
var response = await client.PostAsync("api/auth/2fa/enable", null);
var response = await client.PostAsJsonAsync("api/auth/2fa/enable", new Enable2faRequest(currentPassword));
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
}
public async Task<bool> Disable2faAsync()
public async Task<Complete2faSetupResponse?> ConfirmEnable2faAsync(string code)
{
var client = CreateClient();
var response = await client.PostAsync("api/auth/2fa/disable", null);
var response = await client.PostAsJsonAsync("api/auth/2fa/enable/confirm", new Complete2faSetupRequest(code));
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<Complete2faSetupResponse>(Json);
}
public async Task<bool> Disable2faAsync(string currentPassword)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/disable", new Disable2faRequest(currentPassword));
return response.IsSuccessStatusCode;
}
@@ -154,9 +154,10 @@ public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStatePr
foreach (var role in response.User.Roles ?? [])
claims.Add(new Claim(ClaimTypes.Role, role));
// Map roles → permissions via the AppPermissions dictionary (same as AuthService)
var permissions = response.User.Roles?
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
// Permissions arrive with the signed auth response so the UI and API use
// the same persisted Identity role claims.
var permissions = response.User.Permissions ?? response.User.Roles?
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var defaults) ? defaults : [])
.ToList() ?? [];
foreach (var permission in permissions)
@@ -31,6 +31,7 @@ public class ChangePasswordHandlerTests
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.ChangePasswordAsync(user, "old-password", "new-password")
.Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(user).Returns(IdentityResult.Success);
var result = await _handler.Handle(
new ChangePasswordCommand(user.Id, "old-password", "new-password"), CancellationToken.None);
@@ -63,6 +64,6 @@ public class ChangePasswordHandlerTests
new ChangePasswordCommand(user.Id, "wrong", "new"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.Error!.ShouldContain("Incorrect password");
result.Error.ShouldBe("Password change failed");
}
}
@@ -0,0 +1,32 @@
using Heimdall.Application.Auth.Commands.Disable2fa;
using Heimdall.Application.Common;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Auth;
public sealed class Disable2faHandlerTests
{
[Fact]
public async Task Wrong_current_password_does_not_disable_two_factor()
{
var store = Substitute.For<IUserStore<AppUser>>();
var users = Substitute.For<UserManager<AppUser>>(store,
Microsoft.Extensions.Options.Options.Create(new IdentityOptions()), null!, null!, null!, null!, null!, null!, null!);
var db = Substitute.For<IApplicationDbContext>();
db.UserRecoveryCodes.Returns(MockDbSetHelper.CreateFor<UserRecoveryCode>());
var user = new AppUser { Id = Guid.NewGuid() };
users.FindByIdAsync(user.Id.ToString()).Returns(user);
users.CheckPasswordAsync(user, "wrong").Returns(false);
var handler = new Disable2faHandler(users, db, Substitute.For<ILogger<Disable2faHandler>>());
var result = await handler.Handle(new Disable2faCommand(user.Id, "wrong"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
await users.DidNotReceive().SetTwoFactorEnabledAsync(user, false);
}
}
@@ -30,38 +30,21 @@ public class Enable2faHandlerTests
}
[Fact]
public async Task Enable2fa_should_generate_10_recovery_codes_and_store_hashes()
public async Task Enable2fa_should_initialize_key_without_activating_or_issuing_recovery_codes()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.SetTwoFactorEnabledAsync(user, true)
.Returns(IdentityResult.Success);
_userManager.CheckPasswordAsync(user, "Current-password-123!").Returns(true);
_userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityResult.Success);
_userManager.GetAuthenticatorKeyAsync(user).Returns("ABCDEF123456");
var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None);
var result = await _handler.Handle(new Enable2faCommand(user.Id, "Current-password-123!"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data!.RecoveryCodes.ShouldNotBeNull();
result.Data.RecoveryCodes!.Count.ShouldBe(10);
result.Data.RecoveryCodesRemaining.ShouldBe(10);
// Stockage hashé : chaque hash en base ≠ code en clair, longueur SHA-256 hex (64)
_recoveryCodes.Count().ShouldBe(10);
foreach (var stored in _recoveryCodes)
{
stored.UserId.ShouldBe(user.Id);
stored.CodeHash.ShouldNotBeNull();
stored.CodeHash.Length.ShouldBe(64);
result.Data.RecoveryCodes.ShouldNotContain(stored.CodeHash);
}
// Les hash correspondent bien aux codes retournés
foreach (var code in result.Data.RecoveryCodes)
{
_recoveryCodes.ShouldContain(r => r.CodeHash == RecoveryCodeService.Hash(code));
}
result.Data!.SharedKey.ShouldBe("ABCDEF123456");
_recoveryCodes.Count().ShouldBe(0);
await _userManager.DidNotReceive().SetTwoFactorEnabledAsync(user, true);
}
[Fact]
@@ -69,38 +52,40 @@ public class Enable2faHandlerTests
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(new Enable2faCommand(Guid.NewGuid()), CancellationToken.None);
var result = await _handler.Handle(new Enable2faCommand(Guid.NewGuid(), "Current-password-123!"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
_recoveryCodes.Count().ShouldBe(0);
}
[Fact]
public async Task Enable2fa_with_wrong_current_password_should_not_rotate_authenticator_key()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.CheckPasswordAsync(user, "wrong").Returns(false);
var result = await _handler.Handle(new Enable2faCommand(user.Id, "wrong"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
await _userManager.DidNotReceive().ResetAuthenticatorKeyAsync(user);
}
[Fact]
public async Task Enable2fa_when_identity_fails_should_return_failure()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.SetTwoFactorEnabledAsync(user, true)
_userManager.CheckPasswordAsync(user, "Current-password-123!").Returns(true);
_userManager.ResetAuthenticatorKeyAsync(user)
.Returns(IdentityResult.Failed(new IdentityError { Description = "boom" }));
var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None);
var result = await _handler.Handle(new Enable2faCommand(user.Id, "Current-password-123!"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
_recoveryCodes.Count().ShouldBe(0);
}
[Fact]
public async Task Enable2fa_generated_codes_are_unique()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.SetTwoFactorEnabledAsync(user, true).Returns(IdentityResult.Success);
_userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityResult.Success);
_userManager.GetAuthenticatorKeyAsync(user).Returns("ABCDEF123456");
var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None);
result.Data!.RecoveryCodes!.Distinct().Count().ShouldBe(10);
}
}
@@ -57,7 +57,8 @@ public class LoginHandlerTests
_jwtService.GenerateAccessToken(user, Arg.Any<IList<string>>(), Arg.Any<IList<string>>())
.Returns(("access-token", DateTime.UtcNow.AddHours(1)));
_jwtService.GenerateRefreshToken(user).Returns(("refresh-token", DateTime.UtcNow.AddDays(7)));
_rolePermissionService.GetPermissionsForRoles(Arg.Any<IList<string>>()).Returns([]);
_rolePermissionService.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
var result = await _handler.Handle(new LoginCommand("test@test.com", "password"), CancellationToken.None);
@@ -78,7 +79,7 @@ public class LoginHandlerTests
}
[Fact]
public async Task Login_with_locked_account_should_return_429()
public async Task Login_with_locked_account_should_return_generic_unauthorized()
{
var user = new AppUser { UserName = "locked@test.com", Email = "locked@test.com" };
_userManager.FindByEmailAsync("locked@test.com").Returns(user);
@@ -87,7 +88,7 @@ public class LoginHandlerTests
var result = await _handler.Handle(new LoginCommand("locked@test.com", "password"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(429);
result.StatusCode.ShouldBe(401);
}
[Fact]
@@ -42,7 +42,8 @@ public class RefreshTokenHandlerTests
_jwtService.GenerateAccessToken(user, Arg.Any<IList<string>>(), Arg.Any<IList<string>>(), Arg.Any<DateTime>())
.Returns(("new-access-token", DateTime.UtcNow.AddHours(1)));
_jwtService.GenerateRefreshToken(user, Arg.Any<DateTime>()).Returns(("new-refresh-token", DateTime.UtcNow.AddDays(7)));
_rolePermissionService.GetPermissionsForRoles(Arg.Any<IList<string>>()).Returns([]);
_rolePermissionService.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
var result = await _handler.Handle(new RefreshTokenCommand("valid-token"), CancellationToken.None);
@@ -1,97 +0,0 @@
using Heimdall.Application.Auth.Commands.RegisterAdmin;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Auth;
public class RegisterAdminHandlerTests
{
private readonly UserManager<AppUser> _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IAuthDataService _authData;
private readonly IPasswordBreachChecker _breachChecker;
private readonly ILogger<RegisterAdminHandler> _logger;
private readonly RegisterAdminHandler _handler;
public RegisterAdminHandlerTests()
{
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>();
_breachChecker = Substitute.For<IPasswordBreachChecker>();
_logger = Substitute.For<ILogger<RegisterAdminHandler>>();
_handler = new RegisterAdminHandler(_authData, _userManager, _jwtService, _rolePermissionService, _breachChecker, _logger);
}
[Fact]
public async Task Register_admin_should_create_user_with_admin_role()
{
_authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any<CancellationToken>())
.Returns("true");
_userManager.FindByEmailAsync("admin@test.com").Returns((AppUser?)null);
_userManager.CreateAsync(Arg.Any<AppUser>(), "password").Returns(IdentityResult.Success);
_userManager.AddToRoleAsync(Arg.Any<AppUser>(), Arg.Any<string>()).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 RegisterAdminCommand("admin@test.com", "password", "Admin"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _userManager.Received(1).AddToRoleAsync(Arg.Any<AppUser>(), "Admin");
}
[Fact]
public async Task Register_admin_with_existing_email_should_return_conflict()
{
_authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any<CancellationToken>())
.Returns("true");
_userManager.FindByEmailAsync("existing@test.com").Returns(new AppUser());
var result = await _handler.Handle(
new RegisterAdminCommand("existing@test.com", "password", "Existing"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
}
[Fact]
public async Task Register_admin_when_disabled_should_return_403()
{
_authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any<CancellationToken>())
.Returns("false");
var result = await _handler.Handle(
new RegisterAdminCommand("test@test.com", "TestPwd123!", "Test"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(403);
}
[Fact]
public async Task Register_admin_when_creation_fails_should_return_error()
{
_authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any<CancellationToken>())
.Returns("true");
_userManager.FindByEmailAsync("fail@test.com").Returns((AppUser?)null);
_userManager.CreateAsync(Arg.Any<AppUser>(), Arg.Any<string>())
.Returns(IdentityResult.Failed(new IdentityError { Description = "Password too weak" }));
var result = await _handler.Handle(
new RegisterAdminCommand("fail@test.com", "weak", "Fail"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.Error!.ShouldContain("Password too weak");
}
}
@@ -27,6 +27,8 @@ public class Verify2faHandlerTests
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_jwtService = Substitute.For<IJwtService>();
_rolePermissionService = Substitute.For<IRolePermissionService>();
_rolePermissionService.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
_db = Substitute.For<IApplicationDbContext>();
_logger = Substitute.For<ILogger<Verify2faHandler>>();
_recoveryCodes = (InMemoryDbSet<UserRecoveryCode>)MockDbSetHelper.CreateFor<UserRecoveryCode>();
@@ -35,6 +35,7 @@ public class AssignRolesHandlerTests
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
@@ -77,6 +78,7 @@ public class AssignRolesHandlerTests
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin", "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
@@ -0,0 +1,50 @@
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.LockUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public sealed class LockUserHandlerTests
{
private readonly AppUser _user = new() { Id = Guid.NewGuid(), UserName = "admin@example.test" };
private readonly UserManager<AppUser> _users;
private readonly IUserRepository _repository = Substitute.For<IUserRepository>();
private readonly LockUserHandler _handler;
public LockUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_users = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_handler = new LockUserHandler(_users, _repository);
}
[Fact]
public async Task Cannot_lock_the_last_admin()
{
_users.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_users.GetRolesAsync(_user).Returns(["Admin"]);
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
var result = await _handler.Handle(new LockUserCommand(_user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
await _users.DidNotReceive().SetLockoutEndDateAsync(Arg.Any<AppUser>(), Arg.Any<DateTimeOffset?>());
}
[Fact]
public async Task Can_lock_an_admin_when_another_admin_exists()
{
_users.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_users.GetRolesAsync(_user).Returns(["Admin"]);
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(2);
_users.SetLockoutEndDateAsync(_user, Arg.Any<DateTimeOffset?>()).Returns(IdentityResult.Success);
_users.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(new LockUserCommand(_user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
}
@@ -35,6 +35,7 @@ public class UnlockUserHandlerTests
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(new UnlockUserCommand(_user.Id), CancellationToken.None);
@@ -67,6 +68,7 @@ public class UnlockUserHandlerTests
_userManager.FindByIdAsync(unlockedUser.Id.ToString()).Returns(unlockedUser);
_userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(unlockedUser).Returns(IdentityResult.Success);
var result = await _handler.Handle(new UnlockUserCommand(unlockedUser.Id), CancellationToken.None);
@@ -85,6 +85,7 @@ public class UpdateUserHandlerTests
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByEmailAsync(newEmail).Returns((AppUser?)null);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, newEmail, "Old Name", "Dark", "fr",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
@@ -13,6 +13,7 @@ namespace Heimdall.E2E.Tests.Pages;
/// login success/failure, validation, logout, protected-route redirects
/// and the one-time administrator setup gate.
/// </summary>
[Collection("E2E")]
public class AuthFlowTests : E2ETestBase
{
public AuthFlowTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
@@ -13,6 +13,7 @@ using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
[Collection("E2E")]
public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres)
{
private const string SnapshotJpegBase64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAb/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCCAWkoAAAAAAAAAB//2Q==";
@@ -4,6 +4,7 @@ using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
[Collection("E2E")]
public class LoginPageTests : E2ETestBase
{
public LoginPageTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
@@ -4,6 +4,7 @@ using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
[Collection("E2E")]
public class PageRenderTests : E2ETestBase
{
public PageRenderTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
@@ -9,6 +9,7 @@ using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
[Collection("E2E")]
public sealed class SessionRefreshTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres)
{
[Fact]
@@ -10,6 +10,7 @@ namespace Heimdall.E2E.Tests.Pages;
/// User-management tests driven through the real Blazor UI (/users):
/// list, create, edit roles, lock/unlock, reset password — as the seeded admin.
/// </summary>
[Collection("E2E")]
public class UserManagementTests : E2ETestBase
{
public UserManagementTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
@@ -153,4 +154,23 @@ public class UserManagementTests : E2ETestBase
// The dialog reveals a temporary password
await dialog.Locator("text=temporaire").WaitForAsync(new() { Timeout = 10000 });
}
[Fact]
public async Task Admin_can_edit_role_permissions_in_the_permissions_ui()
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/admin/claims");
await Page.WaitForSelectorAsync("text=Matrice des permissions", new() { Timeout = 20000 });
var row = Page.Locator("tr").Filter(new() { HasText = "Écriture des caméras" });
await row.WaitForAsync(new() { Timeout = 10000 });
var roleChecks = row.Locator("input[type='checkbox']");
await roleChecks.Nth(1).UncheckAsync(); // Supervisor; Admin stays immutable.
var saveButtons = Page.GetByRole(AriaRole.Button, new() { Name = "Enregistrer", Exact = true });
await saveButtons.Nth(0).ClickAsync();
await Page.WaitForSelectorAsync("text=Droits du rôle enregistrés", new() { Timeout = 10000 });
(await roleChecks.Nth(1).IsCheckedAsync()).ShouldBeFalse();
(await roleChecks.Nth(0).IsCheckedAsync()).ShouldBeTrue();
}
}
+1
View File
@@ -11,6 +11,7 @@ namespace Heimdall.E2E.Tests.Smoke;
/// Quick smoke checks that the E2E host itself is reachable and serves
/// the expected routes (used to distinguish host/boot problems from test bugs).
/// </summary>
[Collection("E2E")]
public class SmokeTests : E2ETestBase
{
public SmokeTests(TestCommon.PostgreSqlContainerFixture postgres) : base(postgres) { }
@@ -54,6 +54,8 @@ public class ChallengeAtomicPostgresTests(PostgreSqlContainerFixture postgres)
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var jwt = Substitute.For<IJwtService>();
var roles = Substitute.For<IRolePermissionService>();
roles.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
var handler = new Verify2faHandler(scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>(),
jwt, roles, db, NullLogger<Verify2faHandler>.Instance);
gate.SignalAndWait(TimeSpan.FromSeconds(30)).ShouldBeTrue();
@@ -1,4 +1,7 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using Heimdall.Application.Auth.Commands.Login;
using Heimdall.Application.Auth.Commands.Complete2faSetup;
using Heimdall.Application.Auth.Commands.Verify2fa;
using Heimdall.Application.Auth.Commands.RefreshToken;
using Heimdall.Application.Auth.Services;
@@ -45,7 +48,13 @@ public sealed class PasswordChallengeIdentityTests : IAsyncLifetime
services.AddScoped<IJwtService, JwtService>();
services.AddScoped<IAuthDataService, AuthDataService>();
services.AddScoped<IAuthSignInService, AuthSignInService>();
services.AddScoped<IRolePermissionService>(_ => Substitute.For<IRolePermissionService>());
services.AddScoped<IRolePermissionService>(_ =>
{
var permissions = Substitute.For<IRolePermissionService>();
permissions.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
return permissions;
});
_services = services.BuildServiceProvider();
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
@@ -78,6 +87,65 @@ public sealed class PasswordChallengeIdentityTests : IAsyncLifetime
s.GetRequiredService<UserManager<AppUser>>(), s.GetRequiredService<IJwtService>(),
s.GetRequiredService<IRolePermissionService>(), s.GetRequiredService<AppDbContext>(), NullLogger<Verify2faHandler>.Instance);
[Fact]
public async Task Authenticator_setup_requires_valid_totp_before_enabling_or_issuing_recovery_codes()
{
using var scope = _services.CreateScope();
var services = scope.ServiceProvider;
var users = services.GetRequiredService<UserManager<AppUser>>();
var db = services.GetRequiredService<AppDbContext>();
var user = (await users.FindByEmailAsync(_email))!;
await users.SetTwoFactorEnabledAsync(user, false);
await users.ResetAuthenticatorKeyAsync(user);
var handler = new Complete2faSetupHandler(users, db, NullLogger<Complete2faSetupHandler>.Instance);
var invalid = await handler.Handle(new(user.Id, "000000"), default);
invalid.IsSuccess.ShouldBeFalse();
(await users.GetTwoFactorEnabledAsync(user)).ShouldBeFalse();
(await db.UserRecoveryCodes.CountAsync(x => x.UserId == user.Id)).ShouldBe(0);
var key = (await users.GetAuthenticatorKeyAsync(user))!;
var code = GenerateTotp(key);
(await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue();
var completed = await handler.Handle(new(user.Id, code), default);
completed.IsSuccess.ShouldBeTrue(completed.Error);
completed.Data!.RecoveryCodes.Count.ShouldBe(10);
(await users.GetTwoFactorEnabledAsync(user)).ShouldBeTrue();
var stored = await db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync();
stored.Count.ShouldBe(10);
stored.ShouldAllBe(x => x.CodeHash.Length == 64 && !completed.Data.RecoveryCodes.Contains(x.CodeHash));
}
// RFC 6238 authenticator codes used by ASP.NET Core Identity use HMAC-SHA1.
#pragma warning disable CA5350
private static string GenerateTotp(string base32Key)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var key = new List<byte>();
var buffer = 0;
var bits = 0;
foreach (var ch in base32Key.TrimEnd('='))
{
buffer = (buffer << 5) | alphabet.IndexOf(ch);
bits += 5;
if (bits >= 8)
{
bits -= 8;
key.Add((byte)(buffer >> bits));
}
}
var counter = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30;
Span<byte> message = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(message, counter);
var hash = HMACSHA1.HashData(key.ToArray(), message);
var offset = hash[^1] & 0x0f;
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
| (hash[offset + 2] << 8) | hash[offset + 3];
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
#pragma warning restore CA5350
private async Task<string> ChallengeAsync()
{
using var scope = _services.CreateScope();
@@ -1,81 +1,105 @@
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Persistence;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
public class RolePermissionServiceTests
public sealed class RolePermissionServiceTests : IAsyncLifetime, IDisposable
{
private readonly RolePermissionService _service = new();
private readonly SqliteConnection _connection = new("Data Source=:memory:");
private ServiceProvider _services = null!;
[Fact]
public void GetPermissionsForRoles_AdminRole_ReturnsAllPermissions()
public async Task InitializeAsync()
{
var result = _service.GetPermissionsForRoles(["Admin"]);
await _connection.OpenAsync();
var services = new ServiceCollection();
services.AddLogging();
services.AddDbContext<AppDbContext>(o => o.UseSqlite(_connection));
services.AddSingleton(new AuditInterceptor());
services.AddIdentity<AppUser, AppRole>()
.AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IRolePermissionService, RolePermissionService>();
_services = services.BuildServiceProvider();
using var scope = _services.CreateScope();
await scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreatedAsync();
var roles = scope.ServiceProvider.GetRequiredService<RoleManager<AppRole>>();
foreach (var roleName in AppRoles.All)
(await roles.CreateAsync(new AppRole(roleName))).Succeeded.ShouldBeTrue();
}
result.ShouldContain(AppPermissions.SiteRead);
result.ShouldContain(AppPermissions.AdminManage);
result.ShouldContain(AppPermissions.AdminUsers);
result.ShouldContain(AppPermissions.CameraWrite);
result.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Admin].Length);
public async Task DisposeAsync()
{
await _services.DisposeAsync();
await _connection.DisposeAsync();
}
public void Dispose()
{
_services.Dispose();
_connection.Dispose();
}
[Fact]
public void GetPermissionsForRoles_SupervisorRole_ReturnsSupervisorPermissions()
public async Task Default_role_permissions_are_persisted_and_loaded_from_identity_claims()
{
var result = _service.GetPermissionsForRoles(["Supervisor"]);
using var scope = _services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IRolePermissionService>();
await service.EnsureDefaultsAsync(default);
await service.EnsureDefaultsAsync(default);
result.ShouldContain(AppPermissions.CameraWrite);
result.ShouldContain(AppPermissions.EventRead);
result.ShouldNotContain(AppPermissions.AdminManage);
result.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Supervisor].Length);
var viewer = await service.GetPermissionsForRolesAsync([AppRoles.Viewer], default);
viewer.ShouldContain(AppPermissions.SiteRead);
viewer.ShouldContain(AppPermissions.CameraRead);
viewer.ShouldNotContain(AppPermissions.CameraWrite);
viewer.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Viewer].Length);
}
[Fact]
public void GetPermissionsForRoles_ViewerRole_ReturnsReadOnlyPermissions()
public async Task Updating_role_permissions_persists_and_revokes_member_sessions()
{
var result = _service.GetPermissionsForRoles(["Viewer"]);
using var scope = _services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
var user = new AppUser { UserName = "viewer@example.test", Email = "viewer@example.test", SecurityStamp = "old-stamp" };
(await users.CreateAsync(user, "ViewerPass123!")).Succeeded.ShouldBeTrue();
(await users.AddToRoleAsync(user, AppRoles.Viewer)).Succeeded.ShouldBeTrue();
var beforeStamp = user.SecurityStamp;
var service = scope.ServiceProvider.GetRequiredService<IRolePermissionService>();
await service.EnsureDefaultsAsync(default);
result.ShouldContain(AppPermissions.SiteRead);
result.ShouldContain(AppPermissions.CameraRead);
result.ShouldContain(AppPermissions.CameraLive);
result.ShouldContain(AppPermissions.EventRead);
result.ShouldContain(AppPermissions.PersonRead);
result.ShouldNotContain(AppPermissions.CameraWrite);
result.ShouldNotContain(AppPermissions.AdminManage);
result.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Viewer].Length);
var changed = await service.SetPermissionsAsync(AppRoles.Viewer,
[AppPermissions.SiteRead, AppPermissions.CameraRead, AppPermissions.EventRead, AppPermissions.CameraWrite],
user.Id, default);
changed.IsSuccess.ShouldBeTrue();
user.SecurityStamp.ShouldNotBe(beforeStamp);
var effective = await service.GetPermissionsForRolesAsync([AppRoles.Viewer], default);
effective.ShouldContain(AppPermissions.CameraWrite);
effective.ShouldNotContain(AppPermissions.CameraLive);
}
[Fact]
public void GetPermissionsForRoles_MultipleRoles_ReturnsDistinctPermissions()
public async Task Admin_permissions_cannot_be_changed_or_removed_accidentally()
{
var result = _service.GetPermissionsForRoles(["Supervisor", "Viewer"]);
using var scope = _services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IRolePermissionService>();
await service.EnsureDefaultsAsync(default);
result.ShouldContain(AppPermissions.CameraWrite);
result.ShouldContain(AppPermissions.CameraRead);
result.ShouldContain(AppPermissions.PersonRead);
}
var result = await service.SetPermissionsAsync(AppRoles.Admin, [AppPermissions.SiteRead], Guid.NewGuid(), default);
[Fact]
public void GetPermissionsForRoles_UnknownRole_ReturnsEmpty()
{
var result = _service.GetPermissionsForRoles(["NonExistentRole"]);
result.ShouldBeEmpty();
}
[Fact]
public void GetPermissionsForRoles_EmptyRoles_ReturnsEmpty()
{
var result = _service.GetPermissionsForRoles([]);
result.ShouldBeEmpty();
}
[Fact]
public void GetPermissionsForRoles_MultipleRoles_DeduplicatesPermissions()
{
var result = _service.GetPermissionsForRoles(["Admin", "Supervisor", "Viewer"]);
result.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Admin].Length);
result.IsSuccess.ShouldBeFalse();
var permissions = await service.GetPermissionsForRolesAsync([AppRoles.Admin], default);
permissions.ShouldContain(AppPermissions.AdminUsers);
permissions.ShouldContain(AppPermissions.AdminManage);
permissions.Count.ShouldBe(AppPermissions.RolePermissions[AppRoles.Admin].Length);
}
}
@@ -147,7 +147,7 @@ public class AuthFlowTests : IAsyncLifetime
/// This validates the complete auth pipeline works end-to-end.
/// </summary>
[Fact]
public async Task RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi()
public async Task FirstAdminBootstraps_AndCreatesFurtherAdminsThroughUserManagement()
{
var email = $"e2e-{Guid.NewGuid()}@heimdall.test";
var password = "E2eTestPwd123!";
@@ -166,33 +166,35 @@ public class AuthFlowTests : IAsyncLifetime
var bootToken = bootContent.GetProperty("accessToken").GetString();
bootToken.ShouldNotBeNullOrEmpty();
// Enable the admin-registration feature flag
// Further accounts, including additional administrators, use the same
// user-management path that the authenticated UI calls.
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", bootToken);
var flagResponse = await client.PostAsJsonAsync("/api/settings", new
var createResponse = await client.PostAsJsonAsync("/api/users", new
{
key = "auth.admin-registration.enabled",
value = "true",
valueType = "bool",
category = "Auth",
description = "Enable admin registration via API"
email,
password,
displayName = "E2E Test Admin",
roles = new[] { "Admin" }
});
flagResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
createResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
// Step 2: Register a new admin via RegisterAdmin
var registerResponse = await client.PostAsJsonAsync("/api/auth/register-admin", new
var legacyAdminRegistration = await client.PostAsJsonAsync("/api/auth/register-admin", new
{
email,
password,
displayName = "E2E Test Admin"
});
legacyAdminRegistration.StatusCode.ShouldBe(HttpStatusCode.NotFound);
registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var registerContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
var accessToken = registerContent.GetProperty("accessToken").GetString();
var refreshToken = registerContent.GetProperty("refreshToken").GetString();
accessToken.ShouldNotBeNullOrEmpty("register-admin must return an access token");
refreshToken.ShouldNotBeNullOrEmpty("register-admin must return a refresh token");
// New accounts are not implicitly signed in by account-management actions.
var loginResponse = await client.PostAsJsonAsync("/api/auth/login", new { email, password });
loginResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var loginContent = await loginResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
var accessToken = loginContent.GetProperty("accessToken").GetString();
var refreshToken = loginContent.GetProperty("refreshToken").GetString();
accessToken.ShouldNotBeNullOrEmpty();
refreshToken.ShouldNotBeNullOrEmpty();
// Step 3: Use the new admin token to access a protected API endpoint
client.DefaultRequestHeaders.Authorization =
@@ -82,6 +82,8 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres
[Theory]
[InlineData("lock")]
[InlineData("roles")]
[InlineData("password")]
[InlineData("email")]
public async Task Existing_jwt_cookie_and_refresh_are_revoked_by_account_change(string change)
{
var auth = await LoginAsync();
@@ -92,7 +94,25 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres
{
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
if (change == "lock") (await sender.Send(new LockUserCommand(_userId))).IsSuccess.ShouldBeTrue();
else (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue();
else if (change == "roles") (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue();
else
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
var user = (await users.FindByIdAsync(_userId.ToString()))!;
if (change == "email")
{
var update = await users.SetEmailAsync(user, $"changed-{_email}");
update.Succeeded.ShouldBeTrue();
await users.UpdateSecurityStampAsync(user);
}
else
{
var token = await users.GeneratePasswordResetTokenAsync(user);
var reset = await users.ResetPasswordAsync(user, token, "Changed-password-123!");
reset.Succeeded.ShouldBeTrue();
await users.UpdateSecurityStampAsync(user);
}
}
}
var refresh = await _client.PostAsJsonAsync("/api/auth/refresh", new { refreshToken = auth.RefreshToken });
refresh.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
@@ -1,6 +1,7 @@
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.IntegrationTests.Factories;
using System.Net.Http.Headers;
using Shouldly;
namespace Heimdall.IntegrationTests.Controllers;
@@ -59,4 +60,65 @@ public class RolesControllerTests : PostgresTestBase
roles.Any(r => r.GetProperty("name").GetString() == "Admin").ShouldBeTrue();
roles.Any(r => r.GetProperty("name").GetString() == "Viewer").ShouldBeTrue();
}
[Fact]
public async Task Admin_can_change_viewer_permissions_and_existing_viewer_sessions_are_revoked()
{
var admin = await Factory.CreateAdminClientAsync();
var email = $"dynamic-viewer-{Guid.NewGuid():N}@heimdall.test";
const string password = "DynamicViewer123!";
var created = await admin.PostAsJsonAsync("api/users", new
{
email, password, displayName = "Dynamic Viewer", roles = new[] { "Viewer" }
});
created.EnsureSuccessStatusCode();
using var viewer = Factory.CreateClient();
var login = await viewer.PostAsJsonAsync("api/auth/login", new { email, password });
login.EnsureSuccessStatusCode();
var loginBody = await login.Content.ReadFromJsonAsync<JsonElement>();
var oldToken = loginBody.GetProperty("accessToken").GetString()!;
viewer.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oldToken);
var forbiddenUpdate = await viewer.PutAsJsonAsync("api/roles/Viewer/permissions", new
{
permissions = new[] { "Site.Read" }
});
forbiddenUpdate.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
var update = await admin.PutAsJsonAsync("api/roles/Viewer/permissions", new
{
permissions = new[] { "Site.Read", "Camera.Read", "Event.Read", "Camera.Write" }
});
update.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var staleSession = await viewer.GetAsync("api/users/me");
staleSession.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
var freshLogin = await viewer.PostAsJsonAsync("api/auth/login", new { email, password });
freshLogin.EnsureSuccessStatusCode();
var freshBody = await freshLogin.Content.ReadFromJsonAsync<JsonElement>();
freshBody.GetProperty("user").GetProperty("permissions").EnumerateArray()
.Select(p => p.GetString()).ShouldContain("Camera.Write");
var list = await admin.GetFromJsonAsync<JsonElement>("api/roles");
var viewerRole = list.GetProperty("roles").EnumerateArray()
.Single(r => r.GetProperty("name").GetString() == "Viewer");
viewerRole.GetProperty("permissions").EnumerateArray().Select(p => p.GetString())
.ShouldNotContain("Camera.Live");
}
[Fact]
public async Task Admin_role_permissions_are_immutable()
{
var admin = await Factory.CreateAdminClientAsync();
var update = await admin.PutAsJsonAsync("api/roles/Admin/permissions", new
{
permissions = new[] { "Site.Read" }
});
update.StatusCode.ShouldBe(System.Net.HttpStatusCode.BadRequest);
var role = await admin.GetFromJsonAsync<JsonElement>("api/roles/Admin");
var permissions = role.GetProperty("permissions").EnumerateArray().Select(p => p.GetString()).ToArray();
permissions.ShouldContain("Admin.Users");
permissions.ShouldContain("Admin.Manage");
}
}
@@ -69,4 +69,30 @@ public class UsersControllerTests : PostgresTestBase
var resetContent = await resetResponse.Content.ReadFromJsonAsync<JsonElement>();
resetContent.GetProperty("temporaryPassword").GetString().ShouldNotBeNullOrEmpty();
}
[Fact]
public async Task Last_unlocked_admin_cannot_be_locked_when_another_admin_is_already_locked()
{
var admin = await Factory.CreateAdminClientAsync();
var list = await admin.GetFromJsonAsync<JsonElement>("api/users?page=1&pageSize=20");
var firstAdminId = list.GetProperty("items").EnumerateArray()
.Single(user => user.GetProperty("roles").EnumerateArray().Any(role => role.GetString() == "Admin"))
.GetProperty("id").GetGuid();
var created = await admin.PostAsJsonAsync("api/users", new
{
email = $"extra-admin-{Guid.NewGuid():N}@heimdall.test",
password = "ExtraAdmin123!",
displayName = "Extra Admin",
roles = new[] { "Admin" }
});
created.EnsureSuccessStatusCode();
var secondAdminId = (await created.Content.ReadFromJsonAsync<JsonElement>())
.GetProperty("id").GetGuid();
(await admin.PostAsync($"api/users/{secondAdminId}/lock", null)).StatusCode
.ShouldBe(System.Net.HttpStatusCode.OK);
var lockLast = await admin.PostAsync($"api/users/{firstAdminId}/lock", null);
lockLast.StatusCode.ShouldBe(System.Net.HttpStatusCode.BadRequest);
}
}
@@ -35,4 +35,17 @@ public class AuthStateTests
state.AuthCookie.ShouldBeNull();
state.IsLoggedIn.ShouldBeFalse();
}
[Fact]
public void Login_UsesPersistedPermissionsFromTheAuthResponse()
{
var response = new AuthResponse("access", "refresh", DateTime.UtcNow.AddHours(1), false,
new UserInfo(Guid.NewGuid(), "viewer@heimdall.test", "Viewer", ["Viewer"], ["Camera.Write"]));
var state = new AuthState();
state.Login(response);
state.HasPermission("Camera.Write").ShouldBeTrue();
state.HasPermission("Camera.Live").ShouldBeFalse();
}
}
@@ -769,7 +769,7 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable
{
_handler.QueueResponse(HttpStatusCode.OK, new { secret = "abc", qrCode = "data" });
var result = await _sut.Enable2faAsync();
var result = await _sut.Enable2faAsync("Current-password-123!");
Assert.NotNull(result);
}
@@ -779,7 +779,7 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable
{
_handler.QueueResponse(HttpStatusCode.BadRequest);
var result = await _sut.Enable2faAsync();
var result = await _sut.Enable2faAsync("Current-password-123!");
Assert.Null(result);
}
@@ -789,7 +789,7 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable
{
_handler.QueueResponse(HttpStatusCode.OK);
var result = await _sut.Disable2faAsync();
var result = await _sut.Disable2faAsync("Current-password-123!");
Assert.True(result);
}
@@ -799,7 +799,7 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable
{
_handler.QueueResponse(HttpStatusCode.BadRequest);
var result = await _sut.Disable2faAsync();
var result = await _sut.Disable2faAsync("Current-password-123!");
Assert.False(result);
}
+3 -1
View File
@@ -19,7 +19,9 @@ 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] **AUTH-BOOTSTRAP** L’assistant `/setup` ne crée le premier compte que sur une base vide et lui attribue Admin dans une transaction PostgreSQL sérialisable; l’UI login redirige vers l’assistant au premier lancement. L’inscription anonyme et l’ancienne route `register-admin` renvoient 404; les comptes suivants passent par l’UI `/users` et l’API protégée `Admin.Users`. Recette Compose jetable finale du 4 novembre 2026 : statut initial ouvert → premier Admin → statut fermé → création d’utilisateurs protégée; vérification de la route setup, refus anonyme et suppression des deux anciennes routes. Tests PostgreSQL intégration complets 161/161; tests E2E AuthFlow/UI utilisateur réussis (résultats notés dans USER-RBAC ci-dessous). Le bootstrap concurrent reste couvert par les tests PostgreSQL dédiés.
- [ ] **IDENTITY-HARDENING** La 2FA est enrôlée en deux étapes (clé créée sans activation, renouvellement session après rotation du `SecurityStamp`, TOTP vérifié avant activation et génération de codes de secours hashés); mot de passe, adresse, rôles, verrouillage/déverrouillage et 2FA révoquent les sessions. Les résultats Identity sont contrôlés; réponses d’authentification génériques; journaux sans email ni détails Identity; unicité email et lockout explicites. Validation .NET 10.0.114 : Application 517/517, Infrastructure 281/281, Integration PostgreSQL 161/161, Web 412/412; build Web sans avertissement. Recette Compose jetable complète réussie et nettoyée. `global.json` autorise `latestFeature`; le lock file Web est inchangé. Réserve d’architecture hors de ce parcours : Identity reste référencé depuis Domain/Application et demande une extraction séparée.
- [x] **USER-RBAC** Premier Admin et comptes suivants créés via leurs écrans dédiés; l’UI `/users` liste, crée, édite, assigne les rôles, confirme l’email, verrouille/déverrouille, réinitialise le mot de passe et supprime. L’ancienne API de création Admin hors UI a été retirée. Les claims Identity persistés alimentent maintenant les droits effectifs; `/admin/claims` modifie les permissions Supervisor/Viewer et le rôle Admin reste immuable. Les changements de rôle/droits renouvellent les `SecurityStamp`, invalident JWT/cookies/refresh de la cible et journalisent l’acteur. Les routes Users/Roles/Permissions appliquent leurs politiques; le dernier Admin déverrouillé ne peut pas être verrouillé ou déclassé, et sa suppression est refusée. E2E navigateur AuthFlow + gestion utilisateurs 15/15; tests Application 517/517, Infrastructure 281/281, Web 412/412 et PostgreSQL 161/161. Compose jetable construit depuis le code final : Viewer refusé sur API Admin, permission `Camera.Write` modifiée puis effective sur `/api/cameras`, ancien JWT refusé, dernier Admin protégé; nettoyage conteneurs/volumes/réseau vérifié. Les définitions de rôles restent les trois rôles système (Admin fixe, Supervisor et Viewer configurables), sans création de rôles arbitraires.
- [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`).