Commit Graph
117 Commits
Author SHA1 Message Date
Arnaud Dartois 6eae4eea2f feat(agent): détection GPU + heartbeat étendu + badges Admin UI (#160) 2026-08-26 23:52:16 +02:00
Arnaud Dartois ca43c6d28e feat(analysis): scheduler de jobs d'analyse avec routage par capacités, priorités et dead-letter (#159) 2026-08-26 23:44:38 +02:00
Arnaud Dartois 2d1734114f feat(metrics): métriques OpenTelemetry Prometheus (spec §13.1) (#161) 2026-08-20 18:22:37 +02:00
Arnaud Dartois 7a89a97bf3 feat(notifications): add user-configurable ntfy to 2026-08-20 18:14:46 +02:00
Arnaud Dartois 2ac2789728 chore(hangfire): migrate from obsolete UsePostgreS 2026-08-20 18:14:28 +02:00
Arnaud Dartois 13456ab4f5 fix(security): align rate limiting and password po 2026-08-20 18:14:18 +02:00
Arnaud Dartois 6b611e908a feat(notifications): abonnement par type d'événement + priorité ntfy (Fixes #61) (#154)
## Contexte

Issue #61 : Gestion des types d'alertes — abonnement par type d'événement + sévérité/priorité.

Les utilisateurs ne peuvent pas filtrer quelles notifications push/email ils reçoivent. Tous les événements (mouvement, personne, caméra hors ligne...) sont envoyés sans distinction.

## Changements

### Domaine
- **EventTypePriorityMap** (`src/Heimdall.Domain/Helpers/`) : mapping `EventType` → priorité ntfy (1-5)
  - CameraOffline/UnknownPerson = 5 (urgent), PersonDetected/FaceRecognized = 4 (high), MotionDetected/VehicleDetected/LicensePlateDetected = 3 (default), CameraOnline = 2 (low)
- **UserNotificationConfig** : ajout `SubscribedEventsJson` (JSON array), `GetSubscribedEvents()`, `IsEventTypeSubscribed()`, `SetSubscribedEvents()`
  - `null` ou `[]` = recevoir tous les événements (comportement par défaut)

### Infrastructure
- **NotificationService.DispatchToExternalChannelsAsync** : filtre par `IsEventTypeSubscribed()` avant envoi email/ntfy
- Priorité ntfy calculée via `EventTypePriorityMap.GetPriority()` et passée à `NtfyService`

### UI (Profile.razor)
- Checkboxes par type d'événement dans la section Notifications
- Texte explicatif : « Si aucun n'est sélectionné, tous les événements sont notifiés »
- Sauvegarde via `UpdateNotificationConfigRequest.SubscribedEvents`

### Tests
- 10 tests Domain : `UserNotificationConfig` (GetSubscribedEvents, IsEventTypeSubscribed, cas limites JSON invalide/vidé/unknown)
- 1 test Domain : `EventTypePriorityMap` (couvre les 8 EventTypes + null)
- 3 tests Infrastructure : filtrage par abonnement + priorité ntfy + filtre vide

## Vérification

- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 161 passed
- Infrastructure.Tests : 180 passed
- Application.Tests : 421 passed
- Web.Tests : 243 passed
- Agent.Tests : 206 passed
- Total : 1211 tests ✅

Closes #61

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/154
2026-08-20 15:10:37 +02:00
Arnaud Dartois 4792b69e46 feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte

Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH.

## Changements

### Nouveaux collecteurs (src/Heimdall.Agent/Services/)
- **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2)
- **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation`
- **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU
- **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs
- **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire

### Refonte SystemMetricsProvider
- Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64)
- Uptime machine (`/proc/uptime`) distinct de l'uptime process
- Mémoire swap

### Entité Agent + Migration
- Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible)
- Migration EF `AddAgentTelemetryInventory`

### Transport heartbeat
- Inventaire au register + refresh périodique (5 min, pas à chaque tick)
- Champs JSON pour listes (disques, GPU, interfaces réseau, températures)

### UI Admin (AgentDetail.razor)
- Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges

### Tests
- 40+ tests unitaires : providers, handlers, entité Agent
- Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243)

## Tickets liés
- Fixes #82 — CPU inventory
- Fixes #83 — Mémoire & disque
- Fixes #84 — GPU inventory
- Fixes #85 — OS, conteneur, réseau

## Résultats des tests
- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 149 passed
- Application.Tests : 397 passed
- Agent.Tests : 210 passed
- Web.Tests : 243 passed
- Total : 999 tests ✅

## Checklist
- [x] `dotnet build` vert (TreatWarningsAsErrors)
- [x] Tests unitaires verts
- [x] Migration EF créée
- [x] Champs nullable (rétrocompatible)
- [x] Pas de référence Infrastructure dans les contrôleurs
- [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
2026-08-20 14:13:06 +02:00
Arnaud Dartois f7e6b0cec3 feat(vehicles): API /api/vehicles - contrôleur + recherche par plaque (#150)
Résumé

Implémentation complète de l'API Vehicles (Phase 17 spec) : contrôleur REST + handlers CQRS MediatR.

Endpoints

GET /api/vehicles - Liste avec recherche par plaque (?search=XX-XXX-XX) + pagination
GET /api/vehicles/{id} - Détail avec historique events (50 derniers) + personne associée
POST /api/vehicles - Créer un véhicule
PUT /api/vehicles/{id} - Mettre à jour + associer/dissocier une personne
DELETE /api/vehicles/{id} - Supprimer un véhicule

Fichiers modifiés/créés

- src/Heimdall.Domain/Entities/Vehicle.cs - AssignPerson accepte Guid? (permet unassign)
- src/Heimdall.Infrastructure/Security/AppPermissions.cs - VehicleRead/VehicleWrite ajoutés
- src/Heimdall.Application/DTOs/VehicleDto.cs - Response, Request, EventSummary
- src/Heimdall.Application/Vehicles/ - Commands + Queries + Mapping
- src/Heimdall.Web/Controllers/VehiclesController.cs - 5 endpoints
- tests/Heimdall.Application.Tests/Handlers/Vehicles/ - 16 tests unitaires

Tests

Build 0 erreurs 0 warnings
16 nouveaux tests unitaires
Suite complète ~1149 tests 0 échec

Closes #9

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/150
2026-08-20 07:34:49 +02:00
Arnaud Dartois 66cec88e6e feat(notifications): complète le paramétrage ntfy (serveur + utilisateur) (#152)
## What
Complète le paramétrage des notifications ntfy (serveur + utilisateur, UI + backend).

## Why
L'issue #60 demandait un paramétrage complet. Le code existant avait des bugs et des manques :
- Le lookup DB de l'URL ntfy ratait à cause d'un mismatch de casing (`ntfy.baseUrl` vs `ntfy.baseurl`)
- L'override URL par utilisateur (`UserNotificationConfig.NtfyUrl`) n'était jamais utilisé lors de l'envoi
- La page profil n'affichait pas le topic ntfy à s'abonner
- Le test ntfy n'envoyait pas le topic de l'utilisateur

## Changes
- **Fix casing** : `NtfyService.ResolveConfigAsync` lit maintenant `ntfy.baseurl` (lowercase) pour correspondre à ce que l'UI écrit
- **Per-user URL override** : `INtfyService` accepte un `baseUrl` optionnel ; `NotificationService` passe `config.NtfyUrl` lors de l'envoi
- **Profile.razor** : affiche le topic ntfy personnalisé (`heimdall_{userId}`) + bouton "Tester ntfy" qui envoie vers le topic de l'utilisateur
- **HeimdallApiClient** : `TestNtfyAsync` accepte et envoie le topic dans le body
- **SendNotificationJob** : transmet le paramètre `baseUrl`

## Testing
- `dotnet build` : 0 erreurs, 0 warnings
- 963 tests unitaires passent (Domain 142, Application 391, Infrastructure 177, Agent 197, Web 243, Api 2)

Closes #60

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/152
2026-08-19 23:06:51 +02:00
Arnaud Dartois b0cfd50c3f feat(api-keys): API key management endpoint + admin UI (#149)
## Summary

Adds API key management functionality to Heimdall:

- **CQRS Handlers**: CreateApiKey, ListApiKeys, RevokeApiKey
- **Controller**: ApiKeysController with admin authorization (Admin.ApiKeys policy)
- **UI**: ApiKeysPage.razor admin page with create, list, and revoke
- **Auth**: Updated ApiKeyAuthenticationHandler to reject expired keys
- **Tests**: 10 unit tests for all handlers

## Changes

- `src/Heimdall.Application/ApiKeys/` — New CQRS handlers and DTOs
- `src/Heimdall.Web/Controllers/ApiKeysController.cs` — Admin API endpoints
- `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor` — Admin UI
- `src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs` — Expiry check
- `src/Heimdall.Web/Services/HeimdallApiClient.cs` — API client methods
- `tests/Heimdall.Application.Tests/Handlers/ApiKeys/` — Unit tests

## Acceptance Criteria

- [x] POST /api/api-keys → key created (plain shown once, hash in DB)
- [x] GET /api/api-keys → prefix only (never the full key)
- [x] DELETE /api/api-keys/{id} → key revoked immediately
- [x] Expired keys rejected by auth handler
- [x] Admin UI with create, list, and revoke functionality
- [x] All tests passing (10 new tests)

Closes #10

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/149
2026-08-19 22:47:22 +02:00
Arnaud Dartois 566aa84bc7 chore: auto-commit 2026-08-12 20:05 [Heimdall] src/Heimdall.Agent/Services/AgentRegistrationService.cs, src/Heimdall.Agent/Services/SnapshotPipelineService.cs, src/Heimdall.Application/DTOs/SettingDto.cs, src/Heimdall.Domain/Entities/UserNotificationConfig.cs, src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs… 2026-08-12 20:05:12 +02:00
Arnaud Dartois dc8a24918d feat(settings): topic ntfy par site, SMTP/ntfy/S3 globaux, DSN GlitchTip fixe + toggle (Fixes #105 #106 #107 #108)
#105 — Topic ntfy cible par site :
- Site.NtfyTopic (migration AddSiteNtfyTopic), UI création/édition SitesPage
- NotificationService.ResolveNtfyTopicAsync : topic du site sinon heimdall_{userId}

#106 — Paramètres SMTP/ntfy/S3 GLOBAUX :
- Seed + sections UI : agentScoped=false pour ntfy.*/email.*/storage.*/sentry.*
- Migration douce au démarrage : UPDATE des clés existantes en base

#107 — GlitchTip : DSN fixes (central projet 6, agent projet 7) dans appsettings,
- plus de champ DSN éditable en UI → switch sentry.enabled (nécessite redémarrage)
- Init Sentry déplacé après AddInfrastructure, lit sentry.enabled en base (fallback true)

#108 — Composants typés : MudNumericField borné (port SMTP, rétention, heartbeat),
- switch pour booléens, select pour log.level — pas de saisie libre
2026-08-12 12:18:52 +02:00
Arnaud Dartois 85bfdac7ee feat(settings): boutons Tester email/ntfy/IA + clés techniques masquées (partiel #80)
- Endpoints POST api/settings/{email,ntfy,ai}/test (Admin) :
  - email : envoi réel via EmailService vers l'expéditeur configuré
  - ntfy : SendTestAsync (nouvelle méthode INtfyService, retour HTTP 2xx)
  - ai : ping CodeProject.AI/Ollama via AiHealthCheck
- Client API : TestEmailAsync/TestNtfyAsync/TestAiAsync + record TestActionResult
- UI : boutons Tester dans NotificationSettingsSection (ntfy + email) et
  AiSettingsSection (moteurs IA) avec résultat inline
- AgentDetail : la clé brute n'est plus affichée (libellé global/surchargé)
- Tests bUnit : 3 nouveaux (POST par endpoint + affichage résultat) — 224 verts
2026-08-12 11:50:47 +02:00
Arnaud Dartois 97d0b76a5e feat(settings): NtfyService/EmailService/AiHealthCheck lisent les AppSettings (partiel #80)
- Source de vérité DB (ntfy.*, email.*, ai.cpaiUrl, ai.ollamaUrl) avec
  fallback config/env pour migration douce — relu à chaque appel, une
  modification UI est prise en compte sans redémarrage
- Nouveau helper AppSettingReader (lecture async + parse int/bool, silencieux
  si DB indisponible), pattern StorageProviderFactory (scope + DbContext)
- Les env vars restent en fallback uniquement
2026-08-12 11:04:04 +02:00
Arnaud Dartois a8d665dc78 chore: auto-commit 2026-08-12 11:00 [Heimdall] src/Heimdall.Infrastructure/Settings/ 2026-08-12 11:00:55 +02:00
Arnaud Dartois 7d6213696f feat(storage): stockage configurable par l'IHM — providers Fichier + S3 (Fixes #78)
- IStorageProvider (Application) : Upload/Download/Delete/DeleteBatch/Health
- LocalStorageProvider : écriture atomique (tmp + move), anti path-traversal
- AlarikStorageProvider : S3-compatible (AWS SDK, ForcePathStyle), upload
  staging→final (atomique), batch delete 1000/appel (Correctif D6)
- StorageProviderFactory : provider résolu depuis les settings DB
  (storage.provider = Local|S3) avec fallback env, re-résolu à chaque appel
- Seed idempotent des clés storage.* (catégorie 'storage') au démarrage
- UI : section 'Stockage' dédiée dans SettingsPage (sélecteur Local/S3,
  champs conditionnels, clé secrète masquée, bouton Tester → POST
  /api/settings/storage/test)
- Tests : 6 LocalStorageProvider (roundtrip, delete, batch, traversal,
  health) ; Web 217/217, Infrastructure 177/177, Application 391/391
2026-08-12 10:14:40 +02:00
Arnaud Dartois 2e188e4dda chore: auto-commit 2026-08-12 10:00 [Heimdall] docs/MASTER_SPECIFICATION.md, docs/README.md, docs/codeproject-ai.md, docs/signalr-usage.md, docs/specs.md… 2026-08-12 10:00:44 +02:00
Arnaud Dartois 381410510f feat(health): health checks complets /health/ready + /health/live (Fixes #13)
- Checks enregistrés : PostgreSQL (ready+live), Alarik S3 (ready),
  CodeProject.AI/Ollama (live) — optionnels → Healthy si non configurés
- Routes : /health (alias /healthz), /health/ready (alias /readyz),
  /health/live → 503 + degradationLevel quand IA dégradée
- Fix CI : dashboard Hangfire skip en Testing (Hangfire désactivé → crash
  au démarrage WebApplicationFactory) — IntegrationTests 125/125 verts
2026-08-12 09:54:37 +02:00
Arnaud Dartois e3d14eec04 feat(jobs): jobs Hangfire rétention/cleanup + dashboard admin (Fixes #8)
- RetentionCheckJob (quotidien 3h) : purge enregistrements expirés par
  StoragePolicy via ExecuteDelete (1 requête, pas de boucle), défaut 30 j
- CleanupUnknownFacesJob (dim 5h) : personnes 'unknown' > 30 j
- CleanupLicensePlatesJob (dim 6h) : plaques non associées > 30 j
- DatabaseMaintenanceJob (dim 7h) : VACUUM events + REINDEX (VACUUM FULL
  1er dimanche)
- Dashboard Hangfire /hangfire protégé AdminJobs (filtre custom)
- S3CleanupJob dépend du ticket #7 (stockage S3) — non inclus ici
- Tests : 2 (rétention avec/sans politique)
2026-08-12 09:43:45 +02:00
Arnaud Dartois 0c7bb86eae feat(logs): purge des logs agents — AgentLogCleanupJob Hangfire (Fixes #53)
- Job quotidien 4h : supprime les AgentLogEntry plus vieux que la rétention
  (Logs:RetentionDays, défaut 7 j), par lots de 5000 + pause 100 ms
  (pas de verrou long ni de transaction log explosée)
- Enregistré dans JobSetup + DI BackgroundJobs
- Tests : 2 (purge des vieux uniquement, rien si rien de vieux)
2026-08-12 09:29:03 +02:00
Arnaud Dartois e14e4cde78 feat(discovery): base caméras Strix — DB SQLite embarquée 100k+ patterns (Fixes #64)
- cameras.db récupérée depuis l'image Docker eduard256/strix (MIT © 2025 eduard256,
  /app/cameras.db) : 3 688 marques, 17 313 streams, 73 238 modèles, 4 186 presets, 2 406 OUIs
- SqliteCameraDatabase (Microsoft.Data.Sqlite pur managé, Alpine-safe) :
  Search (presets+brands+models, multi-mots), BuildStreams (ids b:/m:/p:,
  placeholders [CHANNEL]/[USERNAME]/[PASSWORD]..., portFilter), LookupOui
- Copiée en Content CopyToOutputDirectory → dispo Central + Agent + tests
- Central : SearchDatabase/BuildStreamUrls/ResolveOuiVendor préfèrent la DB
  (fallback catalogue statique + templates)
- Agent : BuildCandidateUrls utilise les patterns réels de la marque (DB) sinon templates
- Tests : 10 (search marque/modèle/preset, build URLs, portFilter, OUI)
2026-08-12 08:45:18 +02:00
Arnaud Dartois 4d783b6ff7 fix(discovery): répare build CI + complète screenshots de vérification (Fixes #65)
- DiscoveryController : using Heimdall.Application.Services manquant → CS0246 (crash CI run 1728)
- GetScreenshotAsync réel : délègue au StreamTesterService (screenshots en session TTL 10 min)
- Popup DiscoveriesPage : aperçu <img> du flux quand HasScreenshot (endpoint results/{id}/screenshot)
- PendingDiscoveryItem client : champ HasScreenshot

Bloc #65 complet : capture ffmpeg agent → ScreenshotBase64 → cache mémoire central
(10 min) → endpoint JPEG → aperçu popup avant confirmation.
2026-08-12 08:17:06 +02:00
Arnaud Dartois 6df44cb9e0 chore: auto-commit 2026-08-11 22:57 [Heimdall] src/Heimdall.Agent/Services/NetworkCameraScanner.cs, src/Heimdall.Application/DTOs/SiteCredentialDto.cs, src/Heimdall.Application/Services/ICameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs… 2026-08-11 22:57:42 +02:00
Arnaud Dartois ac1871e8d9 feat(agent): test de flux multi-protocoles — RTMP, Bubble/Uniview, HomeKit (Fixes #67)
- RTMP : handshake minimal C0/C1 (0x03 + 1536 octets) — serveur qui répond C0 = vivant
- Bubble (Uniview) : TCP + requête HTTP tramée (préambule binaire 8 octets, go2rtc pkg/bubble) + vérif HTTP/1.1 200
- HomeKit : TCP + GET /accessories — toute réponse HTTP (200/401/470) prouve un service HAP vivant
- StreamTesterService central : dvrip/bubble/homekit acceptés (TCP reachable)
- Timeouts explicites Task.WhenAny partout (jamais de hang, cf. 491a253)
- Tests : 4 (serveurs TCP factices RTMP/HTTP)
2026-08-11 22:25:59 +02:00
Arnaud Dartois 84c3e3682f feat(discovery): ports de scan élargis + portFilter par protocole (Fixes #68)
- Agent : 22 ports probés (ajout 8080/5544/10554/1935/81/88/8090/8001/8081/7070/7447/51826)
- CameraStreamTemplates : port par défaut par schéma (rtsp=554, rtmp=1935, http=80,
  dvrip=34567, bubble=80), filtre de compatibilité protocole → les URLs ne portent
  plus de ports incohérents (ex. RTSP sur :80) ; plus de forçage de ports[0]
- Nouveaux templates : p:rtmp, b:uniview (bubble), b:reolink, dvrip:// dans p:dvrrip/b:dahua
- ProtocolFromUrl : Dvrip/Bubble/HomeKit reconnus côté central
- Tests : 9 tests unitaires CameraStreamTemplates
2026-08-11 22:04:10 +02:00
Arnaud Dartois 29ff980db5 feat(domain): entités métier Vehicle/Recording/LicensePlate/StoragePolicy + relations Event→Vehicle/Recording, Camera→StoragePolicy (Fixes #6) 2026-08-11 21:42:46 +02:00
Arnaud Dartois 59a864bdfc feat(auth): codes de récupération 2FA — 10 codes hashés à l'enrôlement, usage unique au login (Fixes #12) 2026-08-11 21:35:52 +02:00
Arnaud Dartois ddfa22bee6 fix(agent): camera discovery — host-network compose, parasite filtering, auto stream detection
- Compose (dev+prod): agent on host network (bridge 172.x was skipped by the
  scanner), listen on 8081 (ntfy owns 8080), CentralUrl via host/domain,
  healthcheck adapted, no Docker DNS
- Scanner: skip the LAN gateway (NAT router, never a camera); wider camera
  ports (+34567/34568 Imou SDK, +8000 Hikvision SDK); 750 ms port timeout;
  keep only devices with real camera evidence; RTSP OPTIONS + MJPEG
  content-type probes prove live streams from the agent (it is on the LAN)
- Central: drop Unknown devices (nginx/gunicorn/gateway) on submit; classify
  37777 DVRIP as Standard camera (not NVR), 8899 alone as NVR; persist
  agent-tested stream URLs flagged IsAlive; shared CameraStreamTemplates
  with the agent so both build identical candidate URLs
- UI: discoveries popup auto-selects the agent-verified main stream — no
  manual stream choice
2026-08-11 20:47:27 +02:00
Arnaud Dartois 0136bf33ec feat(logs): remontée des logs agents vers le central — buffer, API, UI (Fixes #50 #51 #52)
- Agent : LogBufferService (ring buffer borné, drop-oldest), AgentLoggingProvider
  (capture ILogger non-bloquante), LogSanitizer (masque password/token/secret/bearer),
  LogUploadService (batch POST /api/agents/{id}/logs, retry, drop si 400)
- Central : entité AgentLogEntry + migration AddAgentLogEntries (index AgentId+TimestampUtc),
  SubmitAgentLogsCommand (batch <= 200, entrées invalides ignorées),
  GetAgentLogsQuery (pagination, filtres niveau/période/recherche),
  endpoints POST + GET /api/agents/{id}/logs
- UI : onglet Logs dans AgentDetail (filtres, pagination, auto-refresh toggle)
- Logs agent enrichis : heartbeat succès (Debug), résolution IP (Debug)
- Tests : LogBufferServiceTests (6), AgentDetailLogsTests (4), handlers AgentLogs (8)
2026-08-11 18:51:52 +02:00
Arnaud Dartoisandnonobis f8f2b08d29 feat(agent): enrichissement ONVIF authentifié côté agent — pool chiffré via config (#49)
## What

L'enrichissement ONVIF authentifié est déplacé côté **agent**. Le pool de credentials du site (login/mdp) est exposé à l'agent via `GET /api/settings/agent/{id}` sous forme d'enveloppe AES-256-GCM (`AgentCredentialEnvelope`, clé dérivée du SHA-256 de l'API key) — déchiffrable uniquement côté agent. `NetworkCameraScanner` tente `GetDeviceInformation` avec chaque couple du pool (PasswordDigest puis PasswordText) et remonte des devices **déjà identifiés** (fabricant/modèle ONVIF + `CredentialLabel`). Le central persiste et marque le credential utilisé (`LastUsedAt`) — plus aucun appel réseau ONVIF côté central.

## Why

Le central n'est généralement **pas** sur le réseau des caméras : les appels ONVIF authentifiés qu'il faisait après réception des devices bruts échouaient. L'agent, lui, est sur le sous-réseau des caméras — c'est lui qui doit porter l'auth. Enrichissement et identification se font au moment du scan, avant la remontée.

## How

- `AgentCredentialEnvelope` (Application/Security) : AES-256-GCM, clé = SHA-256 de l'API key ; central chiffre (via l'`ApiKeyHash` stocké), agent déchiffre (via sa clé en clair).
- `GetEffectiveAgentConfigQuery` : ajoute `discovery.credentials` (pool chiffré) au dict de config.
- `SettingsController.GetEffectiveConfig` : accepte l'API key agent (vérification par site) en plus du JWT admin — corrige au passage un 403 latent sur cet endpoint.
- `NetworkCameraScanner` : probe ONVIF authentifié avec le pool (anonyme d'abord, puis chaque couple).
- `AgentCredentialStore` (mémoire, jamais sur disque) : reçoit le pool déchiffré par `ConfigReceiverService`, lu par `AgentDiscoveryService`.
- `CameraDiscoveryService` : suppression de l'enrichissement réseau ; persistance + `MarkUsed` via `CredentialLabel` ; vendor déduit du fabricant ONVIF remonté.
- `SitesController` : broadcast `ConfigReload` après add/delete credential pour que les agents re-fetch leur pool.
- Multi-agents : inchangé — upsert par (site, IP) et anti-doublon IP/MAC à la confirmation évitent les caméras en double même si un agent est éteint.

## Testing

- `dotnet build Heimdall.slnx` : 0 erreur / 0 warning.
- Application 346 verts, Agent 108 verts, Infrastructure 143 verts (hors Testcontainers).
- Web.Tests 213 verts — nouveaux bUnit : DiscoveriesPage (5) + SiteDetail credentials (4).

## Breaking Changes

Aucun changement de schéma (pas de migration). Comportement API : `GET /api/settings/agent/{id}` accepte désormais l'API key agent (accès élargi au cas d'usage prévu).

Related to #48

Co-authored-by: nonobis <nonobis@tordais.cc>
Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/49
2026-08-11 16:15:41 +02:00
Arnaud Dartois 0b55360ad2 feat(settings): paramètres agent-scoped + configuration agent en cartes visuelles
- Flag AgentScoped sur AppSetting (entité + migration AddAgentScopedSetting
  + DTO + commandes Create/Update + validateurs + client Web)
- Écran Configuration : toggle 'Exposé aux agents' à la création
- AgentDetail : n'affiche que les globaux agent-scoped, par catégories en
  cartes visuelles avec badge Hérité (global) / Surchargé pour cet agent,
  édition inline → crée l'override, bouton restore → retour à la valeur
  globale. Tests bUnit (3) : héritage, surcharge, réinitialisation.
- Tests validateur : aliases boolean/number/integer/dropdown
2026-08-10 20:51:57 +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 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 afc1b2e032 fix: resolve demo admin seeding, Sentry DSN pass-through, and add startup diagnostics
- Replace IsDevelopment() guard with Seed:DemoOnStartup config flag
  (default: true, disable via SEED__DEMO_ON_STARTUP=false)
- Add Seed:AdminLogin (env SEED__ADMIN_LOGIN) to customize demo admin email
- Add Seed:AdminDisplayName (env SEED__ADMIN_DISPLAYNAME) to customize display name
- Add Sentry__Dsn env var to docker-compose files (matches .env convention)
- Increase Heimdall log level to Debug for startup diagnostics
- Add [DIAG] startup logs for Sentry DSN, Data Protection keys, environment
- Add Data Protection key directory diagnostic in DependencyInjection
2026-07-29 14:21:16 +00: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 450e019617 feat(infra): intégration Sentry/GlitchTip complète
- Upgrade Sentry.AspNetCore v6.7.0 → v6.8.0
- Ajout Sentry base package à Infrastructure (pour SentryErrorReporter)
- Configuration SDK enrichie dans Web et Agent:
  - AutoSessionTracking=false (GlitchTip ne supporte pas)
  - EnableLogs=true (logs structurés)
  - CaptureBlockingCalls=true (détection .Result/.Wait())
  - CaptureFailedRequests=true (capture 4xx/5xx HttpClient)
  - IncludeActivityData=true (DiagnosticSource)
  - SetBeforeSend pour nettoyage PII (password, token, secret)
  - SetBeforeBreadcrumb pour filtrage breadcrumbs
  - SampleRate, AttachStacktrace, MaxBreadcrumbs configurés
  - Release depuis la config, Environment auto
  - StackTraceMode.Enhanced
  - double.Parse avec CultureInfo.InvariantCulture
  - UseSentry avec type explicite SentryAspNetCoreOptions
- Abstraction IErrorReporter dans Application (0 dép. Sentry)
- Implémentation SentryErrorReporter dans Infrastructure
- Enregistrement DI dans Infrastructure
- DSN de développement dans appsettings.Development.json
- .env.example avec Sentry__Dsn et Sentry__TracesSampleRate
2026-07-28 14:52:52 +00:00
Arnaud Dartois 234c158a69 fix(auth): audit de securite complet - 12 correctifs
# Fix #28: ProtectedLocalStorage -> ProtectedSessionStorage
#   (donnees token jamais exposees au JS client en Blazor Server)
# Fix #3: GetUserIdFromExpiredToken valide maintenant la signature
#   (plus de ReadJwtToken sans validation)
# Fix #5: API Key handler X-API-Key uniquement (plus de Bearer ambiguité)
# Fix #7: MarkUsed() persiste via SaveChangesAsync()
# Fix #8: Hardcoded permissions (documenté — nécessite migration DB)
# Fix #12: Race condition registration — try/catch DbUpdateException
# Fix #13: Public registration DESACTIVEE par defaut (pas de setting = disabled)
# Fix #15/17: Enable2fa genere et retourne shared key + QR code URI
# Fix #16: Rate limiting specifique 2FA (5 req/min) et RegisterAdmin
# Fix #22/23: RevokeRefreshToken stocke jti (pas token brut)
# Fix #24: Rotation refresh token — ancien token revoque apres refresh
# Fix #39: Audit logging des echecs de login (via IUserRepository)

Breaking: Enable2fa retourne maintenant Enable2faResponse au lieu de Ok()
2026-07-28 14:37:52 +00:00
Arnaud Dartois 25f51781d4 feat: add SetSettingValueAsync to IAuthDataService 2026-07-28 12:56:18 +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 9e58b5bf55 fix: use SaveChangesWithRetryAsync across all handlers
Replace naked SaveChangesAsync(ct) with the project's own
SaveChangesWithRetryAsync(ct: ct) in 5 locations to handle
PostgreSQL serialization conflicts and SQLite SQLITE_BUSY
transient failures:

- UpdateCameraCommand, CreateCameraCommand, DeleteCameraCommand,
  SetCameraCredentialsCommand, AuthDataService
2026-07-27 18:40:23 +00:00
Arnaud Dartois ec50f6635e fix: remove hardcoded DB password from AppDbContextFactory
The fallback connection string included 'Password=heimdall' as a literal.
Remove the password — the fallback is only for local dev where PostgreSQL
trust authentication is typically used. Production deployments must set
the DATABASE_URL environment variable.
2026-07-27 18:37:54 +00:00
Arnaud Dartois 06927fb9b4 fix: remove stale NtfyToken from migration snapshot
The UserNotificationConfig entity was migrated from Gotify to ntfy
(NtfyUrl replaces GotifyUrl, NtfyEnabled replaces GotifyEnabled).
NtfyToken was never part of the entity but the snapshot still referenced
it, causing PendingModelChangesWarning and 4 integration test failures.

Remove NtfyToken from the Designer.cs and ModelSnapshot.cs to align
the snapshot with the actual entity model.
2026-07-27 18:36:45 +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 ef3ea9d1ca fix: resolve 7 code quality issues from audit
- Add CancellationTokenSource timeout to DB migration loop (5 min)
- Make seed admin password configurable via env/config
- Improve ExceptionFilter with typed exception handling (409/499/500)
- Document Hangfire.PostgreSql CS0618 pragma with upgrade link
- Narrow CredentialProtector fallback catch to non-empty ciphertext
- Fix ApiBaseUrl in appsettings.json (:5000 -> :8080) for Docker consistency
- Improve HTTPS reverse proxy comment in middleware config

Build: 0 errors, 0 warnings | Tests: 799/799 passed
2026-07-26 19:49:42 +00:00
Arnaud Dartois 810900cd3e fix(auth): add JWT__RefreshKey config and env var fallback in JwtService
- Add JWT__RefreshKey to .env.example with documentation
- Add JWT__RefreshKey to docker-compose.yml and docker-compose.prod.yml
- Fix JwtService to check both IConfiguration and env vars (JWT__REFRESHKEY)
  for access token key and refresh token key, matching Program.cs pattern
- Fixes 'Jwt:RefreshKey is not configured' 500 error on register/login
2026-07-25 18:02:43 +00:00