From 26321bb81c362ef1489fc4c3635d54bae56a9ead Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 20 Oct 2026 07:21:28 +0200 Subject: [PATCH 1/2] fix(auth): secure 2FA challenges and session revocation --- docs/audits/2026-10-20-lot1-auth-session.md | 61 + readme.md | 4 +- src/Heimdall.Application/Auth/AuthHelper.cs | 11 +- .../Auth/Commands/Login/LoginHandler.cs | 41 +- .../RefreshToken/RefreshTokenHandler.cs | 20 +- .../Auth/Commands/Register/RegisterHandler.cs | 3 + .../Commands/Verify2fa/Verify2faCommand.cs | 2 +- .../Commands/Verify2fa/Verify2faHandler.cs | 45 +- .../Commands/Verify2fa/Verify2faValidator.cs | 4 +- .../Auth/Services/AccountSessionPolicy.cs | 28 + .../Auth/Services/LoginChallengeService.cs | 52 + src/Heimdall.Application/DTOs/AuthDto.cs | 5 +- .../Services/IJwtService.cs | 2 + .../AssignRoles/AssignRolesHandler.cs | 1 + .../Commands/LockUser/LockUserHandler.cs | 1 + .../Entities/LoginChallenge.cs | 13 + .../LoginChallengeConfiguration.cs | 18 + ..._ReconcileExistingAccessSchema.Designer.cs | 2558 ++++++++++++++++ ...020002409_ReconcileExistingAccessSchema.cs | 107 + ...61020002410_AddLoginChallenges.Designer.cs | 2602 +++++++++++++++++ .../20261020002410_AddLoginChallenges.cs | 50 + .../Migrations/AppDbContextModelSnapshot.cs | 154 + .../Security/AuthSignInService.cs | 4 +- .../Security/JwtService.cs | 25 +- src/Heimdall.Web/Components/Pages/Login.razor | 5 +- .../Controllers/AuthController.cs | 8 +- src/Heimdall.Web/Program.cs | 55 +- src/Heimdall.Web/Services/AuthState.cs | 5 +- .../Services/HeimdallApiClient.cs | 31 +- .../Services/HeimdallAuthStateProvider.cs | 54 +- .../Services/TokenRefreshHandler.cs | 44 +- .../Handlers/Auth/LoginHandlerTests.cs | 11 +- .../Handlers/Auth/RefreshTokenHandlerTests.cs | 10 +- .../Handlers/Auth/Verify2faHandlerTests.cs | 88 +- .../Pages/SessionRefreshTests.cs | 37 + .../Pages/UserManagementTests.cs | 7 +- .../AuthMigrationCompatibilityTests.cs | 55 + .../AuthSignInServiceTests.cs | 17 +- .../ChallengeAtomicPostgresTests.cs | 64 + .../JwtServiceTests.cs | 23 + .../PasswordChallengeIdentityTests.cs | 276 ++ .../Controllers/AuthSessionSecurityTests.cs | 107 + .../Services/TokenRefreshHandlerTests.cs | 38 + 43 files changed, 6533 insertions(+), 213 deletions(-) create mode 100644 docs/audits/2026-10-20-lot1-auth-session.md create mode 100644 src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs create mode 100644 src/Heimdall.Application/Auth/Services/LoginChallengeService.cs create mode 100644 src/Heimdall.Domain/Entities/LoginChallenge.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/LoginChallengeConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.cs create mode 100644 tests/Heimdall.E2E.Tests/Pages/SessionRefreshTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/AuthMigrationCompatibilityTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/ChallengeAtomicPostgresTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/PasswordChallengeIdentityTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs diff --git a/docs/audits/2026-10-20-lot1-auth-session.md b/docs/audits/2026-10-20-lot1-auth-session.md new file mode 100644 index 0000000..a3ab958 --- /dev/null +++ b/docs/audits/2026-10-20-lot1-auth-session.md @@ -0,0 +1,61 @@ +# Lot 1 — Authentification et sessions + +Périmètre : SEC-01, SEC-02, SEC-07 et SEC-10 du [rapport](2026-10-20-audit-complet.md), selon le [plan](2026-10-20-plan-implementation.md). Les autres lots restent hors de ce chantier. Ce document ne clôt pas l’audit global. + +## Contrat de connexion + +`POST /api/auth/login` conserve `{ email, password }`. Le mot de passe est vérifié par `SignInManager.CheckPasswordSignInAsync` avec verrouillage Identity, sans ouvrir de session et sans émettre de cookie, même pour un compte sans 2FA. + +Pour un compte avec 2FA, la réponse contient `requires2fa: true`, des tokens vides et `challengeId`, secret aléatoire de 256 bits. Le serveur ne conserve que son empreinte SHA-256, l’utilisateur, son security stamp, l’expiration, le compteur et les états de vérification/consommation. La durée est de cinq minutes, avec cinq tentatives au maximum. + +`POST /api/auth/2fa/verify` attend désormais `{ challengeId, code }`. L’ancien contrat `{ email, code }` est volontairement refusé. Le code accepte un TOTP ou un code de récupération complet, dans la limite de 64 caractères ; la validation ne restreint plus les codes de récupération à six caractères. + +Chaque tentative prend le challenge par une mise à jour SQL conditionnelle. Un seul vérificateur peut le détenir à la fois, y compris entre processus. Un code incorrect incrémente également le compteur Identity puis libère le challenge ; cinq échecs épuisent le challenge. Un succès consomme définitivement le challenge avant émission des tokens. Un crash pendant la vérification impose de recommencer la connexion ; aucune reprise risquant de doubler l’émission n’est permise. + +Le compte, son verrouillage, l’activation 2FA, la confirmation email configurée et le security stamp sont recontrôlés à la seconde étape. Un changement de mot de passe invalide donc la preuve antérieure. Les codes de récupération sont consommés avec `UPDATE ... WHERE UsedAt IS NULL` et contrôle du nombre de lignes affectées. Aucune exclusion mutuelle en mémoire n’est utilisée pour leur unicité. + +## Politique de session + +Les JWT et cookies portent le security stamp et la date initiale de session. Les anciens tokens/cookies sans ces claims sont refusés : les utilisateurs doivent se reconnecter après livraison. Les tokens de récupération 2FA existants restent compatibles ; seule leur consommation change. + +- Chaque renouvellement vérifie l’existence du compte, son verrouillage, la confirmation email requise, le security stamp et la durée maximale de sept jours depuis la connexion initiale. La rotation conserve cette date et ne prolonge pas la limite absolue. +- Les JWT entrants et les cookies sont revalidés contre le compte à chaque requête ; un JWT encore dans sa durée de validité ne contourne pas le verrouillage. +- Le verrouillage administratif et le changement de rôles changent le security stamp. Les verrouillages automatiques observés dans les parcours mot de passe/2FA font de même. Le déverrouillage ne ressuscite pas les anciennes sessions. +- Les cookies ne sont pas prolongés par l’activité ; leur expiration est bornée à la date initiale + sept jours. La conversion JWT → cookie revalide le compte. +- Les circuits Blazor sont revalidés toutes les minutes avec un nouveau scope de base de données ; les requêtes API refusent immédiatement une identité révoquée. Une opération déjà en cours n’est pas annulée rétroactivement. + +Le handler de refresh et la propagation du cookie appartiennent au scope du circuit, tandis que seuls les transports HTTP sans état sont mutualisés. Les transports n’utilisent pas de cookie jar partagé. Le verrou de refresh appartient à `AuthState`. Après 401, le handler compare le token envoyé au token courant, renouvelle même si le token expiré n’est pas vide, puis ne rejoue qu’une fois. Sans HttpContext, l’URL du refresh reprend l’origine et le port de la requête API effectivement résolue. Un échec terminal efface l’état de session web. + +## Migration et exploitation + +Deux migrations additives sont séparées : `ReconcileExistingAccessSchema` rattrape les tables déjà modélisées `group_camera_accesses` et `UserCameraAccesses`, absentes de l’historique initial ; `AddLoginChallenges` crée `login_challenges`, sa clé d’empreinte, son index d’expiration et sa relation au compte. Aucun mot de passe, secret de challenge ou code de récupération en clair n’est ajouté en base. Appliquer la migration avant de démarrer cette version ; coordonner le changement de contrat des clients 2FA. + +La table des challenges expirés n’a pas encore de tâche périodique de purge. Ces lignes sont inutilisables après expiration ; leur rétention opérationnelle doit être définie avec le lot exploitation. La restauration/mutualisation des clés Data Protection reste une exigence d’exploitation indépendante. + +## Vérification + +Validation locale reprise le 20 octobre 2026 : les sept suites hors navigateur ont d'abord totalisé 1 772 tests réussis, sans échec ni test ignoré : + +| Suite | Réussis | +|---|---:| +| Domain | 179 | +| Application | 502 | +| Agent | 355 | +| API | 2 | +| Web | 352 | +| Infrastructure | 241 | +| Integration | 141 | + +La commande initiale `dotnet test Heimdall.slnx --verbosity minimal` a détecté une erreur CA1001 dans le nouveau test HTTP. La libération des ressources étant déjà assurée par `IAsyncLifetime.DisposeAsync`, une suppression documentée et limitée à cette classe a été ajoutée ; la suite Integration a ensuite été compilée et exécutée séparément avec succès. La suite navigateur est exécutée séparément. + +Le premier passage navigateur a donné 31 réussites et trois échecs sur 34 tests. Deux tests de gestion d'utilisateur cliquaient le premier bouton de la ligne, désormais dédié aux accès caméra ; ils ciblent maintenant le bouton par son nom accessible et le champ par son libellé. Leur relance ciblée réussit. Le nouveau scénario de refresh ouvre explicitement le groupe de navigation avant de cliquer le lien visible. + +La vérification de rotation a ensuite révélé que les durées JWT décimales étaient lues avec la culture de la requête : `0.25` n'était pas interprété comme quinze secondes sous `fr-FR`. Les durées access/refresh utilisent maintenant la culture invariante. Les 18 tests `JwtServiceTests` passent, dont un nouveau test sous culture française. Le test navigateur contrôle également l'expiration du JWT effectivement émis avant d'attendre ; sa relance réussit et confirme la rotation en base, le chargement de la page utilisateurs et le maintien de la session. + +Bilan cumulé : **1 807 tests distincts réussis**, dont **34 scénarios navigateur**, sans test ignoré. Ce bilan combine les suites et les relances ciblées après correction ; il ne représente pas une nouvelle exécution intégrale unique. `git diff --check` est propre. + +Les tests avec Identity réel couvrent le mot de passe, le TOTP et les codes de récupération ; des vérifications PostgreSQL distinctes exercent les mises à jour concurrentes sur connexions indépendantes. Le test de migration vérifie l'absence d'écart entre modèle et snapshot, la montée depuis l'historique précédent, le retour arrière puis la réapplication, en préservant un compte Identity existant. Les tests HTTP vérifient le refus de l'ancien contrat 2FA, le rejeu du challenge et la révocation des JWT/cookies/refresh après verrouillage et changement de rôles. + +Les parcours d’installation/reprise sur appareils PWA réels appartiennent au lot 9. Le présent lot prépare la reprise de session connectée, sans service worker ni cache de données privées. + +Les connexions SignalR métier déjà ouvertes et leurs groupes doivent être traités avec le lot 2 : les contrôles d’entrée JWT/cookie ne réévaluent pas rétroactivement les abonnements existants. La revalidation du circuit Blazor ne remplace pas ce contrôle de diffusion. diff --git a/readme.md b/readme.md index d6001ce..2dd038a 100644 --- a/readme.md +++ b/readme.md @@ -222,7 +222,7 @@ Compte par défaut (dev) : |---------|----------|------|-------------| | POST | `/api/auth/register` | - | Créer un compte | | POST | `/api/auth/login` | - | Connexion | -| POST | `/api/auth/2fa/verify` | JWT | Vérification 2FA | +| POST | `/api/auth/2fa/verify` | Challenge après mot de passe | Vérification TOTP ou code de récupération | | POST | `/api/auth/refresh` | JWT | Rafraîchir token | | GET | `/api/sites` | JWT | Lister les sites | | POST | `/api/sites` | JWT | Créer un site | @@ -256,6 +256,8 @@ Compte par défaut (dev) : | GET | `/api/cameras/{id}/events` | JWT | Événements d'une caméra | | POST | `/api/cameras/discover` | JWT | Découverte de caméras | +Le [contrat de connexion et de session](docs/audits/2026-10-20-lot1-auth-session.md) décrit le challenge 2FA opaque, le renouvellement et la révocation. + --- ## Sécurité diff --git a/src/Heimdall.Application/Auth/AuthHelper.cs b/src/Heimdall.Application/Auth/AuthHelper.cs index 8458a11..3bc28ef 100644 --- a/src/Heimdall.Application/Auth/AuthHelper.cs +++ b/src/Heimdall.Application/Auth/AuthHelper.cs @@ -12,13 +12,18 @@ internal static class AuthHelper AppUser user, IJwtService jwtService, IRolePermissionService rolePermissionService, - UserManager userManager) + UserManager userManager, + DateTime? sessionStarted = null) { var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false); var permissions = rolePermissionService.GetPermissionsForRoles(roles); - var (accessToken, expiresAt) = jwtService.GenerateAccessToken(user, roles, permissions); - var (refreshToken, _) = jwtService.GenerateRefreshToken(user); + var (accessToken, expiresAt) = sessionStarted is null + ? jwtService.GenerateAccessToken(user, roles, permissions) + : jwtService.GenerateAccessToken(user, roles, permissions, sessionStarted.Value); + var (refreshToken, _) = sessionStarted is null + ? jwtService.GenerateRefreshToken(user) + : jwtService.GenerateRefreshToken(user, sessionStarted.Value); return ServiceResult.Success(new AuthResponse( accessToken, diff --git a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs index b98223a..0892deb 100644 --- a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Common; +using Heimdall.Application.Auth.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Common.Persistence; using Heimdall.Application.Services; @@ -17,6 +18,7 @@ public class LoginHandler : IRequestHandler _logger; public LoginHandler( @@ -26,7 +28,8 @@ public class LoginHandler : IRequestHandler logger) + ILogger logger, + IApplicationDbContext db) { _userManager = userManager; _signInService = signInService; @@ -35,6 +38,7 @@ public class LoginHandler : IRequestHandler> Handle(LoginCommand request, CancellationToken ct) @@ -55,29 +59,12 @@ public class LoginHandler : IRequestHandler.Failure("Account locked. Try again later.", 429); } - if (await _userManager.GetTwoFactorEnabledAsync(user)) - { - _logger.LogDebug("Login: 2FA required Email={Email}", request.Email); - var signIn = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false); - if (signIn.ResultType == SignInResultType.LockedOut) - { - _logger.LogWarning("Login: Account locked after 2FA attempt Email={Email}", request.Email); - return ServiceResult.Failure("Account locked. Try again later.", 429); - } - if (signIn.ResultType != SignInResultType.Success) - { - _logger.LogWarning("Login: 2FA failed Email={Email}", request.Email); - return ServiceResult.Unauthorized("Invalid email or password"); - } - - _logger.LogInformation("Login: 2FA passed Email={Email}", request.Email); - return ServiceResult.Success(new AuthResponse( - string.Empty, string.Empty, DateTime.UtcNow, true, - await AuthHelper.MapUserInfoAsync(user, _userManager))); - } - var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false); - if (result.ResultType != SignInResultType.Success) + var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); + if (result.ResultType == SignInResultType.LockedOut) + return ServiceResult.Failure("Account locked. Try again later.", 429); + if (result.ResultType != SignInResultType.Success + && !(result.ResultType == SignInResultType.RequiresTwoFactor && twoFactorEnabled)) { _logger.LogWarning("Login: Password mismatch Email={Email}", request.Email); return ServiceResult.Unauthorized("Invalid email or password"); @@ -91,6 +78,14 @@ public class LoginHandler : IRequestHandler.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403); } + if (twoFactorEnabled) + { + var challengeId = await LoginChallengeService.CreateAsync(_db, user, ct); + return ServiceResult.Success(new AuthResponse( + string.Empty, string.Empty, DateTime.UtcNow, true, + await AuthHelper.MapUserInfoAsync(user, _userManager), challengeId)); + } + _logger.LogInformation("Login: Success Email={Email}", request.Email); return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false); } diff --git a/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs b/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs index 62606eb..8c36b17 100644 --- a/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs @@ -1,4 +1,6 @@ using System.Security.Claims; +using System.Globalization; +using Heimdall.Application.Auth.Services; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; @@ -6,6 +8,7 @@ using Heimdall.Domain.Entities; using MediatR; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Auth.Commands.RefreshToken; @@ -65,11 +68,24 @@ public class RefreshTokenHandler : IRequestHandler.Unauthorized("User not found"); } + if (!await AccountSessionPolicy.IsValidAsync(principal, _userManager, _authData, ct) + || !DateTime.TryParse(principal.FindFirstValue(AccountSessionPolicy.StartedClaim), CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow) + return ServiceResult.Unauthorized("Session revoked or expired"); + _logger.LogInformation("RefreshToken: Success UserId={UserId}", userId); // Revoke the old refresh token (rotation) - await _authData.RevokeRefreshTokenAsync(request.RefreshToken, user.Id, ct).ConfigureAwait(false); + try + { + await _authData.RevokeRefreshTokenAsync(request.RefreshToken, user.Id, ct).ConfigureAwait(false); + } + catch (DbUpdateException) + { + // The unique token-id index arbitrates concurrent rotation between instances. + return ServiceResult.Unauthorized("Refresh token already consumed"); + } - return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false); + return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started).ConfigureAwait(false); } } diff --git a/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs b/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs index a40409d..c28e734 100644 --- a/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs @@ -141,6 +141,9 @@ public class RegisterHandler : IRequestHandler.Failure("Account created. Confirm your email before signing in.", 403); return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false); } diff --git a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faCommand.cs b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faCommand.cs index 465e33f..4e8bdb0 100644 --- a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faCommand.cs +++ b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faCommand.cs @@ -4,4 +4,4 @@ using MediatR; namespace Heimdall.Application.Auth.Commands.Verify2fa; -public record Verify2faCommand(string Email, string Code) : IRequest>; +public record Verify2faCommand(string ChallengeId, string Code) : IRequest>; diff --git a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs index 6dfc8f4..d5cef4e 100644 --- a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs @@ -34,14 +34,19 @@ public class Verify2faHandler : IRequestHandler> Handle(Verify2faCommand request, CancellationToken ct) { - _logger.LogDebug("Verify2fa: Email={Email}", request.Email); + var challenge = await LoginChallengeService.TakeAttemptAsync(_db, request.ChallengeId ?? "", ct); + if (challenge is null) + return ServiceResult.Unauthorized("Invalid or expired challenge"); - var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false); - if (user is null) - { - _logger.LogWarning("Verify2fa: User not found Email={Email}", request.Email); - return ServiceResult.Unauthorized("Invalid request"); - } + var user = await _userManager.FindByIdAsync(challenge.UserId.ToString()); + var emailSetting = await _db.AppSettings.AsNoTracking() + .Where(x => x.Key == "email.confirmation.required").Select(x => x.Value).SingleOrDefaultAsync(ct); + var emailRequired = string.Equals(emailSetting, "true", StringComparison.OrdinalIgnoreCase); + if (user is null || user.SecurityStamp != challenge.SecurityStamp + || !await _userManager.GetTwoFactorEnabledAsync(user) + || await _userManager.IsLockedOutAsync(user) + || (emailRequired && !user.EmailConfirmed)) + return ServiceResult.Unauthorized("Account unavailable"); var isValid = await _userManager.VerifyTwoFactorTokenAsync( user, TokenOptions.DefaultAuthenticatorProvider, request.Code); @@ -52,13 +57,20 @@ public class Verify2faHandler : IRequestHandler.Unauthorized("Invalid 2FA code"); } - _logger.LogInformation("Verify2fa: Recovery code redeemed Email={Email}", request.Email); + _logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId); } - _logger.LogInformation("Verify2fa: Success Email={Email}", request.Email); + if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1) + return ServiceResult.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); } @@ -68,15 +80,8 @@ public class Verify2faHandler : IRequestHandler r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null, ct) - .ConfigureAwait(false); - - if (match is null) - return false; - - match.MarkUsed(); - await _db.SaveChangesAsync(ct).ConfigureAwait(false); - return true; + return await _db.UserRecoveryCodes + .Where(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(r => r.UsedAt, DateTime.UtcNow), ct) == 1; } } diff --git a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faValidator.cs b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faValidator.cs index 21ad83f..546ccf2 100644 --- a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faValidator.cs +++ b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faValidator.cs @@ -6,7 +6,7 @@ public class Verify2faValidator : AbstractValidator { public Verify2faValidator() { - RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256); - RuleFor(x => x.Code).NotEmpty().Length(6).WithMessage("2FA code must be 6 digits"); + RuleFor(x => x.ChallengeId).NotEmpty().Length(64); + RuleFor(x => x.Code).NotEmpty().MaximumLength(64); } } diff --git a/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs b/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs new file mode 100644 index 0000000..bfe0c49 --- /dev/null +++ b/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs @@ -0,0 +1,28 @@ +using System.Security.Claims; +using System.Globalization; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; + +namespace Heimdall.Application.Auth.Services; + +public static class AccountSessionPolicy +{ + public const string StampClaim = "security_stamp"; + public const string StartedClaim = "session_started"; + + public static async Task IsValidAsync(ClaimsPrincipal principal, UserManager users, IAuthDataService data, CancellationToken ct) + { + if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow) + return false; + var id = principal.FindFirstValue(ClaimTypes.NameIdentifier); + var user = id is null ? null : await users.FindByIdAsync(id); + if (user is null || string.IsNullOrEmpty(user.SecurityStamp) + || principal.FindFirstValue(StampClaim) != user.SecurityStamp + || await users.IsLockedOutAsync(user)) return false; + var required = await data.GetSettingValueAsync("email.confirmation.required", ct); + if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) return false; + return true; + } +} diff --git a/src/Heimdall.Application/Auth/Services/LoginChallengeService.cs b/src/Heimdall.Application/Auth/Services/LoginChallengeService.cs new file mode 100644 index 0000000..79346b0 --- /dev/null +++ b/src/Heimdall.Application/Auth/Services/LoginChallengeService.cs @@ -0,0 +1,52 @@ +using System.Security.Cryptography; +using System.Text; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Auth.Services; + +public static class LoginChallengeService +{ + public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + + public static async Task CreateAsync(IApplicationDbContext db, AppUser user, CancellationToken ct) + { + var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + db.GetSet().Add(new LoginChallenge + { + Id = Hash(token), UserId = user.Id, SecurityStamp = user.SecurityStamp ?? "", + ExpiresAt = DateTime.UtcNow.AddMinutes(5) + }); + await db.SaveChangesAsync(ct); + return token; + } + + // Compare-and-swap allocates exactly one attempt to each verifier across instances. + public static async Task TakeAttemptAsync(IApplicationDbContext db, string token, CancellationToken ct) + { + if (token.Length != 64) return null; + var id = Hash(token); + var now = DateTime.UtcNow; + var query = db.GetSet().Where(x => x.Id == id && !x.Consumed && !x.Verifying && x.ExpiresAt > now && x.Attempts < 5); + var challenge = await query.AsNoTracking().SingleOrDefaultAsync(ct); + if (challenge is null) return null; + var updated = await query.Where(x => x.Attempts == challenge.Attempts) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.Attempts, x => x.Attempts + 1).SetProperty(x => x.Verifying, true), ct); + if (updated != 1) return null; + challenge.Attempts++; + return challenge; + } + + public static Task ReleaseAttemptAsync(IApplicationDbContext db, LoginChallenge challenge, CancellationToken ct) => + db.GetSet().Where(x => x.Id == challenge.Id && !x.Consumed && x.Attempts == challenge.Attempts) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.Verifying, false), ct); + + public static Task ConsumeAsync(IApplicationDbContext db, LoginChallenge challenge, CancellationToken ct) + { + var now = DateTime.UtcNow; + return db.GetSet() + .Where(x => x.Id == challenge.Id && !x.Consumed && x.ExpiresAt > now && x.Attempts == challenge.Attempts) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.Consumed, true), ct); + } +} diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs index 6351198..1581238 100644 --- a/src/Heimdall.Application/DTOs/AuthDto.cs +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -4,7 +4,7 @@ public record RegisterRequest(string Email, string Password, string DisplayName) public record LoginRequest(string Email, string Password); -public record Verify2faRequest(string Email, string Code); +public record Verify2faRequest(string ChallengeId, string Code); public record RefreshTokenRequest(string RefreshToken); @@ -13,7 +13,8 @@ public record AuthResponse( string RefreshToken, DateTime ExpiresAt, bool Requires2fa, - UserInfo User); + UserInfo User, + string? ChallengeId = null); public record UserInfo( Guid Id, diff --git a/src/Heimdall.Application/Services/IJwtService.cs b/src/Heimdall.Application/Services/IJwtService.cs index c94ec7e..2f45afc 100644 --- a/src/Heimdall.Application/Services/IJwtService.cs +++ b/src/Heimdall.Application/Services/IJwtService.cs @@ -6,7 +6,9 @@ namespace Heimdall.Application.Services; public interface IJwtService { (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions); + (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions); (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user); + (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted) => GenerateRefreshToken(user); ClaimsPrincipal? ValidateRefreshToken(string refreshToken); string? GetUserIdFromExpiredToken(string token); } diff --git a/src/Heimdall.Application/Users/Commands/AssignRoles/AssignRolesHandler.cs b/src/Heimdall.Application/Users/Commands/AssignRoles/AssignRolesHandler.cs index 47c1b39..539053f 100644 --- a/src/Heimdall.Application/Users/Commands/AssignRoles/AssignRolesHandler.cs +++ b/src/Heimdall.Application/Users/Commands/AssignRoles/AssignRolesHandler.cs @@ -37,6 +37,7 @@ public class AssignRolesHandler : IRequestHandler return ServiceResult.NotFound("User not found"); await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false); + await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false); await _repository.AddAuditLogAsync(null, "UserLocked", "User", command.UserId.ToString(), null, null, ct); diff --git a/src/Heimdall.Domain/Entities/LoginChallenge.cs b/src/Heimdall.Domain/Entities/LoginChallenge.cs new file mode 100644 index 0000000..65ca577 --- /dev/null +++ b/src/Heimdall.Domain/Entities/LoginChallenge.cs @@ -0,0 +1,13 @@ +namespace Heimdall.Domain.Entities; + +/// Short-lived password proof. Only the SHA-256 digest of the opaque token is stored. +public class LoginChallenge +{ + public string Id { get; set; } = ""; + public Guid UserId { get; set; } + public string SecurityStamp { get; set; } = ""; + public DateTime ExpiresAt { get; set; } + public int Attempts { get; set; } + public bool Verifying { get; set; } + public bool Consumed { get; set; } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/LoginChallengeConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/LoginChallengeConfiguration.cs new file mode 100644 index 0000000..3287b3d --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/LoginChallengeConfiguration.cs @@ -0,0 +1,18 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class LoginChallengeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("login_challenges"); + builder.HasKey(x => x.Id); + builder.Property(x => x.Id).HasMaxLength(64); + builder.Property(x => x.SecurityStamp).HasMaxLength(256); + builder.HasIndex(x => x.ExpiresAt); + builder.HasOne().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.Designer.cs new file mode 100644 index 0000000..2fb79b8 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.Designer.cs @@ -0,0 +1,2558 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261020002409_ReconcileExistingAccessSchema")] + partial class ReconcileExistingAccessSchema + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.cs b/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.cs new file mode 100644 index 0000000..483911a --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020002409_ReconcileExistingAccessSchema.cs @@ -0,0 +1,107 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class ReconcileExistingAccessSchema : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "group_camera_accesses", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + GroupId = table.Column(type: "uuid", nullable: false), + CameraId = table.Column(type: "uuid", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => + { + table.PrimaryKey("PK_group_camera_accesses", x => x.Id); + table.ForeignKey( + name: "FK_group_camera_accesses_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_group_camera_accesses_groups_GroupId", + column: x => x.GroupId, + principalTable: "groups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "UserCameraAccesses", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + CameraId = table.Column(type: "uuid", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + Id = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UserCameraAccesses", x => new { x.UserId, x.SiteId, x.CameraId }); + table.ForeignKey( + name: "FK_UserCameraAccesses_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserCameraAccesses_sites_SiteId", + column: x => x.SiteId, + principalTable: "sites", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserCameraAccesses_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_group_camera_accesses_CameraId", + table: "group_camera_accesses", + column: "CameraId"); + + migrationBuilder.CreateIndex( + name: "IX_group_camera_accesses_GroupId_CameraId", + table: "group_camera_accesses", + columns: new[] { "GroupId", "CameraId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_UserCameraAccesses_CameraId", + table: "UserCameraAccesses", + column: "CameraId"); + + migrationBuilder.CreateIndex( + name: "IX_UserCameraAccesses_SiteId", + table: "UserCameraAccesses", + column: "SiteId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "group_camera_accesses"); + + migrationBuilder.DropTable( + name: "UserCameraAccesses"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.Designer.cs new file mode 100644 index 0000000..34cc5b5 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.Designer.cs @@ -0,0 +1,2602 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261020002410_AddLoginChallenges")] + partial class AddLoginChallenges + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.cs b/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.cs new file mode 100644 index 0000000..72c031b --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020002410_AddLoginChallenges.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +public partial class AddLoginChallenges : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "login_challenges", + columns: table => new + { + Id = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + SecurityStamp = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + ExpiresAt = table.Column(type: "timestamp with time zone", nullable: false), + Attempts = table.Column(type: "integer", nullable: false), + Verifying = table.Column(type: "boolean", nullable: false), + Consumed = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_login_challenges", x => x.Id); + table.ForeignKey( + name: "FK_login_challenges_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_login_challenges_ExpiresAt", + table: "login_challenges", + column: "ExpiresAt"); + + migrationBuilder.CreateIndex( + name: "IX_login_challenges_UserId", + table: "login_challenges", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "login_challenges"); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 06d9c53..fa66152 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1282,6 +1282,38 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("groups", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => { b.Property("Id") @@ -1359,6 +1391,41 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("license_plates", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => { b.Property("Id") @@ -1777,6 +1844,35 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("user_cameras", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => { b.Property("UserId") @@ -2222,6 +2318,25 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("DiscoveryResult"); }); + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => { b.HasOne("Heimdall.Domain.Entities.Person", "Person") @@ -2250,6 +2365,15 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("Vehicle"); }); + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => { b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") @@ -2298,6 +2422,32 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("User"); }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => { b.HasOne("Heimdall.Domain.Entities.Group", "Group") @@ -2414,6 +2564,8 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("Credentials"); b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); }); modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => @@ -2423,6 +2575,8 @@ namespace Heimdall.Infrastructure.Migrations modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => { + b.Navigation("GroupCameraAccesses"); + b.Navigation("UserGroups"); }); diff --git a/src/Heimdall.Infrastructure/Security/AuthSignInService.cs b/src/Heimdall.Infrastructure/Security/AuthSignInService.cs index 1b7c9f1..426bf87 100644 --- a/src/Heimdall.Infrastructure/Security/AuthSignInService.cs +++ b/src/Heimdall.Infrastructure/Security/AuthSignInService.cs @@ -15,7 +15,9 @@ public class AuthSignInService : IAuthSignInService public async Task PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure) { - var result = await _signInManager.PasswordSignInAsync(user, password, false, lockoutOnFailure).ConfigureAwait(false); + var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure).ConfigureAwait(false); + if (result.IsLockedOut) + await _signInManager.UserManager.UpdateSecurityStampAsync(user).ConfigureAwait(false); return result switch { { Succeeded: true } => new SignInServiceResult(SignInResultType.Success), diff --git a/src/Heimdall.Infrastructure/Security/JwtService.cs b/src/Heimdall.Infrastructure/Security/JwtService.cs index 6c1e035..ce6153f 100644 --- a/src/Heimdall.Infrastructure/Security/JwtService.cs +++ b/src/Heimdall.Infrastructure/Security/JwtService.cs @@ -1,4 +1,6 @@ +using Heimdall.Application.Auth.Services; using System.IdentityModel.Tokens.Jwt; +using System.Globalization; using System.Security.Claims; using System.Text; using Heimdall.Application.Services; @@ -21,18 +23,23 @@ public class JwtService : IJwtService } public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions) + => GenerateAccessToken(user, roles, permissions, DateTime.UtcNow); + + public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions, DateTime sessionStarted) { var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(GetJwtKey())); var expiresAt = DateTime.UtcNow.AddMinutes( - double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], out var minutes) ? minutes : 15); + double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], NumberStyles.Float, CultureInfo.InvariantCulture, out var minutes) ? minutes : 15); var claims = new List { new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), + new(AccountSessionPolicy.StampClaim, user.SecurityStamp ?? ""), new(JwtRegisteredClaimNames.Email, user.Email ?? ""), new(JwtRegisteredClaimNames.Name, user.DisplayName), + new(AccountSessionPolicy.StartedClaim, sessionStarted.ToString("O")), }; // Add individual role claims so [Authorize(Roles = "Admin")] works @@ -55,18 +62,24 @@ public class JwtService : IJwtService } public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user) + => GenerateRefreshToken(user, DateTime.UtcNow); + + public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted) { var refreshKeyValue = GetJwtRefreshKey(); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshKeyValue)); var expiresAt = DateTime.UtcNow.AddDays( - double.TryParse(_configuration["Jwt:RefreshTokenExpiryDays"], out var days) ? days : 7); + double.TryParse(_configuration["Jwt:RefreshTokenExpiryDays"], NumberStyles.Float, CultureInfo.InvariantCulture, out var days) ? days : 7); + expiresAt = new[] { expiresAt, sessionStarted.AddDays(7) }.Min(); var tokenId = Guid.NewGuid().ToString(); // unique jti for DB revocation tracking var claims = new List { new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), + new(AccountSessionPolicy.StampClaim, user.SecurityStamp ?? ""), new(JwtRegisteredClaimNames.Jti, tokenId), + new(AccountSessionPolicy.StartedClaim, sessionStarted.ToString("O")), new(JwtRegisteredClaimNames.Email, user.Email ?? ""), }; @@ -100,9 +113,7 @@ public class JwtService : IJwtService ClockSkew = TimeSpan.Zero }, out _); } - catch (Exception ex) when (ex is SecurityTokenExpiredException - or SecurityTokenInvalidSignatureException - or SecurityTokenInvalidIssuerException + catch (Exception ex) when (ex is SecurityTokenException or ArgumentException) { _logger.LogWarning("Refresh token validation failed: {ExceptionType} — {Message}", @@ -149,9 +160,7 @@ public class JwtService : IJwtService return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value; } - catch (Exception ex) when (ex is SecurityTokenExpiredException - or SecurityTokenInvalidSignatureException - or SecurityTokenInvalidIssuerException + catch (Exception ex) when (ex is SecurityTokenException or ArgumentException) { _logger.LogWarning("Failed to read expired token: {ExceptionType} — {Message}", diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index 89fbd2e..3d79cd1 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -85,6 +85,7 @@ @code { + private string _challengeId = ""; private string _email = ""; private string _password = ""; private string _twoFactorCode = ""; @@ -142,6 +143,8 @@ // Check if 2FA is required if (result.Requires2fa) { + _challengeId = result.ChallengeId ?? ""; + _password = ""; _requires2fa = true; _loading = false; Logger.LogInformation("2FA required for {Email}", _email); @@ -173,7 +176,7 @@ try { - var result = await Api.Verify2faAsync(_email, _twoFactorCode.Trim()); + var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim()); if (result is null) { Logger.LogWarning("2FA verification failed for {Email}", _email); diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index 0b4b7aa..998a90a 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -85,17 +85,17 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct) { - _logger.LogInformation("2FA verification attempt for {Email}", request.Email); - var command = new Verify2faCommand(request.Email, request.Code); + _logger.LogInformation("2FA verification attempt"); + var command = new Verify2faCommand(request.ChallengeId, request.Code); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { - _logger.LogInformation("2FA verification successful for {Email}", request.Email); + _logger.LogInformation("2FA verification successful"); return Ok(result.Data); } - _logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error); + _logger.LogWarning("2FA verification failed: {Error}", result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index d60ed06..140dc9c 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -530,7 +530,7 @@ public partial class Program options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); - options.SlidingExpiration = true; + options.SlidingExpiration = false; }); } @@ -557,9 +557,19 @@ public partial class Program builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); builder.Services.AddScoped(); - builder.Services.AddTransient(); + builder.Services.AddScoped(sp => + { + var handler = ActivatorUtilities.CreateInstance(sp); + var origin = ActivatorUtilities.CreateInstance(sp); + origin.InnerHandler = sp.GetRequiredService().CreateHandler("HeimdallApi"); + handler.InnerHandler = origin; + return handler; + }); builder.Services.AddTransient(); + builder.Services.AddHttpClient("HeimdallRefresh") + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false }); + var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration); var apiBaseUrl = apiBaseUrlConfigured ? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)! @@ -569,9 +579,7 @@ public partial class Program var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/"; client.BaseAddress = new Uri(baseUrl); client.Timeout = TimeSpan.FromSeconds(30); - }) - .AddHttpMessageHandler() - .AddHttpMessageHandler(); + }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false }); if (apiBaseUrlConfigured) Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)"); @@ -614,11 +622,16 @@ public partial class Program // In production with HTTPS, the cookie will still be secure options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); - options.SlidingExpiration = true; + options.SlidingExpiration = false; // Add logging events options.Events = new CookieAuthenticationEvents { + OnValidatePrincipal = async context => + { + if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext)) + context.RejectPrincipal(); + }, OnRedirectToLogin = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); @@ -647,17 +660,16 @@ public partial class Program } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; - }, - OnValidatePrincipal = context => - { - var logger = context.HttpContext.RequestServices.GetRequiredService>(); - logger.LogDebug("Validating principal for {Path}", context.HttpContext.Request.Path); - return Task.CompletedTask; } }; }); } + private static Task ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) => + Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal, + http.RequestServices.GetRequiredService>(), + http.RequestServices.GetRequiredService(), http.RequestAborted); + private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience) { authBuilder.AddJwtBearer("JwtBearer", options => @@ -665,6 +677,11 @@ public partial class Program options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience); options.Events = new JwtBearerEvents { + OnTokenValidated = async context => + { + if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext)) + context.Fail("Session revoked"); + }, OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; @@ -861,6 +878,8 @@ public partial class Program var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(request.AccessToken, GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _); + if (!await ValidateAccountSessionAsync(principal, httpContext)) + return Results.Unauthorized(); var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; var email = principal.FindFirst(ClaimTypes.Email)?.Value; var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; @@ -873,13 +892,23 @@ public partial class Program new(ClaimTypes.Email, email), new(ClaimTypes.Name, displayName ?? email), }; + claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim, + principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim)!)); + claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim, + principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!)); foreach (var role in principal.FindAll(ClaimTypes.Role)) claims.Add(new Claim(ClaimTypes.Role, role.Value)); foreach (var permission in principal.FindAll("permission")) claims.Add(new Claim("permission", permission.Value)); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); - await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); + await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), + new AuthenticationProperties + { + IsPersistent = false, AllowRefresh = false, + ExpiresUtc = DateTimeOffset.Parse(principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!, + System.Globalization.CultureInfo.InvariantCulture).AddDays(7) + }); return Results.Ok(); } catch (SecurityTokenExpiredException) { return Results.Unauthorized(); } diff --git a/src/Heimdall.Web/Services/AuthState.cs b/src/Heimdall.Web/Services/AuthState.cs index 1ab7e90..e75e0b1 100644 --- a/src/Heimdall.Web/Services/AuthState.cs +++ b/src/Heimdall.Web/Services/AuthState.cs @@ -9,6 +9,8 @@ public class AuthState /// Nom du cookie d'authentification ASP.NET Core (schéma Cookies). public const string AuthCookieName = ".Heimdall.Auth"; + public SemaphoreSlim RefreshLock { get; } = new(1, 1); + public string? AccessToken { get; set; } public string? RefreshToken { get; set; } public UserInfo? User { get; set; } @@ -83,7 +85,8 @@ public record AuthResponse( [property: JsonPropertyName("refreshToken")] string RefreshToken, [property: JsonPropertyName("expiresAt")] DateTime ExpiresAt, [property: JsonPropertyName("requires2fa")] bool Requires2fa, - [property: JsonPropertyName("user")] UserInfo? User); + [property: JsonPropertyName("user")] UserInfo? User, + [property: JsonPropertyName("challengeId")] string? ChallengeId = null); public record UserInfo( [property: JsonPropertyName("id")] Guid Id, diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index cc9039d..7dc2fbe 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -6,10 +6,11 @@ using Heimdall.Application.DTOs; namespace Heimdall.Web.Services; -public class HeimdallApiClient +public class HeimdallApiClient : IDisposable { private readonly IHttpClientFactory _httpFactory; private readonly AuthState _authState; + private readonly HttpClient? _sessionClient; private const string InvalidServerResponse = "Réponse du serveur invalide."; private static readonly JsonSerializerOptions Json = new() @@ -18,18 +19,32 @@ public class HeimdallApiClient PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; - public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState) + public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState, TokenRefreshHandler? sessionHandler = null) { _httpFactory = httpFactory; _authState = authState; + if (sessionHandler is not null) + { + using var configured = httpFactory.CreateClient("HeimdallApi"); + _sessionClient = new HttpClient(sessionHandler, disposeHandler: false) + { + BaseAddress = configured.BaseAddress, + Timeout = configured.Timeout + }; + } + } + + public void Dispose() + { + _sessionClient?.Dispose(); + GC.SuppressFinalize(this); } private HttpClient CreateClient() { - var client = _httpFactory.CreateClient("HeimdallApi"); - if (_authState.AccessToken is not null) - client.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue("Bearer", _authState.AccessToken); + var client = _sessionClient ?? _httpFactory.CreateClient("HeimdallApi"); + client.DefaultRequestHeaders.Authorization = string.IsNullOrEmpty(_authState.AccessToken) + ? null : new AuthenticationHeaderValue("Bearer", _authState.AccessToken); return client; } @@ -220,10 +235,10 @@ public class HeimdallApiClient return result; } - public async Task Verify2faAsync(string email, string code) + public async Task Verify2faAsync(string challengeId, string code) { var client = CreateClient(); - var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { email, code }); + var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { challengeId, code }); if (!response.IsSuccessStatusCode) return null; var result = await response.Content.ReadFromJsonAsync(Json); if (result is not null) _lastAuthResponse = result; diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs index 2076232..cc2ef2d 100644 --- a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs +++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs @@ -1,28 +1,55 @@ using System.Security.Claims; +using System.IdentityModel.Tokens.Jwt; +using Heimdall.Application.Auth.Services; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; using Heimdall.Infrastructure.Security; namespace Heimdall.Web.Services; -public class HeimdallAuthStateProvider : AuthenticationStateProvider +public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStateProvider { + private readonly IServiceScopeFactory? _scopeFactory; private readonly ProtectedSessionStorage _storage; private readonly AuthState _authState; private readonly IHttpContextAccessor _httpContextAccessor; + private bool _restoredFromStorage; private const string StorageKey = "heimdall_auth"; + public HeimdallAuthStateProvider(ProtectedSessionStorage storage, AuthState authState, IHttpContextAccessor httpContextAccessor) + : this(storage, authState, httpContextAccessor, null) { } + public HeimdallAuthStateProvider( ProtectedSessionStorage storage, AuthState authState, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor, IServiceScopeFactory? scopeFactory) + : base(NullLoggerFactory.Instance) { + _scopeFactory = scopeFactory; _storage = storage; _authState = authState; _httpContextAccessor = httpContextAccessor; } + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1); + + protected override async Task ValidateAuthenticationStateAsync(AuthenticationState state, CancellationToken cancellationToken) + { + if (_scopeFactory is null) return false; + await using var scope = _scopeFactory.CreateAsyncScope(); + var valid = await AccountSessionPolicy.IsValidAsync(state.User, + scope.ServiceProvider.GetRequiredService>(), + scope.ServiceProvider.GetRequiredService(), cancellationToken); + if (!valid) await NotifyLogoutAsync(); + return valid; + } + public override async Task GetAuthenticationStateAsync() { // 1) Interactive circuit: the auth response is persisted in the browser @@ -42,8 +69,16 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider if (result.Success && result.Value is not null) { var authResponse = result.Value; + var state = CreateAuthenticationState(authResponse); + if (_scopeFactory is not null && !await ValidateAuthenticationStateAsync(state, CancellationToken.None)) + return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); _authState.Login(authResponse); - return CreateAuthenticationState(authResponse); + if (!_restoredFromStorage) + { + _restoredFromStorage = true; + SetAuthenticationState(Task.FromResult(state)); + } + return state; } } catch @@ -85,11 +120,13 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider public virtual async Task NotifyLogoutAsync() { + _authState.Logout(); if (_httpContextAccessor.HttpContext is null) { - await _storage.DeleteAsync(StorageKey); + try { await _storage.DeleteAsync(StorageKey); } + catch (Microsoft.JSInterop.JSDisconnectedException) { } + catch (InvalidOperationException) { } // Revalidation may run while the circuit is disconnected. } - _authState.Logout(); NotifyAuthenticationStateChanged( Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())))); } @@ -107,6 +144,13 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider new(ClaimTypes.AuthenticationMethod, "Bearer") }; + if (new JwtSecurityTokenHandler().CanReadToken(response.AccessToken)) + { + var token = new JwtSecurityTokenHandler().ReadJwtToken(response.AccessToken); + foreach (var claim in token.Claims.Where(c => c.Type == AccountSessionPolicy.StampClaim || c.Type == AccountSessionPolicy.StartedClaim)) + claims.Add(claim); + } + foreach (var role in response.User.Roles ?? []) claims.Add(new Claim(ClaimTypes.Role, role)); diff --git a/src/Heimdall.Web/Services/TokenRefreshHandler.cs b/src/Heimdall.Web/Services/TokenRefreshHandler.cs index 2c9b1f8..6e95991 100644 --- a/src/Heimdall.Web/Services/TokenRefreshHandler.cs +++ b/src/Heimdall.Web/Services/TokenRefreshHandler.cs @@ -13,8 +13,8 @@ namespace Heimdall.Web.Services; public class TokenRefreshHandler : DelegatingHandler { private readonly AuthState _authState; + private readonly IHttpClientFactory? _clientFactory; private readonly HeimdallAuthStateProvider _authStateProvider; - private readonly IHttpContextAccessor _httpContextAccessor; private readonly IConfiguration _configuration; private static readonly JsonSerializerOptions Json = new() { @@ -22,25 +22,23 @@ public class TokenRefreshHandler : DelegatingHandler PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; - /// Prevents concurrent refresh storms when multiple requests fail at once. - private static readonly SemaphoreSlim _refreshLock = new(1, 1); - public TokenRefreshHandler( AuthState authState, HeimdallAuthStateProvider authStateProvider, IHttpContextAccessor httpContextAccessor, - IConfiguration configuration) + IConfiguration configuration, IHttpClientFactory? clientFactory = null) { + _clientFactory = clientFactory; _authState = authState; _authStateProvider = authStateProvider; - _httpContextAccessor = httpContextAccessor; _configuration = configuration; } protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { - // Clone the request so we can retry it + var failedToken = request.Headers.Authorization?.Parameter; + using var retryRequest = await CloneHttpRequestMessageAsync(request); var response = await base.SendAsync(request, cancellationToken); // Only intercept 401 responses for the Heimdall API @@ -51,7 +49,7 @@ public class TokenRefreshHandler : DelegatingHandler } // Try to refresh the token - var refreshed = await TryRefreshTokenAsync(cancellationToken); + var refreshed = await TryRefreshTokenAsync(failedToken, request.RequestUri!, cancellationToken); if (!refreshed) { // Refresh failed — logout user @@ -60,31 +58,35 @@ public class TokenRefreshHandler : DelegatingHandler } // Retry the original request with the new access token - var retryRequest = await CloneHttpRequestMessageAsync(request); retryRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authState.AccessToken); response.Dispose(); - return await base.SendAsync(retryRequest, cancellationToken); + var retried = await base.SendAsync(retryRequest, cancellationToken); + if (retried.StatusCode == System.Net.HttpStatusCode.Unauthorized) + await _authStateProvider.NotifyLogoutAsync(); + return retried; } - private async Task TryRefreshTokenAsync(CancellationToken cancellationToken) + private async Task TryRefreshTokenAsync(string? failedToken, Uri apiUri, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(_authState.RefreshToken)) return false; - await _refreshLock.WaitAsync(cancellationToken); + await _authState.RefreshLock.WaitAsync(cancellationToken); try { // Double-check: another thread might have refreshed already - if (!string.IsNullOrEmpty(_authState.AccessToken)) + if (!string.IsNullOrEmpty(_authState.AccessToken) && _authState.AccessToken != failedToken) return true; // Create a raw HttpClient (NOT the "HeimdallApi" named client which // includes this handler — would cause an infinite loop). - var baseUrl = ApiBaseUrlResolver.Resolve(_httpContextAccessor, _configuration); - using var rawClient = new HttpClient { BaseAddress = new Uri(baseUrl) }; - var response = await rawClient.PostAsJsonAsync( + var baseUrl = ApiBaseUrlResolver.ResolveConfigured(_configuration) + ?? apiUri.GetLeftPart(UriPartial.Authority) + "/"; + using var rawClient = _clientFactory?.CreateClient("HeimdallRefresh") ?? new HttpClient(); + rawClient.BaseAddress = new Uri(baseUrl); + using var response = await rawClient.PostAsJsonAsync( "api/auth/refresh", new { refreshToken = _authState.RefreshToken }, cancellationToken); @@ -102,13 +104,17 @@ public class TokenRefreshHandler : DelegatingHandler await _authStateProvider.NotifyLoginAsync(result); return true; } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch { return false; } finally { - _refreshLock.Release(); + _authState.RefreshLock.Release(); } } @@ -119,8 +125,8 @@ public class TokenRefreshHandler : DelegatingHandler { var contentBytes = await request.Content.ReadAsByteArrayAsync(); clone.Content = new ByteArrayContent(contentBytes); - if (request.Content.Headers.ContentType is not null) - clone.Content.Headers.ContentType = request.Content.Headers.ContentType; + foreach (var (key, values) in request.Content.Headers) + clone.Content.Headers.TryAddWithoutValidation(key, values); } foreach (var (key, value) in request.Headers) diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs index f90e8a4..a44ccc6 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs @@ -2,6 +2,8 @@ using System.Security.Claims; using Heimdall.Application.Auth.Commands.Login; using Heimdall.Application.DTOs; using Heimdall.Application.Services; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Microsoft.AspNetCore.Identity; using Heimdall.Application.Common.Persistence; @@ -32,7 +34,14 @@ public class LoginHandlerTests _logger = Substitute.For>(); _userRepository = Substitute.For(); _authData = Substitute.For(); - _handler = new LoginHandler(_userManager, _signInService, _jwtService, _rolePermissionService, _userRepository, _authData, _logger); + _handler = new LoginHandler(_userManager, _signInService, _jwtService, _rolePermissionService, _userRepository, _authData, _logger, CreateDb()); + } + + private static IApplicationDbContext CreateDb() + { + var db = Substitute.For(); + db.GetSet().Returns(MockDbSetHelper.CreateFor()); + return db; } [Fact] diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs index fdce098..f951e0a 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs @@ -33,15 +33,15 @@ public class RefreshTokenHandlerTests [Fact] public async Task Refresh_with_valid_token_should_return_new_tokens() { - var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", DisplayName = "Test" }; - var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim("jti", "token-id")])); + var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", DisplayName = "Test", SecurityStamp = "stamp" }; + var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim("jti", "token-id"), new Claim("security_stamp", "stamp"), new Claim("session_started", DateTime.UtcNow.ToString("O"))])); _jwtService.ValidateRefreshToken("valid-token").Returns(principal); _authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any()).Returns(false); _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); _userManager.GetRolesAsync(user).Returns(["Viewer"]); - _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>()) + _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>(), Arg.Any()) .Returns(("new-access-token", DateTime.UtcNow.AddHours(1))); - _jwtService.GenerateRefreshToken(user).Returns(("new-refresh-token", DateTime.UtcNow.AddDays(7))); + _jwtService.GenerateRefreshToken(user, Arg.Any()).Returns(("new-refresh-token", DateTime.UtcNow.AddDays(7))); _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); var result = await _handler.Handle(new RefreshTokenCommand("valid-token"), CancellationToken.None); @@ -79,7 +79,7 @@ public class RefreshTokenHandlerTests { var userId = Guid.NewGuid(); var principal = new ClaimsPrincipal(new ClaimsIdentity([ - new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim("jti", "token-id")])); + new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim("jti", "token-id"), new Claim("security_stamp", "stamp"), new Claim("session_started", DateTime.UtcNow.ToString("O"))])); _jwtService.ValidateRefreshToken("token").Returns(principal); _authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any()).Returns(false); _userManager.FindByIdAsync(userId.ToString()).Returns((AppUser?)null); diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs index 9ef978a..f7a1822 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs @@ -34,88 +34,14 @@ public class Verify2faHandlerTests _handler = new Verify2faHandler(_userManager, _jwtService, _rolePermissionService, _db, _logger); } - private AppUser SetupUser(string email) + [Theory] + [InlineData("")] + [InlineData("test@test.com")] + [InlineData("123456")] + public async Task Verify2fa_without_password_challenge_is_rejected(string proof) { - var user = new AppUser { Id = Guid.NewGuid(), UserName = email, Email = email, DisplayName = "Test" }; - _userManager.FindByEmailAsync(email).Returns(user); - _userManager.GetRolesAsync(user).Returns(["Viewer"]); - _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>()) - .Returns(("access-token", DateTime.UtcNow.AddHours(1))); - _jwtService.GenerateRefreshToken(user).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); - _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); - return user; - } - - [Fact] - public async Task Verify2fa_with_valid_totp_should_return_success() - { - var user = SetupUser("test@test.com"); - _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, "123456") - .Returns(true); - - var result = await _handler.Handle(new Verify2faCommand("test@test.com", "123456"), CancellationToken.None); - - result.IsSuccess.ShouldBeTrue(); - result.Data!.AccessToken.ShouldBe("access-token"); - } - - [Fact] - public async Task Verify2fa_with_recovery_code_should_redeem_and_return_success() - { - var user = SetupUser("test@test.com"); - var plainCode = "ABC12"; - _recoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(plainCode))); - _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, plainCode) - .Returns(false); - - var result = await _handler.Handle(new Verify2faCommand("test@test.com", plainCode), CancellationToken.None); - - result.IsSuccess.ShouldBeTrue(); - result.Data!.AccessToken.ShouldBe("access-token"); - - // Usage unique : le code est marqué utilisé - var stored = _recoveryCodes.Single(); - stored.UsedAt.ShouldNotBeNull(); - } - - [Fact] - public async Task Verify2fa_with_invalid_code_should_return_unauthorized() - { - var user = SetupUser("test@test.com"); - _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, "000000") - .Returns(false); - - var result = await _handler.Handle(new Verify2faCommand("test@test.com", "000000"), CancellationToken.None); - - result.IsSuccess.ShouldBeFalse(); - result.StatusCode.ShouldBe(401); - } - - [Fact] - public async Task Verify2fa_with_unknown_user_should_return_unauthorized() - { - _userManager.FindByEmailAsync("unknown@test.com").Returns((AppUser?)null); - - var result = await _handler.Handle(new Verify2faCommand("unknown@test.com", "123456"), CancellationToken.None); - - result.IsSuccess.ShouldBeFalse(); - result.StatusCode.ShouldBe(401); - } - - [Fact] - public async Task Verify2fa_recovery_code_cannot_be_reused() - { - var user = SetupUser("test@test.com"); - var plainCode = "ABC12"; - var code = new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(plainCode)); - code.MarkUsed(); // déjà consommé - _recoveryCodes.Add(code); - _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, plainCode) - .Returns(false); - - var result = await _handler.Handle(new Verify2faCommand("test@test.com", plainCode), CancellationToken.None); - - result.IsSuccess.ShouldBeFalse(); + var result = await _handler.Handle(new Verify2faCommand(proof, "123456"), CancellationToken.None); result.StatusCode.ShouldBe(401); + await _userManager.DidNotReceiveWithAnyArgs().VerifyTwoFactorTokenAsync(null!, null!, null!); } } diff --git a/tests/Heimdall.E2E.Tests/Pages/SessionRefreshTests.cs b/tests/Heimdall.E2E.Tests/Pages/SessionRefreshTests.cs new file mode 100644 index 0000000..9bf7961 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/SessionRefreshTests.cs @@ -0,0 +1,37 @@ +using Heimdall.Infrastructure.Data; +using System.IdentityModel.Tokens.Jwt; +using System.Text.Json; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Playwright; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +public sealed class SessionRefreshTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres) +{ + [Fact] + public async Task Active_blazor_session_refreshes_expired_nonempty_jwt_without_http_context() + { + App.Configuration["Jwt:AccessTokenExpiryMinutes"] = "0.25"; + var signinRequest = Page.WaitForRequestAsync(r => r.Url.EndsWith("/_auth/signin", StringComparison.Ordinal)); + await LoginViaUiAsync(); + using var payload = JsonDocument.Parse((await signinRequest).PostData!); + var access = new JwtSecurityTokenHandler().ReadJwtToken(payload.RootElement.GetProperty("accessToken").GetString()); + (access.ValidTo - DateTime.UtcNow).TotalSeconds.ShouldBeInRange(0, 16); + await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 }); + int before; + using (var scope = App.Services.CreateScope()) + before = await scope.ServiceProvider.GetRequiredService().RevokedRefreshTokens.CountAsync(); + + await Task.Delay(TimeSpan.FromSeconds(17)); + App.Configuration["Jwt:AccessTokenExpiryMinutes"] = "15"; + await Page.GetByRole(AriaRole.Button, new() { Name = "Gestion des utilisateurs" }).ClickAsync(); + await Page.Locator("a[href='/users']:visible").First.ClickAsync(); + await Page.WaitForSelectorAsync($"text={AdminEmail}", new() { Timeout = 15000 }); + Page.Url.ShouldNotContain("/login"); + using var after = App.Services.CreateScope(); + (await after.ServiceProvider.GetRequiredService().RevokedRefreshTokens.CountAsync()).ShouldBeGreaterThan(before); + } +} diff --git a/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs index 8a42cd0..a42c0a8 100644 --- a/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs @@ -110,13 +110,12 @@ public class UserManagementTests : E2ETestBase // Open the edit dialog via the pencil icon in the user row var row = Page.Locator($"tr:has-text('{email}')"); - await row.Locator("button").First.ClickAsync(); + await row.GetByRole(AriaRole.Button, new() { Name = "Modifier l'utilisateur", Exact = true }).ClickAsync(); // Rename + grant Supervisor (scope to the edit dialog) var dialog = Page.Locator(".mud-dialog"); await dialog.WaitForAsync(new() { Timeout = 10000 }); - // The display-name field is the first text input in the dialog - var nameInput = dialog.Locator("input:not([type='password'])").First; + var nameInput = dialog.GetByLabel("Nom d'affichage", new() { Exact = true }); await nameInput.WaitForAsync(new() { Timeout = 10000 }); await nameInput.FillAsync("Après Modification"); await dialog.Locator("label:has-text('Supervisor')").ClickAsync(); @@ -146,7 +145,7 @@ public class UserManagementTests : E2ETestBase await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 20000 }); var row = Page.Locator($"tr:has-text('{email}')"); - await row.Locator("button").First.ClickAsync(); + await row.GetByRole(AriaRole.Button, new() { Name = "Modifier l'utilisateur", Exact = true }).ClickAsync(); var dialog = Page.Locator(".mud-dialog"); await dialog.WaitForAsync(new() { Timeout = 10000 }); diff --git a/tests/Heimdall.Infrastructure.Tests/AuthMigrationCompatibilityTests.cs b/tests/Heimdall.Infrastructure.Tests/AuthMigrationCompatibilityTests.cs new file mode 100644 index 0000000..47d4dd5 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/AuthMigrationCompatibilityTests.cs @@ -0,0 +1,55 @@ +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +[Collection("PostgresInfra")] +public class AuthMigrationCompatibilityTests(PostgreSqlContainerFixture postgres) +{ + [Fact] + public async Task Upgrade_and_rollback_preserve_existing_identity_accounts() + { + var database = $"auth_migration_{Guid.NewGuid():N}"; + await using var admin = new NpgsqlConnection(postgres.ConnectionString); + await admin.OpenAsync(); + await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", admin)) + await create.ExecuteNonQueryAsync(); + var connectionString = new NpgsqlConnectionStringBuilder(postgres.ConnectionString) { Database = database }.ConnectionString; + try + { + var options = new DbContextOptionsBuilder().UseNpgsql(connectionString).Options; + await using var db = new AppDbContext(options, new AuditInterceptor()); + db.Database.HasPendingModelChanges().ShouldBeFalse(); + var prior = db.Database.GetMigrations().Last(x => string.CompareOrdinal(x, "20261020002409") < 0); + var migrator = db.GetService(); + await migrator.MigrateAsync(prior); + var user = new AppUser { Id = Guid.NewGuid(), Email = "existing@example.test", UserName = "existing", SecurityStamp = "preserved" }; + db.Users.Add(user); + await db.SaveChangesAsync(); + await migrator.MigrateAsync(); + (await db.Users.AsNoTracking().SingleAsync()).SecurityStamp.ShouldBe("preserved"); + db.Set().Add(new LoginChallenge + { + Id = new string('a', 64), UserId = user.Id, SecurityStamp = user.SecurityStamp, ExpiresAt = DateTime.UtcNow.AddMinutes(5) + }); + await db.SaveChangesAsync(); + await migrator.MigrateAsync(prior); + (await db.Users.AsNoTracking().SingleAsync()).Id.ShouldBe(user.Id); + await migrator.MigrateAsync(); + (await db.Set().CountAsync()).ShouldBe(0); + } + finally + { + NpgsqlConnection.ClearAllPools(); + await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", admin); + await drop.ExecuteNonQueryAsync(); + } + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AuthSignInServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AuthSignInServiceTests.cs index 1e77d66..8bf6e8e 100644 --- a/tests/Heimdall.Infrastructure.Tests/AuthSignInServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AuthSignInServiceTests.cs @@ -47,7 +47,7 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "password", false, false) + signInManager.CheckPasswordSignInAsync(user, "password", false) .Returns(SignInResult.Success); var service = new AuthSignInService(signInManager); @@ -61,7 +61,7 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "wrong", false, false) + signInManager.CheckPasswordSignInAsync(user, "wrong", false) .Returns(SignInResult.Failed); var service = new AuthSignInService(signInManager); @@ -75,7 +75,7 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "password", false, true) + signInManager.CheckPasswordSignInAsync(user, "password", true) .Returns(SignInResult.LockedOut); var service = new AuthSignInService(signInManager); @@ -89,7 +89,7 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "password", false, false) + signInManager.CheckPasswordSignInAsync(user, "password", false) .Returns(SignInResult.TwoFactorRequired); var service = new AuthSignInService(signInManager); @@ -114,13 +114,13 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "password", false, true) + signInManager.CheckPasswordSignInAsync(user, "password", true) .Returns(SignInResult.Failed); var service = new AuthSignInService(signInManager); await service.PasswordSignInAsync(user, "password", true); - await signInManager.Received(1).PasswordSignInAsync(user, "password", false, true); + await signInManager.Received(1).CheckPasswordSignInAsync(user, "password", true); } [Fact] @@ -128,12 +128,13 @@ public class AuthSignInServiceTests { var (signInManager, _) = CreateSignInManager(); var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" }; - signInManager.PasswordSignInAsync(user, "password", false, false) + signInManager.CheckPasswordSignInAsync(user, "password", false) .Returns(SignInResult.Success); var service = new AuthSignInService(signInManager); await service.PasswordSignInAsync(user, "password", false); - await signInManager.Received(1).PasswordSignInAsync(user, "password", false, false); + await signInManager.Received(1).CheckPasswordSignInAsync(user, "password", false); + await signInManager.DidNotReceiveWithAnyArgs().PasswordSignInAsync((AppUser)null!, null!, false, false); } } diff --git a/tests/Heimdall.Infrastructure.Tests/ChallengeAtomicPostgresTests.cs b/tests/Heimdall.Infrastructure.Tests/ChallengeAtomicPostgresTests.cs new file mode 100644 index 0000000..5411102 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/ChallengeAtomicPostgresTests.cs @@ -0,0 +1,64 @@ +using Heimdall.Application.Auth.Commands.Verify2fa; +using Heimdall.Application.Auth.Services; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Security; +using Heimdall.TestCommon; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +[Collection("PostgresInfra")] +public class ChallengeAtomicPostgresTests(PostgreSqlContainerFixture postgres) +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Independent_instances_cannot_redeem_recovery_or_challenge_twice(bool sameChallenge) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(new AuditInterceptor()); + services.AddDbContext(o => o.UseNpgsql(postgres.ConnectionString)); + services.AddIdentity().AddEntityFrameworkStores().AddDefaultTokenProviders(); + await using var provider = services.BuildServiceProvider(); + string first, second; + var code = Guid.NewGuid().ToString("N"); + using (var scope = provider.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.ExecuteSqlRawAsync("CREATE EXTENSION IF NOT EXISTS pg_trgm"); + await db.Database.EnsureCreatedAsync(); + var users = scope.ServiceProvider.GetRequiredService>(); + var email = $"{Guid.NewGuid():N}@example.test"; + var user = new AppUser { Id = Guid.NewGuid(), Email = email, UserName = email, EmailConfirmed = true }; + (await users.CreateAsync(user, "Correct-password-123!")).Succeeded.ShouldBeTrue(); + await users.ResetAuthenticatorKeyAsync(user); + await users.SetTwoFactorEnabledAsync(user, true); + db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code))); + first = await LoginChallengeService.CreateAsync(db, user, default); + second = sameChallenge ? first : await LoginChallengeService.CreateAsync(db, user, default); + } + using var gate = new Barrier(2); + var results = await Task.WhenAll(new[] { first, second }.Select(challenge => Task.Run(async () => + { + // A new scope owns its own DbContext, UserManager and PostgreSQL connection. + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var jwt = Substitute.For(); + var roles = Substitute.For(); + var handler = new Verify2faHandler(scope.ServiceProvider.GetRequiredService>(), + jwt, roles, db, NullLogger.Instance); + gate.SignalAndWait(TimeSpan.FromSeconds(30)).ShouldBeTrue(); + return await handler.Handle(new(challenge, code), default); + }))); + results.Count(x => x.IsSuccess).ShouldBe(1); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/JwtServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/JwtServiceTests.cs index 4327781..4a8e083 100644 --- a/tests/Heimdall.Infrastructure.Tests/JwtServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/JwtServiceTests.cs @@ -1,4 +1,5 @@ using System.IdentityModel.Tokens.Jwt; +using System.Globalization; using System.Security.Claims; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Security; @@ -11,6 +12,28 @@ namespace Heimdall.Infrastructure.Tests; public class JwtServiceTests { + [Fact] + public void Fractional_token_lifetimes_are_independent_of_request_culture() + { + var previousCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + var service = new JwtService(CreateConfig(accessExpiry: "0.25", refreshExpiry: "0.5"), + Substitute.For>()); + var user = CreateUser(); + var now = DateTime.UtcNow; + var access = service.GenerateAccessToken(user, [], []); + var refresh = service.GenerateRefreshToken(user); + (access.expiresAt - now).TotalSeconds.ShouldBeInRange(14, 16); + (refresh.expiresAt - now).TotalHours.ShouldBeInRange(11.99, 12.01); + } + finally + { + CultureInfo.CurrentCulture = previousCulture; + } + } + private static IConfiguration CreateConfig( string? key = null, string? refreshKey = null, diff --git a/tests/Heimdall.Infrastructure.Tests/PasswordChallengeIdentityTests.cs b/tests/Heimdall.Infrastructure.Tests/PasswordChallengeIdentityTests.cs new file mode 100644 index 0000000..64104b1 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/PasswordChallengeIdentityTests.cs @@ -0,0 +1,276 @@ +using Heimdall.Application.Auth.Commands.Login; +using Heimdall.Application.Auth.Commands.Verify2fa; +using Heimdall.Application.Auth.Commands.RefreshToken; +using Heimdall.Application.Auth.Services; +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.Security; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public sealed class PasswordChallengeIdentityTests : IAsyncLifetime +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"heimdall-auth-{Guid.NewGuid()}.db"); + private ServiceProvider _services = null!; + private readonly string _email = "identity@example.test"; + private const string Password = "Correct-password-123!"; + + public async Task InitializeAsync() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseSqlite($"Data Source={_path}")); + services.AddSingleton(new AuditInterceptor()); + services.AddIdentity(o => { o.Lockout.MaxFailedAccessAttempts = 5; }) + .AddEntityFrameworkStores().AddDefaultTokenProviders(); + var accessor = Substitute.For(); + accessor.HttpContext.Returns(new DefaultHttpContext()); + services.AddSingleton(accessor); + services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Jwt:Key"] = new string('a', 64), ["Jwt:RefreshKey"] = new string('b', 64) + }).Build()); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(_ => Substitute.For()); + _services = services.BuildServiceProvider(); + using var scope = _services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.EnsureCreatedAsync(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new AppUser { Id = Guid.NewGuid(), Email = _email, UserName = _email, EmailConfirmed = true }; + (await users.CreateAsync(user, Password)).Succeeded.ShouldBeTrue(); + await users.ResetAuthenticatorKeyAsync(user); + await users.SetTwoFactorEnabledAsync(user, true); + } + + public async Task DisposeAsync() + { + await _services.DisposeAsync(); + SqliteConnection.ClearAllPools(); + File.Delete(_path); + } + + private static LoginHandler Login(IServiceProvider s) + { + s.GetRequiredService().HttpContext!.RequestServices = s; + return new( + s.GetRequiredService>(), s.GetRequiredService(), + s.GetRequiredService(), s.GetRequiredService(), + Substitute.For(), s.GetRequiredService(), NullLogger.Instance, + s.GetRequiredService()); + } + + private static Verify2faHandler Verify(IServiceProvider s) => new( + s.GetRequiredService>(), s.GetRequiredService(), + s.GetRequiredService(), s.GetRequiredService(), NullLogger.Instance); + + private async Task ChallengeAsync() + { + using var scope = _services.CreateScope(); + var result = await Login(scope.ServiceProvider).Handle(new(_email, Password), default); + result.IsSuccess.ShouldBeTrue(); + result.Data!.Requires2fa.ShouldBeTrue(); + result.Data.AccessToken.ShouldBeEmpty(); + result.Data.ChallengeId.ShouldNotBeNull(); + return result.Data.ChallengeId!; + } + + private async Task RecoveryAsync() + { + using var scope = _services.CreateScope(); + var s = scope.ServiceProvider; + var user = await s.GetRequiredService>().FindByEmailAsync(_email); + var code = Guid.NewGuid().ToString("N"); + var db = s.GetRequiredService(); + db.UserRecoveryCodes.Add(new UserRecoveryCode(user!.Id, RecoveryCodeService.Hash(code))); + await db.SaveChangesAsync(); + return code; + } + + [Fact] + public async Task Real_authenticator_totp_completes_password_challenge_once() + { + var challenge = await ChallengeAsync(); + string key; + using (var scope = _services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + key = (await users.GetAuthenticatorKeyAsync((await users.FindByEmailAsync(_email))!))!; + } + var bits = string.Concat(key.TrimEnd('=').Select(c => Convert.ToString("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".IndexOf(c, StringComparison.Ordinal), 2).PadLeft(5, '0'))); + var secret = Enumerable.Range(0, bits.Length / 8).Select(i => Convert.ToByte(bits.Substring(i * 8, 8), 2)).ToArray(); + var counter = BitConverter.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30); + if (BitConverter.IsLittleEndian) Array.Reverse(counter); +#pragma warning disable CA5350 // RFC 6238 / Identity authenticator protocol requires HMAC-SHA1. + var hash = System.Security.Cryptography.HMACSHA1.HashData(secret, counter); +#pragma warning restore CA5350 + var offset = hash[^1] & 15; + var number = ((hash[offset] & 127) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; + var code = (number % 1000000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); + using (var scope = _services.CreateScope()) + (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).IsSuccess.ShouldBeTrue(); + using (var scope = _services.CreateScope()) + (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); + } + + [Theory] + [InlineData("locked")] + [InlineData("email")] + [InlineData("stamp")] + public async Task Refresh_revalidates_account(string mode) + { + var challenge = await ChallengeAsync(); + var code = await RecoveryAsync(); + string refresh; + using (var scope = _services.CreateScope()) + refresh = (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).Data!.RefreshToken; + using (var scope = _services.CreateScope()) + { + var s = scope.ServiceProvider; + var users = s.GetRequiredService>(); + var user = (await users.FindByEmailAsync(_email))!; + if (mode == "locked") await users.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddMinutes(5)); + if (mode == "stamp") await users.UpdateSecurityStampAsync(user); + if (mode == "email") + { + user.EmailConfirmed = false; + await users.UpdateAsync(user); + await s.GetRequiredService().SetSettingValueAsync("email.confirmation.required", "true", "Auth", null, default); + } + } + using var verify = _services.CreateScope(); + var sp = verify.ServiceProvider; + var handler = new RefreshTokenHandler(sp.GetRequiredService(), sp.GetRequiredService>(), + sp.GetRequiredService(), sp.GetRequiredService(), NullLogger.Instance); + (await handler.Handle(new(refresh), default)).StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Refresh_preserves_absolute_session_deadline_and_rotates() + { + using var scope = _services.CreateScope(); + var sp = scope.ServiceProvider; + var user = (await sp.GetRequiredService>().FindByEmailAsync(_email))!; + var started = DateTime.UtcNow.AddDays(-6); + var jwt = sp.GetRequiredService(); + var token = jwt.GenerateRefreshToken(user, started).token; + var handler = new RefreshTokenHandler(jwt, sp.GetRequiredService>(), + sp.GetRequiredService(), sp.GetRequiredService(), NullLogger.Instance); + var result = await handler.Handle(new(token), default); + result.IsSuccess.ShouldBeTrue(); + var parsed = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().ReadJwtToken(result.Data!.RefreshToken); + Math.Abs((parsed.ValidTo - started.AddDays(7)).TotalSeconds).ShouldBeLessThan(2); + (await handler.Handle(new(token), default)).StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Password_check_does_not_emit_cookie_and_requires_real_password() + { + using var scope = _services.CreateScope(); + var s = scope.ServiceProvider; + (await Login(s).Handle(new(_email, "wrong"), default)).StatusCode.ShouldBe(401); + (await Login(s).Handle(new(_email, Password), default)).Data!.Requires2fa.ShouldBeTrue(); + s.GetRequiredService().HttpContext!.Response.Headers.ContainsKey("Set-Cookie").ShouldBeFalse(); + } + + [Fact] + public async Task Login_without_2fa_issues_tokens_with_real_identity() + { + using var scope = _services.CreateScope(); + var s = scope.ServiceProvider; + var users = s.GetRequiredService>(); + await users.SetTwoFactorEnabledAsync((await users.FindByEmailAsync(_email))!, false); + var result = await Login(s).Handle(new(_email, Password), default); + result.IsSuccess.ShouldBeTrue(); + result.Data!.Requires2fa.ShouldBeFalse(); + result.Data.AccessToken.ShouldNotBeNullOrEmpty(); + } + + [Fact] + public async Task Recovery_and_challenge_are_single_use_across_scopes() + { + var challenge = await ChallengeAsync(); + var code = await RecoveryAsync(); + using (var scope = _services.CreateScope()) + (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).IsSuccess.ShouldBeTrue(); + using (var scope = _services.CreateScope()) + (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); + var another = await ChallengeAsync(); + using (var scope = _services.CreateScope()) + (await Verify(scope.ServiceProvider).Handle(new(another, code), default)).StatusCode.ShouldBe(401); + } + + [Theory] + [InlineData("expired")] + [InlineData("locked")] + [InlineData("disabled")] + [InlineData("email")] + [InlineData("password")] + public async Task Challenge_rechecks_account_and_expiration(string mode) + { + var challenge = await ChallengeAsync(); + var code = await RecoveryAsync(); + using (var scope = _services.CreateScope()) + { + var s = scope.ServiceProvider; + var users = s.GetRequiredService>(); + var user = (await users.FindByEmailAsync(_email))!; + var db = s.GetRequiredService(); + if (mode == "expired") await db.Set().ExecuteUpdateAsync(x => x.SetProperty(c => c.ExpiresAt, DateTime.UtcNow.AddSeconds(-1))); + if (mode == "locked") await users.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddMinutes(10)); + if (mode == "disabled") await users.SetTwoFactorEnabledAsync(user, false); + if (mode == "password") await users.ChangePasswordAsync(user, Password, "New-password-123!"); + if (mode == "email") + { + user.EmailConfirmed = false; + await users.UpdateAsync(user); + db.AppSettings.Add(new AppSetting("email.confirmation.required", "true")); + await db.SaveChangesAsync(); + } + } + using var verify = _services.CreateScope(); + (await Verify(verify.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Five_invalid_attempts_exhaust_challenge_and_lock_identity() + { + var challenge = await ChallengeAsync(); + for (var i = 0; i < 5; i++) + { + using var scope = _services.CreateScope(); + (await Verify(scope.ServiceProvider).Handle(new(challenge, "invalid"), default)).StatusCode.ShouldBe(401); + } + using var last = _services.CreateScope(); + var users = last.ServiceProvider.GetRequiredService>(); + (await users.IsLockedOutAsync((await users.FindByEmailAsync(_email))!)).ShouldBeTrue(); + (await Verify(last.ServiceProvider).Handle(new(challenge, await RecoveryAsync()), default)).StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Concurrent_recovery_redemption_allows_only_one_session() + { + var challenges = new[] { await ChallengeAsync(), await ChallengeAsync() }; + var code = await RecoveryAsync(); + var results = await Task.WhenAll(challenges.Select(challenge => Task.Run(async () => + { + using var scope = _services.CreateScope(); + return await Verify(scope.ServiceProvider).Handle(new(challenge, code), default); + }))); + results.Count(x => x.IsSuccess).ShouldBe(1); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs new file mode 100644 index 0000000..dfc11ab --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs @@ -0,0 +1,107 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Heimdall.Application.Auth.Services; +using Heimdall.Application.DTOs; +using Heimdall.Application.Users.Commands.AssignRoles; +using Heimdall.Application.Users.Commands.LockUser; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.IntegrationTests.Factories; +using MediatR; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +[Collection("Postgres")] +[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "xUnit invokes IAsyncLifetime.DisposeAsync to dispose the client and application factory.")] +public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres) : IAsyncLifetime +{ + private HeimdallWebApplicationFactory _factory = null!; + private HttpClient _client = null!; + private readonly string _email = $"auth-{Guid.NewGuid():N}@example.test"; + private Guid _userId; + private const string Password = "Correct-password-123!"; + + public async Task InitializeAsync() + { + _factory = new HeimdallWebApplicationFactory(postgres.ConnectionString); + _client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false }); + using var scope = _factory.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new AppUser { Id = Guid.NewGuid(), Email = _email, UserName = _email, EmailConfirmed = true }; + (await users.CreateAsync(user, Password)).Succeeded.ShouldBeTrue(); + (await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue(); + _userId = user.Id; + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _factory.DisposeAsync(); + } + + private async Task LoginAsync() + { + var response = await _client.PostAsJsonAsync("/api/auth/login", new { email = _email, password = Password }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Headers.Contains("Set-Cookie").ShouldBeFalse(); + return (await response.Content.ReadFromJsonAsync())!; + } + + [Fact] + public async Task Http_2fa_requires_password_challenge_and_rejects_replay() + { + var code = "ABCDE"; + using (var scope = _factory.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var user = (await users.FindByIdAsync(_userId.ToString()))!; + await users.ResetAuthenticatorKeyAsync(user); + await users.SetTwoFactorEnabledAsync(user, true); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserRecoveryCodes.Add(new UserRecoveryCode(_userId, RecoveryCodeService.Hash(code))); + await db.SaveChangesAsync(); + } + var bypass = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { email = _email, code }); + bypass.IsSuccessStatusCode.ShouldBeFalse(); + var challenge = await LoginAsync(); + challenge.Requires2fa.ShouldBeTrue(); + challenge.AccessToken.ShouldBeEmpty(); + var response = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + (await response.Content.ReadFromJsonAsync())!.AccessToken.ShouldNotBeNullOrEmpty(); + var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); + replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Theory] + [InlineData("lock")] + [InlineData("roles")] + public async Task Existing_jwt_cookie_and_refresh_are_revoked_by_account_change(string change) + { + var auth = await LoginAsync(); + var signin = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken }); + signin.StatusCode.ShouldBe(HttpStatusCode.OK); + var cookie = signin.Headers.GetValues("Set-Cookie").Single(x => x.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0]; + using (var scope = _factory.Services.CreateScope()) + { + var sender = scope.ServiceProvider.GetRequiredService(); + if (change == "lock") (await sender.Send(new LockUserCommand(_userId))).IsSuccess.ShouldBeTrue(); + else (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue(); + } + var refresh = await _client.PostAsJsonAsync("/api/auth/refresh", new { refreshToken = auth.RefreshToken }); + refresh.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + var bearer = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); + bearer.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AccessToken); + (await _client.SendAsync(bearer)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + var withCookie = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); + withCookie.Headers.Add("Cookie", cookie); + (await _client.SendAsync(withCookie)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + (await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken })).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } +} diff --git a/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs index 7a52e83..76ab956 100644 --- a/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs +++ b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs @@ -104,3 +104,41 @@ public class MockInnerHandler : HttpMessageHandler return handler; } } + +public class SessionRefreshRegressionTests +{ + [Fact] + public async Task Expired_nonempty_token_refreshes_against_actual_api_origin_without_http_context() + { + var auth = new AuthState { AccessToken = "expired", RefreshToken = "refresh" }; + var provider = Substitute.For( + new ProtectedSessionStorage(Substitute.For(), Substitute.For()), + auth, Substitute.For()); + provider.When(x => x.NotifyLoginAsync(Arg.Any())).Do(x => auth.Login(x.Arg()!)); + var raw = new MockInnerHandler(); + raw.QueueResponse(HttpStatusCode.OK, new AuthResponse("fresh", "rotated", DateTime.UtcNow.AddMinutes(15), false, + new UserInfo(Guid.NewGuid(), "test@example.test", "Test", []))); + var factory = Substitute.For(); + factory.CreateClient("HeimdallRefresh").Returns(_ => new HttpClient(raw, false)); + var api = new MockInnerHandler(); + api.QueueResponse(HttpStatusCode.Unauthorized); + api.QueueResponse(HttpStatusCode.OK); + using var handler = new TokenRefreshHandler(auth, provider, new HttpContextAccessor(), new ConfigurationBuilder().Build(), factory) + { InnerHandler = api }; + using var client = new HttpClient(handler) { BaseAddress = new Uri("http://127.0.0.1:5287/") }; + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "expired"); + var response = await client.GetAsync("api/sites"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, raw.CallCount); + Assert.Equal("http://127.0.0.1:5287/api/auth/refresh", raw.Requests[0].RequestUri!.AbsoluteUri); + Assert.Equal("fresh", api.Requests[1].Headers.Authorization!.Parameter); + } + + [Fact] + public void Refresh_locks_are_owned_by_each_session() + { + var a = new AuthState(); + var b = new AuthState(); + Assert.NotSame(a.RefreshLock, b.RefreshLock); + } +} From c0467ad82056511258d7b68b202ef82c987d867e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 20 Oct 2026 07:36:26 +0200 Subject: [PATCH 2/2] fix: revalidate live hub sessions from database --- docs/audits/2026-10-20-lot1-auth-session.md | 4 +- docs/audits/2026-10-20-lot2-hubs-secrets.md | 6 ++- .../Auth/Services/AccountSessionPolicy.cs | 24 +++++++++ src/Heimdall.Web/Hubs/AdminHub.cs | 39 +++++++++++---- src/Heimdall.Web/Hubs/NotificationsHub.cs | 47 +++++++++++++----- .../Security/LiveSubscriptions.cs | 7 ++- src/Heimdall.Web/Security/ResourceAccess.cs | 8 ++- .../Hubs/IsolationHubTests.cs | 49 +++++++++++++++++++ .../Security/AccessFixture.cs | 23 +++++++-- .../Security/HttpIsolationTests.cs | 8 ++- 10 files changed, 182 insertions(+), 33 deletions(-) diff --git a/docs/audits/2026-10-20-lot1-auth-session.md b/docs/audits/2026-10-20-lot1-auth-session.md index a3ab958..4fd76ad 100644 --- a/docs/audits/2026-10-20-lot1-auth-session.md +++ b/docs/audits/2026-10-20-lot1-auth-session.md @@ -1,6 +1,6 @@ # Lot 1 — Authentification et sessions -Périmètre : SEC-01, SEC-02, SEC-07 et SEC-10 du [rapport](2026-10-20-audit-complet.md), selon le [plan](2026-10-20-plan-implementation.md). Les autres lots restent hors de ce chantier. Ce document ne clôt pas l’audit global. +Périmètre initial : SEC-01, SEC-02, SEC-07 et SEC-10 du [rapport](2026-10-20-audit-complet.md), selon le [plan](2026-10-20-plan-implementation.md). Cette branche intègre désormais aussi le lot 2 (isolation API et hubs) de façon coordonnée ; voir [rapport du lot 2](2026-10-20-lot2-hubs-secrets.md) et [rapport d’isolation API](2026-10-20-lot2-isolation-api.md). Ce document ne clôt pas l’audit global. ## Contrat de connexion @@ -59,3 +59,5 @@ Les tests avec Identity réel couvrent le mot de passe, le TOTP et les codes de Les parcours d’installation/reprise sur appareils PWA réels appartiennent au lot 9. Le présent lot prépare la reprise de session connectée, sans service worker ni cache de données privées. Les connexions SignalR métier déjà ouvertes et leurs groupes doivent être traités avec le lot 2 : les contrôles d’entrée JWT/cookie ne réévaluent pas rétroactivement les abonnements existants. La revalidation du circuit Blazor ne remplace pas ce contrôle de diffusion. + +Après intégration du lot 2, `ResourceAccess.ResolveAsync` applique aussi `AccountSessionPolicy` aux identités humaines avant chaque diffusion autorisée : existence du compte, verrouillage, confirmation email configurée, security stamp et date initiale de session. La révocation retire ces connexions des diffusions événements, monitoring, configuration, administration et notifications ; une reconnexion est nécessaire après changement de stamp. diff --git a/docs/audits/2026-10-20-lot2-hubs-secrets.md b/docs/audits/2026-10-20-lot2-hubs-secrets.md index d60fd48..f52b21d 100644 --- a/docs/audits/2026-10-20-lot2-hubs-secrets.md +++ b/docs/audits/2026-10-20-lot2-hubs-secrets.md @@ -6,7 +6,7 @@ Suite de la PR politique API et groupes. Périmètre SEC-04/SEC-05 et raccordeme EventsHub autorise le site demandé puis inscrit uniquement les caméras effectivement accessibles. Le broadcaster adresse les abonnés de la caméra de l’événement, jamais tous les abonnés du site. Les GUID sont normalisés. MonitoringHub exige un droit sur le site entier ; un accès caméra partiel ne donne pas l’inventaire et les statuts des autres ressources du site. JoinAdminBroadcast exige le rôle Admin en base. ConfigHub exige la relation persistée clé → agent/site et interdit un autre agent, même dans le même site. -Un registre de connexions est utilisé par les trois broadcasters. Chaque envoi résout à nouveau l’identité et le droit depuis la base : retrait de groupe/site, suppression d’agent et révocation/expiration de clé sont pris en compte sans attendre une reconnexion. Les groupes SignalR ne sont pas considérés comme une preuve durable d’autorisation. Le registre est nettoyé à la déconnexion ; un redémarrage implique la reconnexion et le réabonnement habituels. +Un registre de connexions est utilisé par les broadcasters. Chaque envoi résout à nouveau l’identité et le droit depuis la base : retrait de groupe/site, suppression d’agent et révocation/expiration de clé sont pris en compte sans attendre une reconnexion. À la composition avec le lot 1, les connexions humaines vérifient également verrouillage, security stamp, confirmation email requise et date initiale de session avant toute diffusion. Les accès admin et notifications personnelles utilisent le même registre, au lieu d’envois directs vers un groupe SignalR durable. Une identité ou un droit révoqué est retiré du registre et ne reçoit plus de message. Le registre est nettoyé à la déconnexion ; un redémarrage implique la reconnexion et le réabonnement habituels. ## Configuration et journaux @@ -18,4 +18,8 @@ Les contrôleurs transmettent désormais explicitement le champ AgentScoped des Tests : abonnements caméra directs/groupes/sites, refus site B, monitoring partiel refusé, broadcast Admin, refus d’usurpation ConfigHub, révocation après abonnement, exclusion SMTP/S3 du push et du rechargement et rejet d’override serveur. Validation locale exécutée le 20 octobre 2026 avec .NET SDK 10.0.112 (`dotnet test --no-restore --verbosity minimal`) : Web 385/385, Agent 356/356, Application 504/504 et Infrastructure 223/223 ; aucun test ignoré. `git diff --check` passe. Un test de régression vérifie également le nettoyage des anciennes inscriptions lors d’un réabonnement après retrait des droits. Ces résultats ne couvrent pas les suites navigateur ou une infrastructure externe réelle. +Validation complémentaire après fusion coordonnée avec la politique de session : Web 389/389, Infrastructure 242/242, Application 502/502, et `AuthSessionSecurityTests` 3/3 sur PostgreSQL ; aucun test ignoré. Le test Web vérifie les diffusions enregistrées pour événements, monitoring, administration et notifications personnelles avant/après verrouillage du compte et rotation du security stamp. + +La vérification des sessions humaines sur les diffusions lit les champs security stamp, verrouillage et confirmation email via une projection EF `AsNoTracking`, sans réutiliser une instance utilisateur suivie par Identity. `IsolationHubTests` conserve volontairement l’utilisateur périmé dans son contexte principal, puis change le stamp ou verrouille le compte et sauvegarde depuis un second `DbContext` ; les quatre catégories d’abonnement cessent de recevoir les messages (11 tests ciblés réussis, Web 389/389 après ce changement). + Le registre est local à l’instance, conformément au déploiement SignalR actuel sans backplane. Un déploiement distribué devra transporter les abonnements ou diffuser sur chaque instance avec la même réautorisation ; aucune promesse de fan-out multi-instance n’est faite. La réautorisation ajoute des lectures par destinataire et doit être mesurée avant une montée en charge. Les changements de droits entre la vérification et l’envoi restent soumis à la course normale d’une requête en cours. Les anciens journaux déjà persistés ne sont pas purgés par ces changements. La sécurité des objets snapshot eux-mêmes relève du lot 4. La validation par caméra réelle et les essais SMTP/S3 réels ne sont pas remplacés par les tests locaux. diff --git a/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs b/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs index bfe0c49..bf2dd60 100644 --- a/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs +++ b/src/Heimdall.Application/Auth/Services/AccountSessionPolicy.cs @@ -1,8 +1,10 @@ using System.Security.Claims; using System.Globalization; using Heimdall.Application.Services; +using Heimdall.Application.Common; using Heimdall.Domain.Entities; using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Auth.Services; @@ -25,4 +27,26 @@ public static class AccountSessionPolicy if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) return false; return true; } + + /// Validates a live connection against persisted values without using Identity's tracked user cache. + public static async Task IsValidLiveAsync(ClaimsPrincipal principal, IApplicationDbContext db, CancellationToken ct) + { + if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow) + return false; + var id = principal.FindFirstValue(ClaimTypes.NameIdentifier); + if (!Guid.TryParse(id, out var userId)) return false; + + var user = await db.Users.AsNoTracking().Where(u => u.Id == userId) + .Select(u => new { u.SecurityStamp, u.LockoutEnabled, u.LockoutEnd, u.EmailConfirmed }) + .SingleOrDefaultAsync(ct); + if (user is null || string.IsNullOrEmpty(user.SecurityStamp) + || principal.FindFirstValue(StampClaim) != user.SecurityStamp + || (user.LockoutEnabled && user.LockoutEnd > DateTimeOffset.UtcNow)) return false; + + var confirmationRequired = await db.AppSettings.AsNoTracking() + .Where(s => s.Key == "email.confirmation.required") + .Select(s => s.Value).SingleOrDefaultAsync(ct); + return !string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed; + } } diff --git a/src/Heimdall.Web/Hubs/AdminHub.cs b/src/Heimdall.Web/Hubs/AdminHub.cs index b70d878..147e25e 100644 --- a/src/Heimdall.Web/Hubs/AdminHub.cs +++ b/src/Heimdall.Web/Hubs/AdminHub.cs @@ -1,3 +1,4 @@ +using Heimdall.Api.Security; using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; @@ -13,24 +14,31 @@ namespace Heimdall.Api.Hubs; public class AdminHub : Hub { private readonly ILogger _logger; + private readonly ResourceAccess _access; + private readonly LiveSubscriptions _subscriptions; - public AdminHub(ILogger logger) => _logger = logger; + public AdminHub(ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) + { _logger = logger; _access = access; _subscriptions = subscriptions; } /// /// Clients call this to join the admin broadcast group. /// public async Task JoinAdminBroadcast() { - await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast"); + var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted); + if (requester is null || !await _access.IsAdminAsync(requester, Context.ConnectionAborted)) + throw new HubException("Access denied"); + _subscriptions.Join("admin", Context.ConnectionId, "admin-broadcast", Context.User!); _logger.LogDebug("Admin client {ConnectionId} joined admin broadcast group", Context.ConnectionId); } /// /// Clients call this to leave the admin broadcast group. /// - public async Task LeaveAdminBroadcast() + public Task LeaveAdminBroadcast() { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, "admin-broadcast"); + _subscriptions.Leave("admin", Context.ConnectionId, "admin-broadcast"); + return Task.CompletedTask; } public override async Task OnConnectedAsync() @@ -42,6 +50,7 @@ public class AdminHub : Hub public override async Task OnDisconnectedAsync(Exception? exception) { + _subscriptions.Disconnect("admin", Context.ConnectionId); HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Admin disconnected from admin hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); @@ -56,34 +65,46 @@ public class AdminBroadcastService : IAdminBroadcastService { private readonly IHubContext _hubContext; private readonly ILogger _logger; + private readonly ResourceAccess _access; + private readonly LiveSubscriptions _subscriptions; - public AdminBroadcastService(IHubContext hubContext, ILogger logger) + public AdminBroadcastService(IHubContext hubContext, ILogger logger, + ResourceAccess access, LiveSubscriptions subscriptions) { _hubContext = hubContext; _logger = logger; + _access = access; + _subscriptions = subscriptions; } public async Task NotifyConfigChanged(string key, string? oldValue, string? newValue, CancellationToken ct = default) { _logger.LogDebug("Broadcasting config change: {Key}", key); - await _hubContext.Clients.Group("admin-broadcast").SendAsync("ConfigChanged", new { key, oldValue, newValue }, ct); + await SendToAdminsAsync("ConfigChanged", new { key, oldValue, newValue }, ct); } public async Task NotifyCameraAdded(Guid siteId, Guid cameraId, string cameraName, CancellationToken ct = default) { _logger.LogDebug("Broadcasting camera added: {CameraName} ({CameraId})", cameraName, cameraId); - await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraAdded", new { siteId, cameraId, cameraName }, ct); + await SendToAdminsAsync("CameraAdded", new { siteId, cameraId, cameraName }, ct); } public async Task NotifyCameraRemoved(Guid siteId, Guid cameraId, CancellationToken ct = default) { _logger.LogDebug("Broadcasting camera removed: {CameraId}", cameraId); - await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraRemoved", new { siteId, cameraId }, ct); + await SendToAdminsAsync("CameraRemoved", new { siteId, cameraId }, ct); } public async Task NotifyUserRoleChanged(Guid userId, string newRole, CancellationToken ct = default) { _logger.LogDebug("Broadcasting user role change: User={UserId} Role={NewRole}", userId, newRole); - await _hubContext.Clients.Group("admin-broadcast").SendAsync("UserRoleChanged", new { userId, newRole }, ct); + await SendToAdminsAsync("UserRoleChanged", new { userId, newRole }, ct); + } + + private async Task SendToAdminsAsync(string method, object payload, CancellationToken ct) + { + var recipients = await _subscriptions.AuthorizedAsync("admin", "admin-broadcast", _access, + r => _access.IsAdminAsync(r, ct), ct); + await _hubContext.Clients.Clients(recipients).SendAsync(method, payload, ct); } } diff --git a/src/Heimdall.Web/Hubs/NotificationsHub.cs b/src/Heimdall.Web/Hubs/NotificationsHub.cs index db3daa2..83c9567 100644 --- a/src/Heimdall.Web/Hubs/NotificationsHub.cs +++ b/src/Heimdall.Web/Hubs/NotificationsHub.cs @@ -1,4 +1,5 @@ using System.Security.Claims; +using Heimdall.Api.Security; using Heimdall.Application.DTOs; using Heimdall.Application.Metrics; using Heimdall.Application.Services; @@ -11,31 +12,39 @@ namespace Heimdall.Api.Hubs; /// SignalR hub for in-app notifications with badge count. /// JWT-authenticated users receive new notifications and unread count updates /// without polling. -/// Groups: "notif_{userId}" +/// Personal notification subscriptions are reauthorized before each broadcast. /// [Authorize(AuthenticationSchemes = "JwtBearer")] public class NotificationsHub : Hub { private readonly ILogger _logger; + private readonly ResourceAccess _access; + private readonly LiveSubscriptions _subscriptions; - public NotificationsHub(ILogger logger) => _logger = logger; + public NotificationsHub(ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) + { _logger = logger; _access = access; _subscriptions = subscriptions; } /// /// Clients call this to join their personal notification channel. - /// The user ID is extracted from the JWT claim. + /// Identity and account session are resolved from persisted state. /// public async Task JoinPersonalNotifications() { - var userId = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; - if (userId is null) - { - await Clients.Caller.SendAsync("Error", "User not authenticated"); - return; - } - await Groups.AddToGroupAsync(Context.ConnectionId, $"notif_{userId}"); + var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted); + if (requester is null || requester.Kind != RequesterKind.Human) + throw new HubException("Access denied"); + var userId = requester.Id.ToString(); + _subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!); _logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId); } + public Task LeavePersonalNotifications() + { + var id = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier); + if (id is not null) _subscriptions.Leave("notifications", Context.ConnectionId, id); + return Task.CompletedTask; + } + public override async Task OnConnectedAsync() { HeimdallMetrics.SignalRConnectionAdded(); @@ -45,6 +54,7 @@ public class NotificationsHub : Hub public override async Task OnDisconnectedAsync(Exception? exception) { + _subscriptions.Disconnect("notifications", Context.ConnectionId); HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Client disconnected from notifications hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); @@ -59,22 +69,33 @@ public class NotificationBroadcastService : INotificationBroadcastService { private readonly IHubContext _hubContext; private readonly ILogger _logger; + private readonly ResourceAccess _access; + private readonly LiveSubscriptions _subscriptions; - public NotificationBroadcastService(IHubContext hubContext, ILogger logger) + public NotificationBroadcastService(IHubContext hubContext, ILogger logger, + ResourceAccess access, LiveSubscriptions subscriptions) { _hubContext = hubContext; _logger = logger; + _access = access; + _subscriptions = subscriptions; } public async Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default) { _logger.LogDebug("Broadcasting new notification: {NotificationId} to user {UserId}", notification.Id, notification.UserId); - await _hubContext.Clients.Group($"notif_{notification.UserId}").SendAsync("NewNotification", notification, ct); + var recipients = await RecipientsAsync(notification.UserId, ct); + await _hubContext.Clients.Clients(recipients).SendAsync("NewNotification", notification, ct); } public async Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default) { _logger.LogDebug("Broadcasting unread count: User={UserId} Count={Count}", userId, count); - await _hubContext.Clients.Group($"notif_{userId}").SendAsync("UnreadCount", new { count }, ct); + var recipients = await RecipientsAsync(userId, ct); + await _hubContext.Clients.Clients(recipients).SendAsync("UnreadCount", new { count }, ct); } + + private Task> RecipientsAsync(Guid userId, CancellationToken ct) => + _subscriptions.AuthorizedAsync("notifications", userId.ToString(), _access, + r => Task.FromResult(r.Kind == RequesterKind.Human && r.Id == userId), ct); } diff --git a/src/Heimdall.Web/Security/LiveSubscriptions.cs b/src/Heimdall.Web/Security/LiveSubscriptions.cs index a6b0e26..42a0955 100644 --- a/src/Heimdall.Web/Security/LiveSubscriptions.cs +++ b/src/Heimdall.Web/Security/LiveSubscriptions.cs @@ -23,7 +23,12 @@ public sealed class LiveSubscriptions foreach (var (key, principal) in _entries.Where(e => e.Key.Hub == hub && e.Key.Channel == channel)) { var requester = await access.ResolveAsync(principal, ct); - if (requester is not null && await authorize(requester)) result.Add(key.Connection); + if (requester is null || !await authorize(requester)) + { + _entries.TryRemove(key, out _); + continue; + } + result.Add(key.Connection); } return result; } diff --git a/src/Heimdall.Web/Security/ResourceAccess.cs b/src/Heimdall.Web/Security/ResourceAccess.cs index cfcbdea..761fba1 100644 --- a/src/Heimdall.Web/Security/ResourceAccess.cs +++ b/src/Heimdall.Web/Security/ResourceAccess.cs @@ -1,6 +1,8 @@ using System.Security.Claims; +using Heimdall.Application.Auth.Services; using Heimdall.Application.Common; using Heimdall.Application.Services; +using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Security; using Microsoft.EntityFrameworkCore; @@ -10,7 +12,9 @@ public enum RequesterKind { Human, Agent } public sealed record Requester(RequesterKind Kind, Guid Id, Guid? SiteId = null); /// Resolves identities from persisted state; never treats an API key ID as a user ID. -public sealed class ResourceAccess(IApplicationDbContext db, ICameraAccessService cameras) +public sealed class ResourceAccess( + IApplicationDbContext db, + ICameraAccessService cameras) { public async Task ResolveAsync(ClaimsPrincipal? principal, CancellationToken ct = default) { @@ -33,7 +37,7 @@ public sealed class ResourceAccess(IApplicationDbContext db, ICameraAccessServic (claimedSite is not null && claimedSite != key.SiteId.Value.ToString())) return null; return new(RequesterKind.Agent, bound[0], key.SiteId); } - if (!await db.Users.AnyAsync(u => u.Id == id, ct)) return null; + if (!await AccountSessionPolicy.IsValidLiveAsync(principal, db, ct)) return null; return new(RequesterKind.Human, id); } diff --git a/tests/Heimdall.Web.Tests/Hubs/IsolationHubTests.cs b/tests/Heimdall.Web.Tests/Hubs/IsolationHubTests.cs index fcb25cf..f0326e9 100644 --- a/tests/Heimdall.Web.Tests/Hubs/IsolationHubTests.cs +++ b/tests/Heimdall.Web.Tests/Hubs/IsolationHubTests.cs @@ -7,6 +7,7 @@ using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Security; using Heimdall.Web.Tests.Security; using Microsoft.AspNetCore.SignalR; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Shouldly; @@ -66,6 +67,54 @@ public sealed class IsolationHubTests (await subscriptions.AuthorizedAsync("config", "all", f.Access, _ => Task.FromResult(true))).ShouldBeEmpty(); } + [Theory] + [InlineData("stamp")] + [InlineData("lock")] + public async Task Existing_hub_subscriptions_are_revoked_after_session_invalidation(string change) + { + using var f = new AccessFixture(); + var user = f.User(AppRoles.Admin, "none"); + var subscriptions = new LiveSubscriptions(); + var principal = AccessFixture.Principal(user.Id); + foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" }) + subscriptions.Join(hub, $"{hub}-connection", "channel", principal); + + foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" }) + (await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human))) + .ShouldBe([$"{hub}-connection"]); + + // Keep this context's user tracked with its original values while a separate + // context commits the revocation, reproducing a long-lived hub scope. + f.Db.Users.Single(u => u.Id == user.Id).SecurityStamp.ShouldBe("fixture-stamp"); + await using (var revocationDb = f.CreateDbContext()) + { + var persistedUser = await revocationDb.Users.SingleAsync(u => u.Id == user.Id); + if (change == "stamp") persistedUser.SecurityStamp = "rotated-stamp"; + else + { + persistedUser.LockoutEnabled = true; + persistedUser.LockoutEnd = DateTimeOffset.UtcNow.AddMinutes(5); + } + await revocationDb.SaveChangesAsync(); + } + f.Db.Entry(user).State.ShouldBe(EntityState.Unchanged); + + foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" }) + (await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human))) + .ShouldBeEmpty(); + + await using (var restoreDb = f.CreateDbContext()) + { + var persistedUser = await restoreDb.Users.SingleAsync(u => u.Id == user.Id); + if (change == "stamp") persistedUser.SecurityStamp = "fixture-stamp"; + else persistedUser.LockoutEnd = DateTimeOffset.UtcNow.AddMinutes(-1); + await restoreDb.SaveChangesAsync(); + } + foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" }) + (await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human))) + .ShouldBeEmpty(); + } + [Fact] public async Task Server_settings_are_excluded_from_push_overrides_and_full_reload() { diff --git a/tests/Heimdall.Web.Tests/Security/AccessFixture.cs b/tests/Heimdall.Web.Tests/Security/AccessFixture.cs index d3307ea..18a58e0 100644 --- a/tests/Heimdall.Web.Tests/Security/AccessFixture.cs +++ b/tests/Heimdall.Web.Tests/Security/AccessFixture.cs @@ -1,12 +1,13 @@ using System.Security.Claims; using Heimdall.Api.Security; +using Heimdall.Application.Auth.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Security; using Heimdall.Infrastructure.Services; -using Microsoft.AspNetCore.Identity; using Microsoft.Data.Sqlite; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Heimdall.Web.Tests.Security; @@ -49,9 +50,12 @@ public sealed class AccessFixture : IDisposable Access = new(Db, Cameras); } + public AppDbContext CreateDbContext() => new( + new DbContextOptionsBuilder().UseSqlite(_connection).Options, new AuditInterceptor()); + public AppUser User(string role, string grant) { - var user = new AppUser { Id = Guid.NewGuid(), UserName = Guid.NewGuid().ToString() }; + var user = new AppUser { Id = Guid.NewGuid(), UserName = Guid.NewGuid().ToString(), SecurityStamp = "fixture-stamp" }; var entity = Db.Roles.FirstOrDefault(r => r.Name == role) ?? new AppRole { Id = Guid.NewGuid(), Name = role, NormalizedName = role.ToUpperInvariant() }; if (Db.Entry(entity).State == EntityState.Detached) Db.Roles.Add(entity); Db.Users.Add(user); @@ -71,9 +75,18 @@ public sealed class AccessFixture : IDisposable return user; } - public static ClaimsPrincipal Principal(Guid id, bool agent = false) => new(new ClaimsIdentity( - agent ? [new Claim(ClaimTypes.NameIdentifier, id.ToString()), new Claim("auth_method", "api_key")] - : [new Claim(ClaimTypes.NameIdentifier, id.ToString())], "test")); + public static ClaimsPrincipal Principal(Guid id, bool agent = false) + { + var claims = agent + ? new List { new(ClaimTypes.NameIdentifier, id.ToString()), new("auth_method", "api_key") } + : new List + { + new(ClaimTypes.NameIdentifier, id.ToString()), + new(AccountSessionPolicy.StampClaim, "fixture-stamp"), + new(AccountSessionPolicy.StartedClaim, DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) + }; + return new ClaimsPrincipal(new ClaimsIdentity(claims, "test")); + } public void Dispose() { Db.Dispose(); _connection.Dispose(); } } diff --git a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs index b0976c4..14f789e 100644 --- a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs +++ b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs @@ -77,7 +77,13 @@ public sealed class TestHumanHandler(IOptionsMonitor { new(ClaimTypes.NameIdentifier, id.ToString()) }; + var claims = new List + { + new(ClaimTypes.NameIdentifier, id.ToString()), + new(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim, "fixture-stamp"), + new(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim, + DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) + }; claims.AddRange(AppPermissions.RolePermissions[role].Select(p => new Claim("permission", p))); return Task.FromResult(AuthenticateResult.Success(new(new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)), Scheme.Name))); }