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
This commit is contained in:
1 parent
a4503e76ac
commit
f8f2b08d29
46 files changed
+5563
-52
No files matched your search
@@ -1,3 +1,6 @@
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Security;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
@@ -14,18 +17,24 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
private readonly AgentOptions _options;
|
||||
private readonly ILogger<ConfigReceiverService> _logger;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly DiscoveryScanTrigger _scanTrigger;
|
||||
private readonly AgentCredentialStore _credentialStore;
|
||||
private HubConnection? _connection;
|
||||
|
||||
public ConfigReceiverService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
ILogger<ConfigReceiverService> logger,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
IHttpClientFactory httpClientFactory,
|
||||
DiscoveryScanTrigger scanTrigger,
|
||||
AgentCredentialStore credentialStore)
|
||||
{
|
||||
_state = state;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_scanTrigger = scanTrigger;
|
||||
_credentialStore = credentialStore;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
@@ -140,12 +149,45 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
case "log.level":
|
||||
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
|
||||
break;
|
||||
case "discovery.scan.requested":
|
||||
_logger.LogInformation("Camera discovery scan requested by Central");
|
||||
_scanTrigger.Trigger();
|
||||
break;
|
||||
case "discovery.credentials":
|
||||
ApplyCredentialPool(value);
|
||||
break;
|
||||
default:
|
||||
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decrypt the site's camera credential pool shipped by the Central and
|
||||
/// store it for the discovery scanner. Uses the agent's plaintext API key
|
||||
/// (only the agent can open the envelope).
|
||||
/// </summary>
|
||||
private void ApplyCredentialPool(string envelope)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(_state.ApiKey))
|
||||
{
|
||||
_logger.LogWarning("Credential pool received but no API key available — cannot decrypt");
|
||||
return;
|
||||
}
|
||||
|
||||
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(_state.ApiKey);
|
||||
var pool = AgentCredentialEnvelope.Decrypt(envelope, key);
|
||||
_credentialStore.Set(pool);
|
||||
_logger.LogInformation("Camera credential pool updated: {Count} pair(s)", pool.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to decrypt camera credential pool (kept previous pool)");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchFullConfigAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -159,10 +201,23 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
|
||||
var response = await http.GetAsync(url, ct);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogInformation("Full configuration fetched successfully");
|
||||
_logger.LogWarning("Failed to fetch full configuration: {StatusCode}", response.StatusCode);
|
||||
return;
|
||||
}
|
||||
|
||||
var config = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>(ct);
|
||||
if (config is null)
|
||||
{
|
||||
_logger.LogWarning("Full configuration response was empty");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
|
||||
|
||||
if (config.TryGetValue("discovery.credentials", out var envelope))
|
||||
ApplyCredentialPool(envelope);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user