Commit Graph
62 Commits
Author SHA1 Message Date
Arnaud Dartois 3ff20ddf98 fix(agent): settings distants réellement appliqués (heartbeat live)
ConfigReceiverService.ApplySetting ne faisait que logger. Le setting
heartbeat.interval.seconds est désormais appliqué à chaud : écrit dans
AgentState.HeartbeatIntervalSeconds (snapshot thread-safe) et relu par
AgentRegistrationService à chaque cycle — plus besoin de redémarrer
l'agent pour changer l'intervalle. Validation 5-300s, valeurs invalides
ignorées sans muter l'état.

Tests : +2 (application live vérifiée, invalides ne mutent pas l'état).
2026-08-10 11:02:37 +02:00
Arnaud Dartois b6d4164652 test(web): adapte GetStatsAsync au format enveloppe {data, timestamp} 2026-08-10 10:56:09 +02:00
Arnaud Dartois bfe9dc6e56 fix(auth): API key acceptée en Bearer sur les hubs SignalR
Le client SignalR .NET envoie le token d'accès en header Authorization:
Bearer sur le POST negotiate HTTP (les WebSockets ne peuvent pas poser
de header custom) ; le navigateur l'envoie en query string access_token.
ConfigHub étant [Authorize(AuthenticationSchemes="ApiKey")], le handler
ApiKey doit lire les deux sur /hubs. Le fallback reste scoped aux hubs :
sur les endpoints API, un Bearer non-JWT renvoie toujours 401.

Tests : +2 intégration (Bearer sur ConfigHub OK, Bearer hors /hubs 401).
2026-08-10 10:35:15 +02:00
Arnaud Dartois 1e3322cd1a fix(agent): heartbeat X-API-Key complet + métriques temps réel + hub config
- ApiKeyAuthenticationHandler accepte l'API key via query string access_token
  sur les chemins /hubs (WebSocket SignalR ne peut pas poser de header custom)
  → le ConfigReceiverService de l'agent peut se connecter au ConfigHub
- ConfigReceiverService.FetchFullConfigAsync : X-API-Key au lieu de Bearer
- Métriques heartbeat : CpuUsagePercent/MemoryUsageBytes/DiskUsagePercent/
  UptimeSeconds + IsOffline désormais transportées jusqu'à l'entité Agent
  (migration AddAgentLiveMetrics) ; IsOffline marque l'agent Offline
  immédiatement au lieu d'attendre le timeout 90s du HeartbeatMonitorJob
- docker-compose.local.yml : override aussi l'image agent (heimdall-agent:local)

Tests : +2 unit AgentRegistrationService (X-API-Key), +2 HeartbeatHandler
(métriques, offline), +3 intégration SignalR (ConfigHub query string) — verts.
2026-08-10 10:26:31 +02:00
Arnaud Dartois 4516761a3a fix(agent): authentifie le heartbeat via X-API-Key au lieu de Bearer
Le central (ApiKeyAuthenticationHandler) ne lit que le header X-API-Key.
L'agent posait Authorization: Bearer <apiKey> sur le client 'Central'
→ tout heartbeat et le heartbeat final de StopAsync renvoyait 401.
Corrige les deux chemins (identité existante + post-registration) et
verrouille le comportement avec deux tests (nouvelle identité, identité
réutilisée).
2026-08-10 10:09:27 +02:00
Arnaud Dartois 53b6240a3e fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)
Anomalies corrigées :
- MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur
  l'ouverture de menus/popovers (dashboard jamais rendu après login)
- AddIdentity redéfinissait le schéma par défaut sur Identity.Application
  alors que /_auth/signin signait avec Cookies → cookie posé mais jamais
  validé, tout rechargement de page redirigeait vers /login. Forçage du
  schéma par défaut sur Cookies + schémas JwtBearer explicites sur les
  endpoints API d'AuthController et SettingsController
- Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée
  → 500 à l'appel. Ajoutée (RequireRole Admin)
- HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur :
  pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé
  → pages protégées redirigées vers /login. Fallback cookie ajouté
