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,5 +1,6 @@
|
||||
using Heimdall.Application.Agents.Commands.RegisterAgent;
|
||||
using Heimdall.Application.Agents.Commands.Heartbeat;
|
||||
using Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
|
||||
using Heimdall.Application.Agents.Queries.GetAgent;
|
||||
using Heimdall.Application.Agents.Queries.GetAgentsBySite;
|
||||
using Heimdall.Application.Agents.Queries.GetAllAgents;
|
||||
@@ -68,6 +69,27 @@ public class AgentsController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Submit network scan results from agent (API Key auth).</summary>
|
||||
/// <remarks>
|
||||
/// The agent probes its local subnet (ports, HTTP, ONVIF WS-Discovery, ARP)
|
||||
/// and posts the raw devices here; the Central enriches each candidate with
|
||||
/// the site's credential pool (authenticated ONVIF) and builds stream URLs.
|
||||
/// </remarks>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpPost("{id:guid}/discovery")]
|
||||
[ProducesResponseType(typeof(AgentDiscoverySubmitResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SubmitDiscovery(
|
||||
Guid id, [FromBody] IReadOnlyList<AgentDiscoveredDevice> devices, CancellationToken ct)
|
||||
{
|
||||
var command = new SubmitAgentDiscoveryCommand(id, devices);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Get agent details (JWT auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
|
||||
@@ -4,10 +4,13 @@ using Heimdall.Application.Discovery.Commands.ConfirmDiscovery;
|
||||
using Heimdall.Application.Discovery.Commands.BuildStreamUrls;
|
||||
using Heimdall.Application.Discovery.Commands.TestStreams;
|
||||
using Heimdall.Application.Discovery.Commands.CancelTestSession;
|
||||
using Heimdall.Application.Discovery.Commands.RequestSiteScan;
|
||||
using Heimdall.Application.Discovery.Commands.RejectDiscovery;
|
||||
using Heimdall.Application.Discovery.Queries.SearchDatabase;
|
||||
using Heimdall.Application.Discovery.Queries.GetTestSession;
|
||||
using Heimdall.Application.Discovery.Queries.GetScreenshot;
|
||||
using Heimdall.Application.Discovery.Queries.CheckDuplicate;
|
||||
using Heimdall.Application.Discovery.Queries.ListPendingDiscoveries;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using MediatR;
|
||||
@@ -170,4 +173,43 @@ public class DiscoveryController : ControllerBase
|
||||
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List pending discovery results for a site (agent-submitted).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("sites/{siteId:guid}")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<PendingDiscoveryResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ListPending(Guid siteId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ListPendingDiscoveriesQuery(siteId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Reject (ignore) a pending discovery result.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{resultId:guid}/reject")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Reject(Guid resultId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new RejectDiscoveryCommand(resultId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Ask the site's online agents to run an immediate network scan.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("sites/{siteId:guid}/scan-now")]
|
||||
[ProducesResponseType(typeof(ScanNowResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ScanNow(Guid siteId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new RequestSiteScanCommand(siteId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Heimdall.Application.Agents.Queries.GetAgent;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
@@ -136,14 +137,35 @@ public class SettingsController : ControllerBase
|
||||
|
||||
/// <summary>
|
||||
/// Get the effective configuration for an agent: global defaults merged with
|
||||
/// per-agent overrides (Agent or Admin only).
|
||||
/// per-agent overrides, plus the site's camera credential pool inside an
|
||||
/// encrypted envelope. Accessible by the agent itself (API key, same site)
|
||||
/// or by an admin (JWT/Cookie).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")]
|
||||
[HttpGet("agent/{agentId:guid}")]
|
||||
[ProducesResponseType(typeof(Dictionary<string, string>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
// API key callers: the agent may only read its own site's config.
|
||||
var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key");
|
||||
if (isApiKey)
|
||||
{
|
||||
var siteClaim = User.FindFirst("site_id")?.Value;
|
||||
if (!Guid.TryParse(siteClaim, out var apiKeySiteId))
|
||||
return Forbid();
|
||||
|
||||
var agentResult = await _mediator.Send(new GetAgentQuery(agentId), ct);
|
||||
if (!agentResult.IsSuccess || agentResult.Data is null)
|
||||
return Forbid();
|
||||
if (agentResult.Data.SiteId != apiKeySiteId)
|
||||
return Forbid();
|
||||
}
|
||||
else if (!User.HasClaim("permission", AppPermissions.AdminManage))
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.SiteCredentials.Queries.ListSiteCredentials;
|
||||
using Heimdall.Application.SiteCredentials.Commands.AddSiteCredential;
|
||||
using Heimdall.Application.SiteCredentials.Commands.DeleteSiteCredential;
|
||||
using Heimdall.Application.Sites.Commands.CreateSite;
|
||||
using Heimdall.Application.Sites.Commands.UpdateSite;
|
||||
using Heimdall.Application.Sites.Commands.DeleteSite;
|
||||
@@ -20,8 +24,13 @@ namespace Heimdall.Api.Controllers;
|
||||
public class SitesController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly IConfigBroadcastService _broadcast;
|
||||
|
||||
public SitesController(IMediator mediator) => _mediator = mediator;
|
||||
public SitesController(IMediator mediator, IConfigBroadcastService broadcast)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_broadcast = broadcast;
|
||||
}
|
||||
|
||||
/// <summary>Create a new site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
@@ -112,4 +121,58 @@ public class SitesController : ControllerBase
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List camera credential pairs declared for this site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<SiteCredentialResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ListCredentials(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ListSiteCredentialsQuery(id), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Add a camera credential pair to this site (used by agent discovery).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(SiteCredentialResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> AddCredential(
|
||||
Guid id, [FromBody] AddSiteCredentialRequest request, CancellationToken ct)
|
||||
{
|
||||
var command = new AddSiteCredentialCommand(id, request.Label, request.Username, request.Password);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
// Les agents du site doivent re-fetch leur config pour recevoir le
|
||||
// nouveau pool de credentials (enveloppe chiffrée) et enrichir les
|
||||
// caméras protégées dès le prochain scan.
|
||||
await _broadcast.NotifyAllAgentsReload(ct);
|
||||
}
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera credential pair from this site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpDelete("{id:guid}/credentials/{credentialId:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteCredential(Guid id, Guid credentialId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new DeleteSiteCredentialCommand(id, credentialId), ct);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
// Idem : les agents doivent purger le couple supprimé de leur pool.
|
||||
await _broadcast.NotifyAllAgentsReload(ct);
|
||||
}
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user