## 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
272 lines
13 KiB
C#
272 lines
13 KiB
C#
using Heimdall.Application.Agents.Queries.GetAgent;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Application.DTOs;
|
|
using Heimdall.Application.Services;
|
|
using Heimdall.Application.Settings.Commands.CreateAppSetting;
|
|
using Heimdall.Application.Settings.Commands.UpdateAppSetting;
|
|
using Heimdall.Application.Settings.Commands.DeleteAppSetting;
|
|
using Heimdall.Application.Settings.Commands.SetAgentSetting;
|
|
using Heimdall.Application.Settings.Commands.RemoveAgentSetting;
|
|
using Heimdall.Application.Settings.Queries.GetSettings;
|
|
using Heimdall.Application.Settings.Queries.GetSettingByKey;
|
|
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
|
|
using Heimdall.Application.Settings.Queries.GetAgentSettings;
|
|
using Heimdall.Api.Hubs;
|
|
using Heimdall.Infrastructure.Security;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/settings")]
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
|
[EnableRateLimiting("Api")]
|
|
public class SettingsController : ControllerBase
|
|
{
|
|
private readonly IMediator _mediator;
|
|
private readonly IConfigBroadcastService _broadcast;
|
|
private readonly ILogger<SettingsController> _logger;
|
|
|
|
public SettingsController(
|
|
IMediator mediator,
|
|
IConfigBroadcastService broadcast,
|
|
ILogger<SettingsController> logger)
|
|
{
|
|
_mediator = mediator;
|
|
_broadcast = broadcast;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>List all global settings (Admin only).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpGet]
|
|
[ProducesResponseType(typeof(List<AppSettingDto>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
public async Task<IActionResult> ListAll(CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new GetSettingsQuery(), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
// Redact sensitive values before returning to client
|
|
var redacted = result.Data!.Select(s => s with
|
|
{
|
|
Value = RedactValue(s.ValueType, s.Value, s.Key)
|
|
}).ToList();
|
|
|
|
return Ok(redacted);
|
|
}
|
|
|
|
/// <summary>Get a global setting by key (Admin only).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpGet("{key}")]
|
|
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetByKey(string key, CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new GetSettingByKeyQuery(key), ct);
|
|
if (!result.IsSuccess)
|
|
return NotFound(new { error = result.Error });
|
|
|
|
// Redact sensitive values before returning to client
|
|
var redacted = result.Data! with
|
|
{
|
|
Value = RedactValue(result.Data.ValueType, result.Data.Value, result.Data.Key)
|
|
};
|
|
|
|
return Ok(redacted);
|
|
}
|
|
|
|
/// <summary>Create a new global setting (Admin only).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpPost]
|
|
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
public async Task<IActionResult> Create(
|
|
[FromBody] CreateAppSettingRequest request, CancellationToken ct)
|
|
{
|
|
var command = new CreateAppSettingCommand(request.Key, request.Value, request.Category, request.Description, request.ValueType, request.AllowedValues);
|
|
var result = await _mediator.Send(command, ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
|
_logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>Update a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpPut("{key}")]
|
|
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> Update(
|
|
string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
|
|
{
|
|
var command = new UpdateAppSettingCommand(key, request.Value, request.Description, request.Category, request.ValueType, request.AllowedValues);
|
|
var result = await _mediator.Send(command, ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
|
_logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>Delete a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpDelete("{key}")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> Delete(string key, CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new DeleteAppSettingCommand(key), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
await _broadcast.NotifyAllAgentsReload(ct);
|
|
_logger.LogInformation("Deleted global setting {Key}", key);
|
|
return NoContent();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get the effective configuration for an agent: global defaults merged with
|
|
/// 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 = "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)
|
|
: NotFound(new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpGet("agent/{agentId:guid}/overrides")]
|
|
[ProducesResponseType(typeof(List<AgentSettingDto>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> ListAgentOverrides(Guid agentId, CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new GetAgentSettingsQuery(agentId), ct);
|
|
return result.IsSuccess
|
|
? Ok(result.Data)
|
|
: NotFound(new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>
|
|
/// Set (create or update) a per-agent setting override (Admin only).
|
|
/// Broadcasts the change to the affected agent in real-time.
|
|
/// </summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpPut("agent/{agentId:guid}/overrides")]
|
|
[ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> SetAgentOverride(
|
|
Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct)
|
|
{
|
|
var command = new SetAgentSettingCommand(agentId, request.Key, request.Value);
|
|
var result = await _mediator.Send(command, ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct);
|
|
_logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}",
|
|
agentId, result.Data.Key, RedactValue(null, result.Data.Value, result.Data.Key));
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Remove a per-agent setting override (Admin only).
|
|
/// Broadcasts a reload notification to the affected agent.
|
|
/// </summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpDelete("agent/{agentId:guid}/overrides/{key}")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> RemoveAgentOverride(Guid agentId, string key, CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new RemoveAgentSettingCommand(agentId, key), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct);
|
|
_logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key);
|
|
return NoContent();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Broadcast a "ConfigReload" signal to all connected agents so they
|
|
/// re-fetch their full configuration (Admin only).
|
|
/// </summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
|
[HttpPost("reload")]
|
|
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
public async Task<IActionResult> ReloadAllAgents(CancellationToken ct)
|
|
{
|
|
await _broadcast.NotifyAllAgentsReload(ct);
|
|
_logger.LogInformation("Broadcast ConfigReload to all agents");
|
|
return Accepted(new { message = "Config reload broadcast to all connected agents" });
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sensitive key patterns whose values must never be returned to the client.
|
|
/// Centralized list — add new patterns here as needed.
|
|
/// </summary>
|
|
private static readonly string[] SensitiveKeyPatterns =
|
|
["password", "token", "secret", "apikey", "api_key", "credential", "jwt", "privatekey", "connectionstring"];
|
|
|
|
/// <summary>
|
|
/// Sensitive value type patterns whose values must never be returned to the client.
|
|
/// </summary>
|
|
private static readonly string[] SensitiveValueTypePatterns =
|
|
["password", "token", "secret", "key", "credential"];
|
|
|
|
private static string RedactValue(string? valueType, string value, string? key = null)
|
|
{
|
|
if (key is not null && SensitiveKeyPatterns.Any(p =>
|
|
key.Contains(p, StringComparison.OrdinalIgnoreCase)))
|
|
return "***REDACTED***";
|
|
|
|
if (valueType is not null && SensitiveValueTypePatterns.Any(p =>
|
|
valueType.Contains(p, StringComparison.OrdinalIgnoreCase)))
|
|
return "***REDACTED***";
|
|
|
|
return value;
|
|
}
|
|
}
|