- SameOriginHttpMessageHandler : résolution de l'origine via
  IServerAddressesFeature quand IHttpContextAccessor est null (circuit
  Blazor post-hydratation) au lieu de heimdall.local → DNS cassé
- UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400
  à l'édition. Accepte désormais auto (case-insensitive)

Tests :
- E2E Playwright complets (login/logout/register/user management) : 33/33
- Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du
  valueType, bootstrap admin via /register auto-admin, header X-API-Key,
  /proc/meminfo optionnel pour les LXC restreints)
- Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
2026-08-09 23:43:11 +02:00
Arnaud Dartois 64753b9ba6 fix(ci): reparation tests integration + infrastructure
- TestHelpers.CreateAdminClientAsync: bootstrap via register normal
  (first user = admin) + active les flags public-registration et
  admin-registration.enabled
- JwtService.GetUserIdFromExpiredToken: utilise GetJwtRefreshKey()
  (methode appelee avec refresh tokens, signes avec Jwt:RefreshKey)
- AuthDataServiceTests.RevokeRefreshTokenAsync_StoresToken:
  utilise SHA256 hash (nouveau comportement ExtractJti fallback)
2026-07-28 15:14:54 +00:00
Arnaud Dartois 663b872dc2 feat(auth): confirmation email + forgot/reset password
#37: Email confirmation flow:
- Nouveaux endpoints: POST /api/auth/confirm-email
- Register envoie email de confirmation si SMTP configure + flag active
- Login verifie EmailConfirmed si email.confirmation.required = true
- Premier admin auto-confirme (evite chicken-and-egg)
- Setting DB: email.confirmation.required (boolean)

#38: Forgot/Reset password flow:
- Nouveaux endpoints: POST /api/auth/forgot-password, POST /api/auth/reset-password
- ForgotPassword genere token et envoie email via IEmailService
- ResetPassword valide token et change le mot de passe
- Pas de divulgation si l email n'existe pas

Infrastructure email existante (IEmailService + SmtpClient) reutilisee.
2026-07-28 15:03:18 +00:00
Arnaud Dartois ba985ed3c2 fix(auth): RegisterAdmin — [Authorize] + feature flag auth.admin-registration.enabled
#14: Remplacé le guard environment (Testing/Development) par:
- [Authorize(Policy = "AdminUsers")] sur l'endpoint
- Feature flag auth.admin-registration.enabled en DB (default: absent = disabled)
- Suppression de la dependance IWebHostEnvironment du controller
- Test mis a jour: bootstrap via register normal, puis flag, puis RegisterAdmin
2026-07-28 14:57:28 +00:00
Arnaud Dartois 1b5395b86b fix(test): update LoginHandlerTests to inject IUserRepository
Breaking: LoginHandler constructor now requires IUserRepository pour
l'audit logging des echecs de login. Test mis a jour.
2026-07-28 14:40:55 +00:00
Arnaud Dartois 45c6ce82eb perf: add ConfigureAwait(false) to all async calls in library projects
Add ConfigureAwait(false) to all await expressions in Application and
Infrastructure projects (111 files). This follows .NET best practices
for library code to avoid potential deadlocks when consumed from
synchronization contexts (legacy, unit test runners).

