Commit Graph
32 Commits
Author SHA1 Message Date
Arnaud Dartois 88da58723f Store detection snapshots in managed storage
Heimdall Gitea / Build and tests (pull_request) Failing after 1m26s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
2026-10-22 20:50:40 +02:00
Arnaud Dartois d24a20b497 fix(events): filter person history by identity
Heimdall Gitea / Build and tests (pull_request) Failing after 1m24s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
2026-10-22 20:12:25 +02:00
Arnaud Dartois 2b41ab4ea3 fix(storage): record historical object destinations
Heimdall Gitea / Build and tests (pull_request) Failing after 4m57s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
2026-10-22 19:58:55 +02:00
arnaud.dartois 6b887d5fbf Merge pull request 'fix(auth): secure 2FA challenges and session revocation' (#5) from audit-auth-session into main
Validation intégrée avec profils/failover : Infrastructure 305/305 (dont upgrade/rollback migrations combinées), Application 504/504. Branche auth Web389/389 et PostgreSQL auth3/3 ; révocation abonnements inter-contextes11/11. Galerie #10 suit séparément.
2026-10-20 07:38:58 +02:00
Arnaud Dartois 26321bb81c fix(auth): secure 2FA challenges and session revocation 2026-10-20 07:21:28 +02:00
Arnaud Dartois 8c6ecccf49 fix(pipeline): version detection profiles and resync camera configuration 2026-10-20 02:27:19 +02:00
Arnaud Dartois acf3a4304c fix(ci): réduire artifact build + corriger URL YOLO ONNX (#181) 2026-08-30 09:45:37 +02:00
Arnaud Dartois e0290c8a1b feat(db): partitionnement camera_events + gestion automatique des partitions mensuelles (#164) 2026-08-27 00:31:12 +02:00
Arnaud Dartois 6eae4eea2f feat(agent): détection GPU + heartbeat étendu + badges Admin UI (#160) 2026-08-26 23:52:16 +02:00
Arnaud Dartois 7a89a97bf3 feat(notifications): add user-configurable ntfy to 2026-08-20 18:14:46 +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 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 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 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 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 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 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 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 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 129a6148f5 feat(persons): add person manager with known face registry and CRUD API 2026-07-19 15:28:38 +00:00
Arnaud Dartois 358443ff1a feat(events): implement camera event pipeline with AI detection storage
Adds the foundation for AI-powered detection events storage, query,
and snapshot management. Agents can POST detection events (motion,
person, vehicle, face, etc.) with confidence scores and metadata;
users can query, filter, and view event history.

- CameraEvent entity with EF Core configuration + migration
- ICameraEventService / CameraEventService with paged query + filters
- EventsController: 5 REST endpoints (create, get, query, attach snapshot, delete)
- Agent-side CameraStreamService: FFmpeg-based RTSP frame capture (foundation)
- Supports both ApiKey (agent) and JWT (user) authentication
2026-07-19 12:55:05 +00:00
Arnaud Dartois 159da2ca26 feat(assign): implement camera-to-agent assignment with failover and strategy support
Multi-agent sites need automatic camera distribution, failover when
an agent goes offline, and rebalancing when new agents join.

Adds CameraAssignment entity with audit trail, 4 assignment strategies
(RoundRobin, GpuPriority, LeastCameras, Failover), a Hangfire failover
job that checks for stale heartbeats every 60s, a discovery coordinator
for leader election, 6 REST endpoints, EF migration, and DI registration.
2026-07-19 12:20:07 +00:00
Arnaud Dartois 57b51f403c feat(web): add profile, roles, groups and claims pages 2026-07-19 06:49:17 +00:00
Arnaud Dartois abf8162824 fix(db): fix index filter casing in all migration snapshots
Fix the filtered index column name casing in ALL .Designer.cs files
and AppDbContextModelSnapshot.cs:
  - "status" → "Status" (Agent.LastHeartbeat index)
  - "is_deleted" → "IsDeleted" (Site.IsDeleted index)

These must match the actual column names (PascalCase) since
PostgreSQL quoted identifiers are case-sensitive.

Also fix the InitialCreate migration .cs file directly.
All 10 references across 5 snapshot files corrected.
2026-07-18 20:11:19 +00:00
Arnaud Dartois c2837af089 feat(mvp): complete MVP hardening — API, Web, config system, SignalR, tests 2026-07-18 18:58:20 +00:00
Arnaud Dartois ec45fa3c87 fix(perf): eliminate N+1 in AuditLogService by adding User navigation property
Added AppUser navigation property to AuditLog entity with EF Core
configuration (FK -> UserId, SetNull on delete). Replaced the sub-query
in AuditLogService ListAsync with a direct navigation property access,
enabling EF Core to generate a single LEFT JOIN instead of N sub-queries.

Migration: AddAuditLogUserRelation
2026-07-17 19:24:07 +00:00
Arnaud Dartois 7a71a09102 fix(api): replace lockout with MustChangePassword flag in ResetPasswordAsync
Setting LockoutEnd to UtcNow locked the user out instead of forcing
a password change. Added MustChangePassword boolean to AppUser entity
with EF Core migration. ResetPasswordAsync now sets this flag instead
of locking the account.
2026-07-17 19:21:12 +00:00
Arnaud Dartois b217c932e8 feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering:
- Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums
- EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration
- Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern
- Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation
- API: Auth/Sites/Agents controllers with explicit auth scheme policies
- Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob
- Agent: registration service + 30s heartbeat loop
- Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml
- CI/CD: GitHub Actions pipeline with build+test and Docker build
- Tests: 13 domain tests (Site, Agent, Camera entities)

Architecture decisions per deliberation council:
- API Key via AuthenticationHandler<T> (not middleware)
- Explicit [Authorize(AuthenticationSchemes)] on all endpoints
- Event/Recording/Person/Vehicle deferred from initial migration
- Hangfire compatible with .NET 10 (v1.8.17)
2026-07-16 20:53:56 +00:00