- 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
- 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
## 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
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).
- 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.
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
- 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)
- 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
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.
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
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.
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.
- 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
- 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
Move ConfigureApplicationCookie configuration from DependencyInjection.cs
to Program.cs, ensuring it's called AFTER AddAuthentication().AddCookie().
This prevents Identity default paths (/Account/Login) from overriding
custom login paths (/login).
Add ConfigureApplicationCookie to override Identity default paths
(/Account/Login) with custom paths (/login). This fixes the 404 error
when unauthenticated users are redirected to the login page.
- Remove 13 old service interfaces from Application/Services
- Remove 13 old service implementations from Infrastructure/Services
- Remove old SnapshotService (no CQRS replacement needed)
- Update Infrastructure DI to register only CQRS-compatible services
- Preserve CameraEventService + PersonService for existing tests
- Clean up duplicate IUserRepository registration
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)
- 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)
Add ILogger<AuthService> with log events at every step:
register, login, 2FA, refresh token, password change,
logout, admin registration. All error paths now log
the exact failure reason (validation, Identity errors,
public registration disabled, etc.).
Previously all errors were silently swallowed by the
HeimdallApiClient returning null on non-success responses.
- Remove `using var` from dpCert so the cert stays alive for
ProtectKeysWithCertificate (was disposed, causing
CryptographicException)
- Add query filter on DiscoveredStreamUrl for model warning #10622
- Simplify migration retry: call Migrate() directly instead of
GetPendingMigrations()+Migrate() to reduce transient startup noise
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
The self-signed certificate auto-bootstrap for DataProtection key
encryption ran unconditionally, causing integration tests to crash
with CryptographicException (m_safeCertContext is an invalid handle)
when Identity token providers tried to use the certificate encryptor.
The test environment has no /var/lib/heimdall/dp-keys/ directory, and
loading a PFX with empty password is fragile on Linux — the X509
certificate handle becomes invalid.
Wrap the certificate + file persistence code in the same if (isTesting)
guard already used for the DbContext setup. Tests now use ephemeral
DataProtection keys without certificate encryption.
Generates a self-signed X.509 certificate on first run and stores it
alongside DP keys in the persistent volume. Uses ProtectKeysWithCertificate
to encrypt data protection keys at rest. Prevents the 'No XML encryptor
configured' startup warning.
Adds ValueComparer<float[]> with element-by-element comparison and
snapshot copy. Prevents EF Core warning 10620 about collection types
with value converters but no value comparer.
Adds HasQueryFilter for CameraAssignment (→Agent), CameraDiscoveryResult
(→Site), and CameraEvent (→Camera) to match existing pattern.
Prevents EF Core warning 10622 about required ends with global query
filters.