Also fix 4 test assertions that check SaveChangesAsync — update to
SaveChangesWithRetryAsync to match the handler changes from Fix 4.
2026-07-27 18:59:12 +00:00
Arnaud Dartois a6b2a21ebc fix: corriger les issues mineures du review
🟡 SnapshotUrl: validation sécurité SSRF (scheme + loopback)
🟡 Integration tests: skip graceful sans PostgreSQL (TestContainers)
2026-07-27 09:09:14 +00:00
Arnaud Dartois c1eac5431b fix: corriger les 8 issues du code review notifications
🔴 EmailService: implémentation SMTP réelle (System.Net.Mail)
🔴 GetNotificationConfigHandler: CQS — retourne DTO par défaut sans écrire en DB
🟠 NotificationRateLimiter: increment atomique (Interlocked)
🟠 DailyDigestJob/WeeklyDigestJob: comptes événements user-specific
🟠 docker-compose.prod: auth ntfy via NTFY_AUTH_FILE
🟠 Namespace: Heimdall.Web.Controllers (consistant)
🟠 Commentaire 'gotify' → 'ntfy'
🟠 Tests: NotificationsControllerTests (7 tests)
2026-07-27 05:33:53 +00:00
Arnaud Dartois f800103239 feat: remplacer Gotify par ntfy — push notifications multi-utilisateur avec isolation par topic
- Nouveau NtfyService: topic isolé par user (heimdall_{userId})
- Configuration globale Ntfy:BaseUrl + Ntfy:Token (plus de token par user)
- Renommage UserNotificationConfig: Gotify* → Ntfy*
- Migration des colonnes DB: gotify_enabled/url/token → ntfy_enabled/url
- Ajout service ntfy dans docker-compose (binwiederhier/ntfy)
- Mise à jour .env.example avec NTFY__BASE_URL et NTFY__TOKEN
- Suppression GotifyService et IGotifyService
2026-07-27 04:56:16 +00:00
Arnaud Dartois f9be0f1e0d feat: implémenter SignalR hubs (Monitoring, Notifications, Admin) + système de notifications complet
SignalR Hubs:
- MonitoringHub (/hubs/monitoring) — statuts agents/caméras/stockage/GPU jobs
- NotificationsHub (/hubs/notifications) — notifications in-app badge temps réel
- AdminHub (/hubs/admin) — broadcast changements config (Admin only)

Notification System:
- Nouvelles entités: Notification, NotificationTemplate, UserNotificationConfig
- CQRS/MediatR: 6 handlers (list, unread, mark-read, mark-all, config get/update)
- Infrastructure: NotificationService orchestrator + EmailService + GotifyService
- Rate limiter IMemoryCache (20 events/min/camera/type)
- Hangfire jobs: SendNotification, DailyDigest, WeeklyDigest
- NotificationsController API (6 endpoints)
- Blazor UI: NotificationsPage + NotificationBadge
- Migration AddNotifications (3 nouvelles tables)
- 644 nouveaux tests (Domain: 131, Application: 321, Infra: 151, Integration: 120, +autres)
2026-07-26 20:45:35 +00:00
Arnaud Dartois d0da78188a test(auth): add integration tests for authentication redirect flow
Add AuthFlowTests to catch Blazor redirect bugs:
- Get_Root_WithoutAuth_RedirectsToLogin: unauthenticated GET /
  must redirect to /login (would have caught the /Account/Login bug)
- Get_LoginPage_ReturnsOk: verify login page renders
- Get_ProtectedApi_WithoutAuth_ReturnsUnauthorized: API auth check
- RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi:
  full auth flow with JWT token refresh
