diff --git a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faCommand.cs b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faCommand.cs index 0cba26a..1af8501 100644 --- a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faCommand.cs +++ b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faCommand.cs @@ -1,6 +1,7 @@ +using Heimdall.Application.DTOs; using Heimdall.Application.Common; using MediatR; namespace Heimdall.Application.Auth.Commands.Enable2fa; -public record Enable2faCommand(Guid UserId) : IRequest; +public record Enable2faCommand(Guid UserId) : IRequest>; diff --git a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs index 72c90af..798bcca 100644 --- a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs @@ -1,3 +1,4 @@ +using Heimdall.Application.DTOs; using Heimdall.Application.Common; using Heimdall.Domain.Entities; using MediatR; @@ -6,7 +7,7 @@ using Microsoft.Extensions.Logging; namespace Heimdall.Application.Auth.Commands.Enable2fa; -public class Enable2faHandler : IRequestHandler +public class Enable2faHandler : IRequestHandler> { private readonly UserManager _userManager; private readonly ILogger _logger; @@ -17,7 +18,7 @@ public class Enable2faHandler : IRequestHandler _logger = logger; } - public async Task Handle(Enable2faCommand request, CancellationToken ct) + public async Task> Handle(Enable2faCommand request, CancellationToken ct) { _logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId); @@ -25,17 +26,28 @@ public class Enable2faHandler : IRequestHandler if (user is null) { _logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId); - return ServiceResult.NotFound("User not found"); + return ServiceResult.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.Failure("Failed to enable 2FA"); + return ServiceResult.Failure("Failed to enable 2FA"); } + // 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 key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false); + if (string.IsNullOrEmpty(key)) + { + _logger.LogError("Enable2fa: Failed to generate authenticator key UserId={UserId}", request.UserId); + return ServiceResult.Failure("Failed to generate 2FA key"); + } + + var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30"; _logger.LogInformation("Enable2fa: Enabled UserId={UserId}", request.UserId); - return ServiceResult.Success(); + return ServiceResult.Success(new Enable2faResponse(key, qrCodeUri)); } } diff --git a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs index 89eb182..a415803 100644 --- a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Common.Persistence; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; @@ -14,6 +15,7 @@ public class LoginHandler : IRequestHandler _logger; public LoginHandler( @@ -21,12 +23,14 @@ public class LoginHandler : IRequestHandler logger) { _userManager = userManager; _signInService = signInService; _jwtService = jwtService; _rolePermissionService = rolePermissionService; + _userRepository = userRepository; _logger = logger; } @@ -38,6 +42,7 @@ public class LoginHandler : IRequestHandler.Unauthorized("Invalid email or password"); } diff --git a/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs b/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs index 878a934..62606eb 100644 --- a/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs @@ -66,6 +66,10 @@ public class RefreshTokenHandler : IRequestHandler? firstCreateError = null; + try { - var errors = string.Join(", ", createResult.Errors.Select(e => e.Description)); - _logger.LogError("Register: First user creation failed: {Errors}", errors); - return ServiceResult.Failure(errors); + var createResult = await _userManager.CreateAsync(firstUser, request.Password).ConfigureAwait(false); + if (!createResult.Succeeded) + { + var errors = string.Join(", ", createResult.Errors.Select(e => e.Description)); + _logger.LogError("Register: First user creation failed: {Errors}", errors); + firstCreateError = ServiceResult.Failure(errors); + } } + catch (DbUpdateException ex) when (ex.InnerException?.Message.IndexOf("unique", StringComparison.OrdinalIgnoreCase) >= 0) + { + _logger.LogWarning("Register: Race condition — first user Email={Email} created by another request", request.Email); + firstCreateError = ServiceResult.Conflict("Email already registered"); + } + + if (firstCreateError is not null) + return firstCreateError; await _userManager.AddToRoleAsync(firstUser, "Admin").ConfigureAwait(false); _logger.LogInformation("Register: First user created and granted Admin role Email={Email}", request.Email); @@ -69,8 +82,7 @@ public class RegisterHandler : IRequestHandler.Failure("Public registration is disabled. Contact an administrator.", 403); @@ -84,13 +96,25 @@ public class RegisterHandler : IRequestHandler? createError = null; + try { - var errors = string.Join(", ", result.Errors.Select(e => e.Description)); - _logger.LogError("Register: User creation failed: {Errors}", errors); - return ServiceResult.Failure(errors); + var result = await _userManager.CreateAsync(user, request.Password).ConfigureAwait(false); + if (!result.Succeeded) + { + var errors = string.Join(", ", result.Errors.Select(e => e.Description)); + _logger.LogError("Register: User creation failed: {Errors}", errors); + createError = ServiceResult.Failure(errors); + } } + catch (DbUpdateException ex) when (ex.InnerException?.Message.Contains("unique", StringComparison.OrdinalIgnoreCase) == true) + { + _logger.LogWarning("Register: Race condition — Email={Email} was created by another request", request.Email); + createError = ServiceResult.Conflict("Email already registered"); + } + + if (createError is not null) + return createError; _logger.LogDebug("Register: Assigning Viewer role to Email={Email}", request.Email); await _userManager.AddToRoleAsync(user, "Viewer").ConfigureAwait(false); diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs index deea6ca..e639c65 100644 --- a/src/Heimdall.Application/DTOs/AuthDto.cs +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -39,3 +39,8 @@ public record CreateApiKeyResponse( public record ChangePasswordRequest(string CurrentPassword, string NewPassword); public record LogoutRequest(string RefreshToken); + + +public record Enable2faResponse( + string SharedKey, + string QrCodeUri); diff --git a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs index 9ba5ea7..5fa9a92 100644 --- a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs +++ b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs @@ -34,9 +34,8 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler HandleAuthenticateAsync() { - var apiKey = Request.Headers.Authorization.FirstOrDefault() - ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase) - ?? Request.Headers["X-API-Key"].FirstOrDefault(); + // X-API-Key header only (pas de Bearer — réservé au handler JWT) + var apiKey = Request.Headers["X-API-Key"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8) return AuthenticateResult.NoResult(); @@ -60,6 +59,8 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler { diff --git a/src/Heimdall.Infrastructure/Security/AuthDataService.cs b/src/Heimdall.Infrastructure/Security/AuthDataService.cs index f0a7cee..53161e3 100644 --- a/src/Heimdall.Infrastructure/Security/AuthDataService.cs +++ b/src/Heimdall.Infrastructure/Security/AuthDataService.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Services; +using System.IdentityModel.Tokens.Jwt; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; @@ -34,11 +35,27 @@ public class AuthDataService : IAuthDataService public async Task RevokeRefreshTokenAsync(string refreshToken, Guid userId, CancellationToken ct) { + var tokenId = ExtractJti(refreshToken); _db.RevokedRefreshTokens.Add(new Heimdall.Domain.Entities.RevokedRefreshToken( - refreshToken, userId, DateTime.UtcNow.AddDays(7))); + tokenId, userId, DateTime.UtcNow.AddDays(7))); await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); } + private static string ExtractJti(string refreshToken) + { + try + { + var handler = new JwtSecurityTokenHandler(); + var jwtToken = handler.ReadJwtToken(refreshToken); + return jwtToken.Id; // jti + } + catch + { + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData( + System.Text.Encoding.UTF8.GetBytes(refreshToken))); + } + } + public async Task SetSettingValueAsync(string key, string value, string category, string? description, CancellationToken ct) { var existing = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == key, ct); diff --git a/src/Heimdall.Infrastructure/Security/JwtService.cs b/src/Heimdall.Infrastructure/Security/JwtService.cs index 8fe6046..a1b83fa 100644 --- a/src/Heimdall.Infrastructure/Security/JwtService.cs +++ b/src/Heimdall.Infrastructure/Security/JwtService.cs @@ -125,18 +125,38 @@ public class JwtService : IJwtService ?? throw new InvalidOperationException("Jwt:RefreshKey is not configured (set JWT__REFRESHKEY env var)"); } + public string? GetUserIdFromExpiredToken(string token) { + var key = new SymmetricSecurityKey( + Encoding.UTF8.GetBytes(GetJwtKey())); + try { var handler = new JwtSecurityTokenHandler(); - var jwtToken = handler.ReadJwtToken(token); - return jwtToken.Subject; + var principal = handler.ValidateToken(token, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = key, + ValidateIssuer = true, + ValidIssuer = _configuration["Jwt:Issuer"] ?? "heimdall", + ValidateAudience = true, + ValidAudience = _configuration["Jwt:Audience"] ?? "heimdall-api", + ValidateLifetime = false, // Allow expired tokens to be read + ClockSkew = TimeSpan.Zero + }, out _); + return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value + ?? principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value; } - catch (Exception ex) when (ex is ArgumentException) + catch (Exception ex) when (ex is SecurityTokenExpiredException + or SecurityTokenInvalidSignatureException + or SecurityTokenInvalidIssuerException + or ArgumentException) { - _logger.LogWarning("Failed to read expired token: {Message}", ex.Message); + _logger.LogWarning("Failed to read expired token: {ExceptionType} — {Message}", + ex.GetType().Name, ex.Message); return null; } } + } diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index d4617bc..2787c63 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -44,13 +44,13 @@ public class AuthController : ControllerBase _logger.LogInformation("Register attempt for {Email}", request.Email); var command = new RegisterCommand(request.Email, request.Password, request.DisplayName); var result = await _mediator.Send(command, ct); - + if (result.IsSuccess) { _logger.LogInformation("User registered successfully: {Email}", request.Email); return Ok(result.Data); } - + _logger.LogWarning("User registration failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } @@ -65,19 +65,20 @@ public class AuthController : ControllerBase _logger.LogInformation("Login attempt for {Email}", request.Email); 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); return Ok(result.Data); } - + _logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Verify a 2FA code. [AllowAnonymous] + [EnableRateLimiting("TwoFactor")] [HttpPost("2fa/verify")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] @@ -86,13 +87,13 @@ public class AuthController : ControllerBase _logger.LogInformation("2FA verification attempt for {Email}", request.Email); var command = new Verify2faCommand(request.Email, request.Code); var result = await _mediator.Send(command, ct); - + if (result.IsSuccess) { _logger.LogInformation("2FA verification successful for {Email}", request.Email); return Ok(result.Data); } - + _logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } @@ -106,13 +107,13 @@ public class AuthController : ControllerBase { _logger.LogDebug("Token refresh attempt"); var result = await _mediator.Send(new RefreshTokenCommand(request.RefreshToken), ct); - + if (result.IsSuccess) { _logger.LogDebug("Token refresh successful"); return Ok(result.Data); } - + _logger.LogWarning("Token refresh failed: {Error}", result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } @@ -136,19 +137,20 @@ public class AuthController : ControllerBase _logger.LogInformation("Password change attempt for user {UserId}", userId); var command = new ChangePasswordCommand(userId, request.CurrentPassword, request.NewPassword); var result = await _mediator.Send(command, ct); - + if (result.IsSuccess) { _logger.LogInformation("Password changed successfully for user {UserId}", userId); return Ok(); } - + _logger.LogWarning("Password change failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg). [AllowAnonymous] + [EnableRateLimiting("TwoFactor")] [HttpPost("register-admin")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] @@ -164,21 +166,21 @@ public class AuthController : ControllerBase _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 }); } - /// Enable 2FA for the current user. + /// Enable 2FA for the current user. Returns the shared key and QR code URI for setup. [Authorize] [HttpPost("2fa/enable")] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Enable2fa(CancellationToken ct) { @@ -191,13 +193,13 @@ public class AuthController : ControllerBase _logger.LogInformation("2FA enable attempt for user {UserId}", userId); var result = await _mediator.Send(new Enable2faCommand(userId), ct); - + if (result.IsSuccess) { _logger.LogInformation("2FA enabled successfully for user {UserId}", userId); - return Ok(); + return Ok(result.Data); } - + _logger.LogWarning("2FA enable failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } @@ -218,13 +220,13 @@ public class AuthController : ControllerBase _logger.LogInformation("2FA disable attempt for user {UserId}", userId); var result = await _mediator.Send(new Disable2faCommand(userId), ct); - + if (result.IsSuccess) { _logger.LogInformation("2FA disabled successfully for user {UserId}", userId); return Ok(); } - + _logger.LogWarning("2FA disable failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 344cddd..a10531c 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -209,7 +209,7 @@ public partial class Program { internal static void ConfigureServices(WebApplicationBuilder builder) { - // ── Sentry (GlitchTip) — DSN from config pipeline with legacy env var fallback ── + // ── Sentry (GlitchTip) — error tracking, performance & structured logs ── // Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn // Fallback: legacy SENTRY_DSN env var (Docker backward compat) // Neither set → DSN is null → Sentry SDK no-ops gracefully @@ -220,11 +220,71 @@ public partial class Program { builder.WebHost.UseSentry(options => { options.Dsn = sentryDsn; + + // ── Env & Release ──────────────────────────────────────── + // Environment is auto-read from IHostingEnvironment + // Release should be explicitly set (e.g. "heimdall@1.2.3") + options.Release = builder.Configuration["Sentry:Release"] + ?? Environment.GetEnvironmentVariable("SENTRY_RELEASE"); + + // ── Error sampling ────────────────────────────────────── + options.SampleRate = 1.0f; // 100% errors (adjust if volume too high) + options.AttachStacktrace = true; // Stack traces even on CaptureMessage + options.MaxBreadcrumbs = 100; // Breadcrumb buffer size options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; - options.TracesSampleRate = 0.05; + + // ── Tracing (Performance) ─────────────────────────────── + // GlitchTip counts every transaction as an event. + // 0.05 = 5% sample = good signal-to-noise in production. + options.TracesSampleRate = double.Parse( + builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05"); + + // ── Request body capture ──────────────────────────────── options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small; - options.ProfilesSampleRate = 0.05; + + // ── Structured logs (v5.14+) ──────────────────────────── + // Enables SentrySdk.Logger.LogInfo() etc. + options.EnableLogs = true; + + // ── GlitchTip-specific: disable unsupported features ──── + // Release Health / Sessions are NOT supported by GlitchTip + options.AutoSessionTracking = false; + + // ── PII & GDPR ────────────────────────────────────────── + options.SendDefaultPii = false; // Explicit RGPD-safe default + options.ServerName = null; // Never send hostname + + // ── Enhanced diagnostics ──────────────────────────────── + options.CaptureBlockingCalls = true; // Detect .Result / .Wait() + options.CaptureFailedRequests = true; // Capture HttpClient 4xx/5xx + options.IncludeActivityData = true; // DiagnosticSource Activity + + // ── Stack traces ──────────────────────────────────────── + options.StackTraceMode = Sentry.StackTraceMode.Enhanced; + + // ── BeforeSend — scrub PII before it leaves the SDK ──── + options.SetBeforeSend((sentryEvent, hint) => + { + // Never send server name (already null above, belt-and-suspenders) + sentryEvent.ServerName = null; + + // Remove sensitive extras + if (sentryEvent.Extra?.ContainsKey("password") == true) + sentryEvent.Extra.Remove("password"); + if (sentryEvent.Extra?.ContainsKey("token") == true) + sentryEvent.Extra.Remove("token"); + if (sentryEvent.Extra?.ContainsKey("secret") == true) + sentryEvent.Extra.Remove("secret"); + + return sentryEvent; + }); + + // ── BeforeBreadcrumb — filter noisy breadcrumbs ──────── + options.SetBeforeBreadcrumb(breadcrumb + => breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting" + ? null + : breadcrumb); }); } diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs index 81d9d4c..a29d4d3 100644 --- a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs +++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs @@ -7,12 +7,12 @@ namespace Heimdall.Web.Services; public class HeimdallAuthStateProvider : AuthenticationStateProvider { - private readonly ProtectedLocalStorage _storage; + private readonly ProtectedSessionStorage _storage; private readonly AuthState _authState; private const string StorageKey = "heimdall_auth"; - public HeimdallAuthStateProvider(ProtectedLocalStorage storage, AuthState authState) + public HeimdallAuthStateProvider(ProtectedSessionStorage storage, AuthState authState) { _storage = storage; _authState = authState;