Commit Graph
16 Commits
Author SHA1 Message Date
Arnaud Dartois 1cd4e2b4b5 fix(security): enforce resource isolation across API and hubs 2026-10-20 07:16:44 +02:00
Arnaud Dartois 58b6a1de9b feat(app): implement all open issues - camera access control, i18n, GPU, mDNS, site filtering
- Implement UserCameraAccess entity and CRUD API (issues #131, #133)
- Add CameraAccessPanel UI component for granular access management (issue #134)
- Implement camera toggle UI (issues #59, #199)
- Implement site filtering by user rights (issue #136)
- Implement Groups camera access assignment (issue #138)
- Implement audit logging for camera access changes (issue #140)
- Add comprehensive camera access test coverage (issue #141)
- Implement i18n/l10n localization infrastructure (issue #142)
- Implement OpenTelemetry metrics infrastructure (issue #14)
- Implement Agent GPU worker (issue #76)
- Implement Agent remote sensor mode (issue #75)
- Fix Docker GPU exposure in compose files (issues #76, #77)
- Fix mDNS divergence by extracting shared MdnsClient library (issue #81)
- Implement User email confirm/edit UI (issues #88, #89)
- Implement Persons UI (issue #11)
- Fix E2E test timing issues by increasing circuit delay

- Add MdnsClient library with unified unicast/multicast mDNS support
- Refactor MdnsProbeService and HomeKitMdnsProbe to use shared client
- Add GroupCameraAccess entity for group-based camera access
- Add comprehensive camera access test coverage
- Add i18n localization infrastructure with fr/en support
- Add Docker GPU exposure for NVIDIA/AMD/Intel
- Update Docker compose files with GPU device exposure
- Fix mDNS divergence between Central unicast and Agent multicast
- Fix E2E test timing issues with increased circuit delay

All 1700+ tests pass (unit + integration)
2026-10-11 21:23:16 +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 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 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 c0768b3804 feat(agent): test de flux DVRIP — handshake login Sofia MD5 (Fixes #66)
- IsDvripUrlAliveAsync : connexion TCP + login DVRIP-Web (paquet 20 octets,
  cmd=1000), hash Sofia (md5 + mapping 62 chars) transposé de go2rtc pkg/dvrip
- Ret=100/515 = caméra DVRIP vivante (login prouve identifiants + canal)
- Timeouts explicites Task.WhenAny (jamais de hang, cf. 491a253)
- p:dvrrip ajouté aux candidates quand 34567/34568/37777 ouvert
- ProtocolFromUrl : dvrip:// → StreamProtocol.Dvrip (déjà fait #68)
- Tests : 4 (SofiaHash vecteur go2rtc, layout paquet, payload login, ctor)
2026-08-11 22:22:31 +02:00
Arnaud Dartois e5b035745d feat(agent): découverte mDNS/HomeKit — probe multicast _hap._tcp (Fixes #62)
- HomeKitMdnsProbe : paquet DNS PTR brut sur 224.0.0.251:5353, écoute 2 s
  avec timeout explicite Task.WhenAny (jamais de hang, cf. 491a253)
- Parseur DNS complet : PTR/SRV/TXT/A avec pointeurs de compression, TXT
  (ci/id/md/sf), dédup par IP, mapping IP via SRV target
- Filtre catégories 17 (camera) et 18 (doorbell) — Strix pkg/probe/mdns.go
- Intégré au scan broadcast de NetworkCameraScanner ; devices HomeKit avec
  HomeKitName/HomeKitDeviceId/HomeKitModel remplis → classés HomeKit côté central
- Les devices HomeKit ne génèrent plus de fausses URLs RTSP (flux HAP)
- Tests : 4 (parseur PTR/SRV/TXT/A, filtrage catégories, dédup, no-hang)
2026-08-11 22:16:19 +02:00
Arnaud Dartois f713abc7ca feat(discovery): reverse DNS pour le hostname des devices détectés (Fixes #63)
- ResolveHostnameAsync : PTR via Dns.GetHostEntryAsync avec timeout 500 ms,
  échec silencieux (le scan n'est jamais bloqué par un DNS lent)
- Fallback uniquement : le hostname ONVIF/DVRIP/mDNS existant est conservé
2026-08-11 22:06:10 +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 33a08f5ea0 fix(agent): async UDP receive hangs — explicit timeout via Task.WhenAny
Refs #54 #55 #56

Socket.ReceiveTimeout only applies to synchronous Receive() — the async
ReceiveAsync(ct) on the ONVIF multicast, DVRIP broadcast and unicast
ONVIF probe waited forever when no camera replied, so a scan never
completed (no response → hang). Enforce the listen window explicitly
with Task.WhenAny(receiveTask, Task.Delay(...)):

- WS-Discovery multicast: 5s listen window
- DVRIP broadcast: 2s listen window
- unicast ONVIF probe: OnvifUdpTimeout (500ms)

Also fixed ValueTask→Task (.AsTask()) for the WhenAny overload.
2026-08-11 21:36:48 +02:00
Arnaud Dartois 9e64b03f31 feat(agent): auto main stream via ONVIF GetProfiles/GetStreamUri
Fixes #56

The agent asks the camera for its REAL stream URLs instead of guessing
from templates: GetProfiles (media service) then GetStreamUri per profile
(RTP-Unicast/RTSP), trying the site credential pool (anonymous → digest →
text). The returned URLs get the probed IP injected (buggy 0.0.0.0 or
different host) and the credentials embedded, so the Central gets a
directly usable main stream.

- Generalized BuildSoapEnvelope/PostSoapAsync for device + media services
- OnvifProbe carries StreamUrls; ProbeHostAsync and the WS-Discovery
  multicast enrichment both fill them
- BuildFinalDeviceAsync prioritizes real GetStreamUri URLs over templates
  and keeps them even if the stream test fails (camera proven by ONVIF)
- Refactored TestUrlsAsync shared by both paths
2026-08-11 21:18:26 +02:00
Arnaud Dartois ea773b17a1 feat(agent): Dahua/Imou DVRIP broadcast discovery
Fixes #55

Sends the DVRIP probe (ff00000000000000000000000000fa0500000000) 3x over
UDP broadcast on port 34569 and parses the NetWork.NetCommon JSON replies
(HostIP, HostName, MAC, HttpPort, Ret). Finds Dahua/Imou cameras even
when RTSP/ONVIF are disabled, with MAC/vendor from the reply itself.

- Filter Ret != 100 error replies, require HostIP+HostName
- Devices are created with OpenPorts [37777] (DVRIP) so they pass the
  camera-evidence filter and get classified Standard by the Central
- Transposed from go2rtc internal/dvrip
2026-08-11 21:13:32 +02:00
Arnaud Dartois 1bc4c73f23 feat(agent): ONVIF WS-Discovery multicast camera discovery
Fixes #54

The agent now sends one UDP multicast probe (239.255.255.250:3702) per
scan and collects ONVIF replies for ~5s, instead of relying solely on the
per-IP TCP port sweep. This finds every ONVIF camera on the LAN — even
those with TCP 3702 closed — in one request, with name/hardware from the
WS-Discovery scopes (and the buggy 0.0.0.0 XAddrs fix).

- ScanAsync runs the broadcast probes in parallel with the TCP sweep and
  merges results (dedupe by IP)
- Factorized BuildFinalDeviceAsync (evidence filter + live stream test)
  shared by the TCP sweep and the multicast merge
- Transposed from go2rtc pkg/onvif DiscoveryStreamingDevices
2026-08-11 21:11:45 +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 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