- Register_WithWeakPassword_ReturnsBadRequest: password validation
- Register_ReturnsValidAuthResponse: success path
2026-07-24 19:39:47 +00:00
Arnaud Dartois fc5108a4fa fix(agent): add ffmpegPath parameter to CameraStreamService for deterministic testability 2026-07-24 06:38:15 +00:00
Arnaud Dartois b851a20dde test(web): add bUnit tests for StatusChip and FilterBar with ManualMockKeyInterceptorService 2026-07-23 20:40:56 +00:00
Arnaud Dartois 3d7137a865 test(web): add bUnit shared component tests for PaginationBar, EmptyState, LoadingSkeleton, SectionCard 2026-07-23 19:38:30 +00:00
Arnaud Dartois 0745903fef test: add remaining handler tests for Users, Groups, Persons, Assignments, Discovery; more Agent + E2E tests 2026-07-23 19:19:05 +00:00
Arnaud Dartois a94afed6b5 test(e2e): add Playwright E2E tests for Blazor pages; refactor Program.cs to support test server 2026-07-23 18:12:47 +00:00
Arnaud Dartois 262adc07cf test(agent): add service tests for CameraStream, ConfigReceiver, FrameAnalyzer, SystemMetrics, DTOs 2026-07-23 15:37:20 +00:00
Arnaud Dartois 06247d4f5c test(web): add Web.Tests unit tests and extended IntegrationTests 2026-07-23 15:27:34 +00:00
Arnaud Dartois 5d06c39160 test(infrastructure): add service tests for Security, Data, Discovery, Jobs layers 2026-07-23 15:08:09 +00:00
Arnaud Dartois fed55bb1ab test(application): add CQRS handler tests for Sites, Cameras, Agents, Auth, Events, Settings, Groups, Users, Assignments, Discovery, Persons, Stats, Audit 2026-07-23 14:32:33 +00:00
Arnaud Dartois ddd0664a71 fix(test): replace NSubstitute-based DbSet mock with InMemoryDbSet - fixes nested substitution issue 2026-07-23 14:22:21 +00:00
Arnaud Dartois d9c2a24949 test(application): add MockDbSetHelper and CreateSiteHandler tests 2026-07-23 09:59:30 +00:00
Arnaud Dartois 7da799c0c4 test(application): add AutoMapper mapping profile validation tests 2026-07-23 09:56:11 +00:00
Arnaud Dartois 6ba08d1f39 test(application): add ValidationBehavior and LoggingBehavior pipeline tests 2026-07-23 09:54:47 +00:00
Arnaud Dartois 7328c12dbf test(application): add ServiceResult and ServiceResult<T> unit tests 2026-07-23 09:53:07 +00:00
Arnaud Dartois a44414a543 test(domain): add entity tests for CameraAssignment, CameraCredentials, CameraEvent, Group, Person, CameraDiscoveryResult, DiscoveredStreamUrl, UserGroup, CameraDetectionProfile; augment CameraTests and AgentTests 2026-07-23 09:52:30 +00:00
Arnaud Dartois 1525fabffe test(domain): add ApiKey, AppSetting, AgentSetting, AuditLog, RevokedRefreshToken entity tests 2026-07-23 09:50:43 +00:00
Arnaud Dartois 3cedffb43c test(domain): add enum values tests for all 11 enum types 2026-07-23 09:49:35 +00:00
Arnaud Dartois c02ebe460e test(domain): add Entity<TId> and ValueObject equality tests 2026-07-23 09:48:58 +00:00
Arnaud Dartois 649af93f56 feat(cqrs): add MediatR, AutoMapper and pipeline infrastructure
- Add MediatR 12.5.0, AutoMapper 13.0.1 packages
- Create ValidationBehavior (FluentValidation pipeline)
- Create LoggingBehavior (structured logging pipeline)
- Create MappingProfile with IMapFrom<T> convention
- Make ServiceResult properties public for pipeline use
- Update Application DI with MediatR + AutoMapper registration
2026-07-22 19:31:51 +00:00
Arnaud Dartois 0ef4642f6d fix(tests): restore DATABASE_URL fallback for CI in shared PostgreSqlContainerFixture
The shared fixture (Heimdall.TestCommon) was refactored from per-project
fixtures but lost the DATABASE_URL env var check. Without it, the fixture
always starts a Testcontainers PostgreSQL container, which fails in CI
when Docker disk space is exhausted (initdb: No space left on device).

Now checks DATABASE_URL first — if set (CI mode), skips Testcontainers
and uses the CI-provided PostgreSQL service. Falls back to Testcontainers
for local development.
2026-07-21 19:59:27 +00:00
Arnaud Dartois 6825880b52 fix: share single PostgreSQL container across test projects via static ref-count
Use a static PostgreSqlContainer with reference counting so both
Infrastructure and Integration test projects share one PostgreSQL
container instead of each starting their own. Fixes resource
conflict in CI where only the first test project could connect.
2026-07-21 19:05:54 +00:00
Arnaud Dartois b167c2afcf fix: share one PostgreSQL Testcontainer across all test projects
Create Heimdall.TestCommon project with a single PostgreSqlContainerFixture
shared by both Infrastructure and Integration tests. This prevents Docker
resource conflicts from starting two PostgreSQL containers and ensures
both test suites connect to the same database instance.

- Move shared fixture to tests/Heimdall.TestCommon
- Remove duplicate fixtures from each test project
- Keep test isolation (truncation) and FK fix from previous commit
- Revert DATABASE_URL env var check (Testcontainers works in CI)
2026-07-21 18:48:39 +00:00
Arnaud Dartois 53e0d4c199 fix: resolve CI test failures after InMemory->Testcontainers migration
Three issues fixed:
- Camera.AssignAgent(Guid.Empty) violated FK constraint; changed to
  nullable Guid? and pass null on camera release
- Test fixtures now check DATABASE_URL env var first, falling back to
  Testcontainers locally (CI has no Docker socket)
- Added database truncation before each test via IAsyncLifetime to
  prevent shared state between test methods (InMemory was fresh per test,
  real PostgreSQL persists data)
2026-07-21 17:46:32 +00:00
Arnaud Dartois 58a3ce5b1b chore: vire toute trace d'InMemory, remplace par Testcontainers PostgreSQL
- Supprime InMemory de tous les .csproj (Infrastructure, Domain.Tests, IntegrationTests)\n- Supprime le branchement Database:Provider=InMemory de DependencyInjection.cs\n  (plus que du PostgreSQL natif)\n- Infrastructure.Tests: CameraAssignment + CameraEvent tests -> Testcontainers\n- PostgreSqlContainerFixture ajoute aux Infrastructure.Tests\n- appsettings.Testing.json: retire Database:Provider et Hangfire:Enabled\n- 4 tests echouent encore: bugs pre-existants masques par InMemory\n  (FK non respectees, donnees de test erronees)\n\nTests: 222/226 passed (4 pre-existants lies aux FK)
2026-07-21 12:19:43 +00:00
Arnaud Dartois ee7894646f test: remplace InMemory par Testcontainers PostgreSQL
- Ajoute Testcontainers.PostgreSql v4.13.0\n- PostgreSqlContainerFixture: collection fixture xUnit avec postgres:17-alpine\n- HeimdallWebApplicationFactory: accepte connectionString pour vrai PostgreSQL\n- PostgresTestBase: classe de base pour tous les tests integration\n- Ajoute [Collection("Postgres")] aux 9 classes de test\n- Database:MigrateOnStartup active quand PostgreSQL est utilise\n- Programme le Hangfire (skip en test via isTesting)\n\nAvant: InMemory (pas de contraintes, comportement different)\nApres: Vrai PostgreSQL dans un container temporaire\n\nTests: 226/226 passed (61 integration avec vrai PostgreSQL)
2026-07-21 10:24:11 +00:00
Arnaud Dartois 7be5d42e85 fix(identity): DB refresh tokens, auto-refresh handler, 2FA endpoints, JWT fix
- DB-backed RevokedRefreshToken entity + migration (remplace ConcurrentDictionary\n  en memoire, fonctionne en multi-instance et survive aux redemarrages)\n- TokenRefreshHandler: auto-refresh des JWT 401 via DelegatingHandler\n  (avec SemaphoreSlim pour eviter les refresh storms)\n- Fix: GenerateRefreshToken genere maintenant un JWT valide au lieu de\n  bytes aleatoires (ValidateRefreshToken attendait un JWT - flux casse)\n- Fix: Login.razor gere Requires2fa correctement (affiche champ code 2FA)\n- Ajout: endpoints POST /api/auth/2fa/enable et /2fa/disable\n- Ajout: Disable2faAsync dans IAuthService\n- Fix: GenerateTemporaryPassword garantit les 4 categories de charactere\n  (uppercase, lowercase, digit, non-alphanumeric)\n- Fix: TestFactory ajoute Jwt:RefreshKey manquant\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
2026-07-21 08:57:53 +00:00
Arnaud Dartois 1d70455abb fix(web): make integration tests work with Heimdall.Web as entry point
- Add InternalsVisibleTo for Heimdall.Api.Tests and
  Heimdall.IntegrationTests in Web.csproj
- Add partial class Program for WebApplicationFactory<Program>
- Pass builder.Environment.EnvironmentName instead of env var
  so AddInfrastructure correctly detects Testing environment
- Skip DATABASE_URL check, Hangfire setup, migrations, and
  recurring jobs when environment is Testing
- Update test project references from Heimdall.Api to Heimdall.Web
2026-07-20 20:32:32 +00:00
Arnaud Dartois 630e7987fe refactor(docker): merge worker and web into single heimdall image
Combine Heimdall.Web and Heimdall.Workers into one process/image.
Hangfire background jobs now run inside the web process.

- Move job classes to Infrastructure/Jobs/ (no Worker SDK dependency)
- Add Hangfire server + recurring jobs to Web/Program.cs
- Add missing AddInfrastructure/AddApplication DI registrations to Web
- Rename image: heimdall (was heimdall-web / heimdall-workers)
- Remove src/Heimdall.Workers project entirely
- Remove tests/Heimdall.Workers.Tests (placeholder)
- Simplify Dockerfile: single build target, no workers publish
- Update docker-compose files: one service heimdall, no workers
- Update Makefile, .env.example
2026-07-20 17:22:56 +00:00
Arnaud Dartois 562aabdfc8 feat(api+web): merge REST API and Blazor UI into single process
Previously the API (heimdall-central) and Blazor UI (heimdall-web) ran as
separate containers with the Blazor Server making internal HTTP calls to
the API. This caused the Blazor circuit to disconnect when the API was
unreachable (network error → "Une erreur réseau est survenue").

Now both serve from the same .NET process on the same port:
- All 16 API controllers, ExceptionFilter, and SignalR hubs integrated
  into Heimdall.Web
- JWT auth, CORS, rate limiting configured in the unified Program.cs
- Dockerfile.central entrypoint runs web/Heimdall.Web.dll
- docker-compose simplified: heimdall-central service removed
- CI publishes heimdall-web image instead of heimdall-central

Also fixes timezone validation on Alpine/tzdata-less environments
and enables FluentValidation auto-validation in the API project.
2026-07-20 10:30:01 +00:00
Arnaud Dartois a33a436c26 chore: apply auto-fixes and code improvements
- AuthService: fix public registration logic revert
- JwtService: add ILogger dependency
- SoftDeleteInterceptor removed (merged)
- XML doc comments on all services
- Error boundary + error page in Blazor
- Optimize StatsService queries
- ApiClient error handling improvements
2026-07-20 09:50:43 +00:00
Arnaud Dartois ba968a5f23 fix(security): harden Docker, CSRF, EventsHub scoping, secret logging, tests
- Docker: remove default passwords from prod compose (required env vars)
- CSRF: validate antiforgery tokens on /_auth/signin and /_auth/signout
- EventsHub: broadcast to site-scoped Group() instead of Clients.All
- SettingsController: redact secret values in logs
- Create SetAgentSettingValidator + UpdateAppSettingValidator classes
- Replace 3 placeholder test projects with meaningful tests
- Remove FluentValidation auto-validation (incompatible with .NET 10)
2026-07-19 20:53:48 +00:00
Arnaud Dartois 153be535d4 fix(multiple): auth, workers, EF Core, MudTheme fixes
- Auth: AssignmentsController auth bug, ReleaseCamera result, logout endpoint
- Security: open redirect fix
- Workers: AgentState thread-safety, CameraStreamService async, HttpClientFactory
- EF Core: AddCameraDiscoveryFields migration, DI interceptors, retry helper
- UI: MudTheme palette config, aria-labels on icon buttons
2026-07-19 19:58:45 +00:00
Arnaud Dartois c5728fa810 feat(events): add SignalR real-time event broadcasting to web UI 2026-07-19 15:24:52 +00:00
Arnaud Dartois 76b261378c fix: resolve review findings — thread safety, N+1, DTO layering, sentry, S3 retry 2026-07-19 13:43:48 +00:00