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
@@ -35,6 +35,13 @@ public sealed class AgentOptions
|
||||
[Range(1, 20)]
|
||||
public int RegistrationMaxRetries { get; init; } = 5;
|
||||
|
||||
/// <summary>Interval between automatic camera network scans in seconds (default: 900 = 15 min).</summary>
|
||||
[Range(60, 86400)]
|
||||
public int DiscoveryIntervalSeconds { get; init; } = 900;
|
||||
|
||||
/// <summary>Enable automatic camera discovery on the local network (default: true).</summary>
|
||||
public bool DiscoveryEnabled { get; init; } = true;
|
||||
|
||||
/// <summary>Agent software version reported to Central.</summary>
|
||||
public string Version { get; init; } = "1.0.0";
|
||||
}
|
||||
@@ -61,8 +61,12 @@ builder.Services.AddSingleton<AgentState>(sp =>
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<SystemMetricsProvider>();
|
||||
builder.Services.AddSingleton<NetworkCameraScanner>();
|
||||
builder.Services.AddSingleton<DiscoveryScanTrigger>();
|
||||
builder.Services.AddSingleton<AgentCredentialStore>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
builder.Services.AddHostedService<ConfigReceiverService>();
|
||||
builder.Services.AddHostedService<AgentDiscoveryService>();
|
||||
|
||||
// Health checks — used by Docker HEALTHCHECK
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// In-memory holder for the site's camera credential pool, received from the
|
||||
/// Central inside the encrypted agent config envelope and decrypted locally.
|
||||
/// Shared between <see cref="ConfigReceiverService"/> (writes) and
|
||||
/// <see cref="AgentDiscoveryService"/> / <see cref="NetworkCameraScanner"/>
|
||||
/// (reads). Never persisted to disk.
|
||||
/// </summary>
|
||||
public sealed class AgentCredentialStore
|
||||
{
|
||||
private IReadOnlyList<AgentCameraCredential> _pool = [];
|
||||
|
||||
public IReadOnlyList<AgentCameraCredential> Pool => Volatile.Read(ref _pool);
|
||||
|
||||
public void Set(IReadOnlyList<AgentCameraCredential> pool)
|
||||
=> Interlocked.Exchange(ref _pool, pool ?? []);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Periodically scans the agent's local network for cameras and posts the
|
||||
/// results to the Central (POST /api/agents/{id}/discovery). The agent owns
|
||||
/// the authenticated ONVIF enrichment: it receives the site's credential pool
|
||||
/// through the encrypted agent config (see <see cref="AgentCredentialStore"/>)
|
||||
/// and the scanner identifies protected cameras (ONVIF manufacturer/model)
|
||||
/// before they are posted. The Central only persists the devices.
|
||||
///
|
||||
/// Scan triggers: immediately after registration, then every
|
||||
/// <see cref="AgentOptions.DiscoveryIntervalSeconds"/> seconds, and on demand
|
||||
/// via <see cref="DiscoveryScanTrigger"/> (pushed by Central over SignalR).
|
||||
/// </summary>
|
||||
public sealed class AgentDiscoveryService : BackgroundService
|
||||
{
|
||||
private readonly AgentState _state;
|
||||
private readonly AgentOptions _options;
|
||||
private readonly NetworkCameraScanner _scanner;
|
||||
private readonly DiscoveryScanTrigger _trigger;
|
||||
private readonly AgentCredentialStore _credentialStore;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<AgentDiscoveryService> _logger;
|
||||
|
||||
public AgentDiscoveryService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
NetworkCameraScanner scanner,
|
||||
DiscoveryScanTrigger trigger,
|
||||
AgentCredentialStore credentialStore,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<AgentDiscoveryService> logger)
|
||||
{
|
||||
_state = state;
|
||||
_options = options.Value;
|
||||
_scanner = scanner;
|
||||
_trigger = trigger;
|
||||
_credentialStore = credentialStore;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
// Wait until the agent is registered (has an AgentId + API key).
|
||||
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
|
||||
await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
|
||||
|
||||
if (stoppingToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Camera discovery service started (interval={Interval}s, enabled={Enabled})",
|
||||
_options.DiscoveryIntervalSeconds, _options.DiscoveryEnabled);
|
||||
|
||||
var interval = TimeSpan.FromSeconds(
|
||||
_options.DiscoveryIntervalSeconds > 0 ? _options.DiscoveryIntervalSeconds : 900);
|
||||
|
||||
// Initial scan shortly after registration.
|
||||
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken).ConfigureAwait(false);
|
||||
await ScanAndSubmitAsync(stoppingToken).ConfigureAwait(false);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var delayTask = Task.Delay(interval, stoppingToken);
|
||||
var triggerTask = _trigger.WaitAsync(stoppingToken).AsTask();
|
||||
var completed = await Task.WhenAny(delayTask, triggerTask).ConfigureAwait(false);
|
||||
|
||||
if (completed == triggerTask)
|
||||
_logger.LogInformation("Camera discovery: scan requested by Central");
|
||||
|
||||
await ScanAndSubmitAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Camera discovery cycle failed (will retry)");
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ScanAndSubmitAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_options.DiscoveryEnabled)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var pool = _credentialStore.Pool;
|
||||
var devices = await _scanner.ScanAsync(ct, pool).ConfigureAwait(false);
|
||||
|
||||
using var client = _httpClientFactory.CreateClient("Central");
|
||||
client.DefaultRequestHeaders.Remove("X-API-Key");
|
||||
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
|
||||
|
||||
var response = await client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/discovery", devices, ct).ConfigureAwait(false);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<AgentDiscoverySubmitResponse>(ct).ConfigureAwait(false);
|
||||
_logger.LogInformation(
|
||||
"Camera discovery submitted: {Count} device(s) — {New} new, {Updated} updated",
|
||||
devices.Count, result?.New ?? 0, result?.Updated ?? 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Camera discovery submission failed: {StatusCode} ({Reason})",
|
||||
response.StatusCode, response.ReasonPhrase);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Camera discovery scan/submit error (will retry)");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shared trigger allowing ConfigReceiverService (SignalR "scan now" push)
|
||||
/// to wake the AgentDiscoveryService for an immediate network scan.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryScanTrigger
|
||||
{
|
||||
private readonly Channel<bool> _channel = Channel.CreateBounded<bool>(
|
||||
new BoundedChannelOptions(4) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
|
||||
public void Trigger()
|
||||
{
|
||||
_channel.Writer.TryWrite(true);
|
||||
}
|
||||
|
||||
public ValueTask<bool> WaitAsync(CancellationToken ct) => _channel.Reader.ReadAsync(ct);
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight local-network camera scanner used by the agent.
|
||||
/// The agent lives on the camera network (the Central usually does not), so it
|
||||
/// probes its own subnet: TCP port scan for common camera ports, an HTTP
|
||||
/// header probe, ONVIF WS-Discovery (unicast), and an ARP table lookup for the
|
||||
/// MAC address. When the site's credential pool is available (shipped by the
|
||||
/// Central in the agent config, encrypted), the scanner performs the
|
||||
/// <b>authenticated</b> ONVIF GetDeviceInformation calls itself — protected
|
||||
/// cameras that refuse anonymous probing are identified (manufacturer, model)
|
||||
/// using each credential pair. Raw+enriched results are posted to the Central
|
||||
/// (POST /api/agents/{id}/discovery), which only persists them.
|
||||
/// </summary>
|
||||
public sealed class NetworkCameraScanner
|
||||
{
|
||||
private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777];
|
||||
private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(250);
|
||||
private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2);
|
||||
private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace SoapNs = "http://www.w3.org/2003/05/soap-envelope";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace WsdNs = "http://schemas.xmlsoap.org/ws/2005/04/discovery";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace WsaNs = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace TdnNs = "http://www.onvif.org/ver10/network/wsdl";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace TdsNs = "http://www.onvif.org/ver10/device/wsdl";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
|
||||
|
||||
private readonly ILogger<NetworkCameraScanner> _logger;
|
||||
private readonly string? _localIp;
|
||||
|
||||
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_localIp = GetLocalIpv4();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scan the local subnet for camera-like devices. Returns an empty list
|
||||
/// when the local network cannot be determined. When <paramref name="credentialPool"/>
|
||||
/// is provided, ONVIF device information is fetched with authentication
|
||||
/// (each pair is tried, PasswordDigest then PasswordText) so protected
|
||||
/// cameras are identified with their ONVIF manufacturer/model.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<AgentDiscoveredDevice>> ScanAsync(
|
||||
CancellationToken ct, IReadOnlyList<AgentCameraCredential>? credentialPool = null)
|
||||
{
|
||||
var (subnetCidr, localIp) = GetLocalSubnetCidr();
|
||||
if (subnetCidr is null)
|
||||
{
|
||||
_logger.LogWarning("Camera discovery: unable to determine local subnet, skipping scan");
|
||||
return [];
|
||||
}
|
||||
|
||||
var ips = ExpandSubnet(subnetCidr);
|
||||
_logger.LogInformation("Camera discovery: scanning {Subnet} ({Count} hosts, {Pool} credential pair(s))",
|
||||
subnetCidr, ips.Count, credentialPool?.Count ?? 0);
|
||||
|
||||
var results = new ConcurrentBag<AgentDiscoveredDevice>();
|
||||
using var throttler = new SemaphoreSlim(40);
|
||||
|
||||
var tasks = ips.Select(async ip =>
|
||||
{
|
||||
if (ct.IsCancellationRequested) return;
|
||||
if (ip == localIp) return;
|
||||
|
||||
await throttler.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false);
|
||||
if (device is not null)
|
||||
results.Add(device);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// stop probing
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogTrace(ex, "Probe error for {Ip}", ip);
|
||||
}
|
||||
finally
|
||||
{
|
||||
throttler.Release();
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
|
||||
|
||||
return results.ToList();
|
||||
}
|
||||
|
||||
private async Task<AgentDiscoveredDevice?> ProbeHostAsync(
|
||||
string ip, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
||||
{
|
||||
var openPorts = await ScanPortsAsync(ip, ct).ConfigureAwait(false);
|
||||
if (openPorts.Count == 0)
|
||||
return null;
|
||||
|
||||
HttpProbe? http = null;
|
||||
if (openPorts.Contains(80) || openPorts.Contains(443))
|
||||
{
|
||||
var webPort = openPorts.Contains(80) ? 80 : 443;
|
||||
http = await ProbeHttpAsync(ip, webPort, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
OnvifProbe? onvif = null;
|
||||
if (openPorts.Contains(3702))
|
||||
onvif = await ProbeOnvifAsync(ip, 3702, credentialPool, ct).ConfigureAwait(false);
|
||||
|
||||
var mac = GetArpMac(ip);
|
||||
|
||||
return new AgentDiscoveredDevice(
|
||||
Ip: ip,
|
||||
IsReachable: true,
|
||||
OpenPorts: [.. openPorts],
|
||||
MacAddress: mac,
|
||||
Vendor: null,
|
||||
Hostname: null,
|
||||
HttpServerHeader: http?.ServerHeader,
|
||||
HttpStatusCode: http?.StatusCode,
|
||||
HttpPort: http?.Port,
|
||||
OnvifDeviceServiceUrl: onvif?.DeviceServiceUrl,
|
||||
OnvifName: onvif?.Name,
|
||||
OnvifHardware: onvif?.Hardware,
|
||||
OnvifPort: onvif is not null ? 3702 : null,
|
||||
HomeKitName: null,
|
||||
HomeKitDeviceId: null,
|
||||
HomeKitModel: null,
|
||||
CredentialLabel: onvif?.CredentialLabel);
|
||||
}
|
||||
|
||||
private static async Task<List<int>> ScanPortsAsync(string ip, CancellationToken ct)
|
||||
{
|
||||
var open = new ConcurrentBag<int>();
|
||||
var tasks = CameraPorts.Select(async port =>
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
|
||||
var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
|
||||
if (completed == connectTask && client.Connected)
|
||||
open.Add(port);
|
||||
client.Close();
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
return [.. open.Order()];
|
||||
}
|
||||
|
||||
private async Task<HttpProbe?> ProbeHttpAsync(string ip, int port, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var handler = new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
|
||||
};
|
||||
using var client = new HttpClient(handler) { Timeout = HttpTimeout };
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"http://{ip}:{port}/");
|
||||
request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0");
|
||||
using var response = await client.SendAsync(request, ct).ConfigureAwait(false);
|
||||
|
||||
var serverHeader = response.Headers.TryGetValues("Server", out var values)
|
||||
? string.Join(",", values)
|
||||
: null;
|
||||
return new HttpProbe(port, (int)response.StatusCode, serverHeader);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP probe failed for {Ip}:{Port}", ip, port);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<OnvifProbe?> ProbeOnvifAsync(
|
||||
string ip, int port, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var udp = new UdpClient();
|
||||
udp.Client.ReceiveTimeout = (int)OnvifUdpTimeout.TotalMilliseconds;
|
||||
udp.Connect(ip, port);
|
||||
|
||||
var messageId = Guid.NewGuid().ToString();
|
||||
var probe = $@"<?xml version=""1.0"" encoding=""utf-8""?>
|
||||
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
|
||||
xmlns:wsa=""{WsaNs.NamespaceName}""
|
||||
xmlns:wsd=""{WsdNs.NamespaceName}""
|
||||
xmlns:tdn=""{TdnNs.NamespaceName}"">
|
||||
<soap:Header>
|
||||
<wsa:Action soap:mustUnderstand=""1"">{WsdNs.NamespaceName}/Probe</wsa:Action>
|
||||
<wsa:MessageID soap:mustUnderstand=""1"">uuid:{messageId}</wsa:MessageID>
|
||||
<wsa:To soap:mustUnderstand=""1"">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
<wsd:Probe>
|
||||
<wsd:Types>tdn:NetworkVideoTransmitter</wsd:Types>
|
||||
</wsd:Probe>
|
||||
</soap:Body>
|
||||
</soap:Envelope>";
|
||||
|
||||
await udp.SendAsync(Encoding.UTF8.GetBytes(probe), ct).ConfigureAwait(false);
|
||||
var result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
var xml = Encoding.UTF8.GetString(result.Buffer);
|
||||
|
||||
var doc = XDocument.Parse(xml);
|
||||
var xaddrs = doc.Descendants(XName.Get("XAddrs", WsdNs.NamespaceName))
|
||||
.SelectMany(e => e.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
.ToList();
|
||||
if (xaddrs.Count == 0)
|
||||
return null;
|
||||
|
||||
var deviceServiceUrl = xaddrs[0];
|
||||
var detail = await GetDeviceInformationWithCredentialsAsync(deviceServiceUrl, credentialPool, ct).ConfigureAwait(false);
|
||||
|
||||
return new OnvifProbe(deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel);
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogTrace(ex, "ONVIF probe failed for {Ip}:{Port}", ip, port);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetch ONVIF device information, trying the site credential pool so that
|
||||
/// protected cameras respond. Order: anonymous first (open cameras), then
|
||||
/// each pair of the pool (PasswordDigest, then PasswordText for laxer
|
||||
/// WS-Security implementations). Returns null when nothing works.
|
||||
/// </summary>
|
||||
private async Task<OnvifDetail?> GetDeviceInformationWithCredentialsAsync(
|
||||
string deviceServiceUrl, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
||||
{
|
||||
// 1. Anonymous (cameras without auth or with default-open ONVIF).
|
||||
var anonymous = await GetDeviceInformationAsync(deviceServiceUrl, null, null, null, ct).ConfigureAwait(false);
|
||||
if (anonymous is not null)
|
||||
return anonymous;
|
||||
|
||||
// 2. Credential pool, if provided by the Central.
|
||||
if (credentialPool is not null)
|
||||
{
|
||||
foreach (var credential in credentialPool)
|
||||
{
|
||||
var digest = await GetDeviceInformationAsync(
|
||||
deviceServiceUrl, credential.Username, credential.Password, "PasswordDigest", ct).ConfigureAwait(false);
|
||||
if (digest is not null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"ONVIF auth succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
|
||||
return digest with { CredentialLabel = credential.Label };
|
||||
}
|
||||
|
||||
var text = await GetDeviceInformationAsync(
|
||||
deviceServiceUrl, credential.Username, credential.Password, "PasswordText", ct).ConfigureAwait(false);
|
||||
if (text is not null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"ONVIF auth (PasswordText) succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
|
||||
return text with { CredentialLabel = credential.Label };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<OnvifDetail?> GetDeviceInformationAsync(
|
||||
string deviceServiceUrl, string? username, string? password, string? passwordType, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new HttpClient { Timeout = HttpTimeout };
|
||||
var soap = BuildSoapEnvelope(username, password, passwordType);
|
||||
|
||||
using var content = new StringContent(soap, Encoding.UTF8, "application/soap+xml");
|
||||
using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
|
||||
var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var doc = XDocument.Parse(responseXml);
|
||||
var info = doc.Root?.Element(SoapNs + "Body")?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
|
||||
if (info is null)
|
||||
return null;
|
||||
|
||||
return new OnvifDetail(
|
||||
info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "GetDeviceInformation failed for {Url}", deviceServiceUrl);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build the GetDeviceInformation SOAP envelope, adding a WS-Security
|
||||
/// UsernameToken when credentials are provided (PasswordDigest or
|
||||
/// PasswordText, matching ONVIF interop requirements).
|
||||
/// </summary>
|
||||
private static string BuildSoapEnvelope(string? username, string? password, string? passwordType)
|
||||
{
|
||||
var securityHeader = string.Empty;
|
||||
if (username is not null && passwordType is not null)
|
||||
{
|
||||
if (passwordType == "PasswordDigest")
|
||||
{
|
||||
var nonce = new byte[16];
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
var created = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
|
||||
// ONVIF WS-Security PasswordDigest is defined by the standard to use SHA1
|
||||
// (digest = Base64(SHA1(nonce + created + password))). Required for
|
||||
// interoperability with ONVIF cameras — not used for application security.
|
||||
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
|
||||
var digest = SHA1.HashData([.. nonce, .. Encoding.UTF8.GetBytes(created + password)]);
|
||||
#pragma warning restore CA5350
|
||||
securityHeader = $@"
|
||||
<soap:Header>
|
||||
<Security xmlns=""{WsseNs.NamespaceName}"">
|
||||
<UsernameToken>
|
||||
<Username>{username}</Username>
|
||||
<Password Type=""{WsseNs.NamespaceName}#PasswordDigest"">{Convert.ToBase64String(digest)}</Password>
|
||||
<Nonce>{Convert.ToBase64String(nonce)}</Nonce>
|
||||
<Created>{created}</Created>
|
||||
</UsernameToken>
|
||||
</Security>
|
||||
</soap:Header>";
|
||||
}
|
||||
else
|
||||
{
|
||||
securityHeader = $@"
|
||||
<soap:Header>
|
||||
<Security xmlns=""{WsseNs.NamespaceName}"">
|
||||
<UsernameToken>
|
||||
<Username>{username}</Username>
|
||||
<Password Type=""{WsseNs.NamespaceName}#PasswordText"">{password}</Password>
|
||||
</UsernameToken>
|
||||
</Security>
|
||||
</soap:Header>";
|
||||
}
|
||||
}
|
||||
|
||||
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
|
||||
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
|
||||
xmlns:tds=""{TdsNs.NamespaceName}"">{securityHeader}
|
||||
<soap:Body>
|
||||
<tds:GetDeviceInformation />
|
||||
</soap:Body>
|
||||
</soap:Envelope>";
|
||||
}
|
||||
|
||||
// ─── Network helpers ────────────────────────────────────────────────
|
||||
|
||||
private static string? GetLocalIpv4()
|
||||
{
|
||||
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (ni.OperationalStatus != OperationalStatus.Up)
|
||||
continue;
|
||||
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (IsCandidateNetwork(addr.Address))
|
||||
return addr.Address.ToString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for a routable private IPv4 that is a plausible camera LAN.
|
||||
/// Excludes loopback and common virtualisation/docker ranges
|
||||
/// (172.16.0.0/12, 100.64.0.0/10) so the scanner targets the real LAN.
|
||||
/// </summary>
|
||||
private static bool IsCandidateNetwork(IPAddress address)
|
||||
{
|
||||
if (address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(address))
|
||||
return false;
|
||||
|
||||
var b = address.GetAddressBytes();
|
||||
if (b[0] == 172 && b[1] is >= 16 and <= 31)
|
||||
return false; // docker / private virtualisation
|
||||
if (b[0] == 100 && b[1] is >= 64 and <= 127)
|
||||
return false; // CGNAT
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP.</summary>
|
||||
private (string? Cidr, string? LocalIp) GetLocalSubnetCidr()
|
||||
{
|
||||
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (ni.OperationalStatus != OperationalStatus.Up)
|
||||
continue;
|
||||
|
||||
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (!IsCandidateNetwork(addr.Address))
|
||||
continue;
|
||||
|
||||
var mask = addr.IPv4Mask;
|
||||
if (mask is null)
|
||||
continue;
|
||||
|
||||
var prefix = CountPrefixBits(mask.GetAddressBytes());
|
||||
var network = NetworkAddress(addr.Address.GetAddressBytes(), mask.GetAddressBytes());
|
||||
var cidr = $"{new IPAddress(network)}/{prefix}";
|
||||
_logger.LogDebug("Local subnet detected: {Cidr} (interface {Interface})", cidr, ni.Name);
|
||||
return (cidr, addr.Address.ToString());
|
||||
}
|
||||
}
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
private static int CountPrefixBits(byte[] mask)
|
||||
{
|
||||
var count = 0;
|
||||
foreach (var b in mask)
|
||||
{
|
||||
for (var i = 7; i >= 0; i--)
|
||||
{
|
||||
if ((b & (1 << i)) == 0)
|
||||
return count;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static byte[] NetworkAddress(byte[] ip, byte[] mask)
|
||||
{
|
||||
var network = new byte[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
network[i] = (byte)(ip[i] & mask[i]);
|
||||
return network;
|
||||
}
|
||||
|
||||
/// <summary>Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536).</summary>
|
||||
internal static List<string> ExpandSubnet(string subnetCidr)
|
||||
{
|
||||
var parts = subnetCidr.Split('/');
|
||||
if (parts.Length != 2)
|
||||
return [];
|
||||
if (!IPAddress.TryParse(parts[0], out var ip))
|
||||
return [];
|
||||
if (!int.TryParse(parts[1], out var prefixLength) || prefixLength is < 0 or > 32)
|
||||
return [];
|
||||
|
||||
var ipBytes = ip.GetAddressBytes();
|
||||
if (BitConverter.IsLittleEndian)
|
||||
Array.Reverse(ipBytes);
|
||||
var uintIp = BitConverter.ToUInt32(ipBytes, 0);
|
||||
|
||||
uint mask;
|
||||
long hostCount;
|
||||
int startOffset;
|
||||
|
||||
if (prefixLength >= 32)
|
||||
{
|
||||
mask = uint.MaxValue;
|
||||
hostCount = 1;
|
||||
startOffset = 0;
|
||||
}
|
||||
else if (prefixLength == 31)
|
||||
{
|
||||
mask = uint.MaxValue << 1;
|
||||
hostCount = 2;
|
||||
startOffset = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
mask = uint.MaxValue << (32 - prefixLength);
|
||||
hostCount = (1L << (32 - prefixLength)) - 2;
|
||||
startOffset = 1;
|
||||
}
|
||||
|
||||
if (hostCount < 0)
|
||||
hostCount = 0;
|
||||
if (hostCount > 65536)
|
||||
hostCount = 65536;
|
||||
|
||||
var network = uintIp & mask;
|
||||
var ips = new List<string>((int)hostCount);
|
||||
for (var i = 0; i < hostCount; i++)
|
||||
{
|
||||
var hostIp = network + (uint)(i + startOffset);
|
||||
var bytes = BitConverter.GetBytes(hostIp);
|
||||
if (BitConverter.IsLittleEndian)
|
||||
Array.Reverse(bytes);
|
||||
ips.Add(new IPAddress(bytes).ToString());
|
||||
}
|
||||
|
||||
return ips;
|
||||
}
|
||||
|
||||
/// <summary>Read the ARP table (/proc/net/arp) to resolve an IP's MAC address.</summary>
|
||||
private static string? GetArpMac(string ip)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lines = File.ReadAllLines("/proc/net/arp");
|
||||
foreach (var line in lines.Skip(1))
|
||||
{
|
||||
var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (fields.Length >= 4 && fields[0] == ip && fields[3] != "00:00:00:00:00:00")
|
||||
return fields[3];
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// ARP table unavailable (non-Linux or restricted container) — best effort.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed record HttpProbe(int Port, int StatusCode, string? ServerHeader);
|
||||
private sealed record OnvifProbe(string DeviceServiceUrl, string? Name, string? Hardware, string? CredentialLabel = null);
|
||||
private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
|
||||
|
||||
public record SubmitAgentDiscoveryCommand(
|
||||
Guid AgentId,
|
||||
IReadOnlyList<AgentDiscoveredDevice> Devices) : IRequest<ServiceResult<AgentDiscoverySubmitResponse>>;
|
||||
|
||||
public class SubmitAgentDiscoveryHandler : IRequestHandler<SubmitAgentDiscoveryCommand, ServiceResult<AgentDiscoverySubmitResponse>>
|
||||
{
|
||||
private readonly ICameraDiscoveryService _discovery;
|
||||
|
||||
public SubmitAgentDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
|
||||
|
||||
public async Task<ServiceResult<AgentDiscoverySubmitResponse>> Handle(
|
||||
SubmitAgentDiscoveryCommand request, CancellationToken cancellationToken)
|
||||
=> await _discovery.SubmitAgentDiscoveriesAsync(request.AgentId, request.Devices, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public interface IApplicationDbContext
|
||||
DbSet<Person> Persons { get; }
|
||||
DbSet<RevokedRefreshToken> RevokedRefreshTokens { get; }
|
||||
DbSet<Site> Sites { get; }
|
||||
DbSet<SiteCredential> SiteCredentials { get; }
|
||||
DbSet<UserGroup> UserGroups { get; }
|
||||
DbSet<UserSite> UserSites { get; }
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// Site credentials (pool of login/password pairs for camera discovery)
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Credential pair declared for a site. Password is write-only: never returned by the API.</summary>
|
||||
public record SiteCredentialResponse(
|
||||
Guid Id,
|
||||
Guid SiteId,
|
||||
string Label,
|
||||
string Username,
|
||||
DateTime CreatedAt,
|
||||
DateTime? LastUsedAt);
|
||||
|
||||
/// <summary>Add a credential pair to a site.</summary>
|
||||
public record AddSiteCredentialRequest(
|
||||
string Label,
|
||||
string Username,
|
||||
string Password);
|
||||
|
||||
/// <summary>
|
||||
/// A credential pair shipped inside the agent config envelope. The password is
|
||||
/// only ever present inside the encrypted envelope — never in plain settings.
|
||||
/// </summary>
|
||||
public record AgentCameraCredential(
|
||||
string Label,
|
||||
string Username,
|
||||
string Password);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// Agent-submitted discovery results
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A single device detected by an agent's network scan. The agent performs
|
||||
/// the probes (ports, HTTP header, ONVIF WS-Discovery with the site's
|
||||
/// credential pool, ARP) and reports devices already identified — ONVIF
|
||||
/// manufacturer/model are filled in by the agent when authentication with a
|
||||
/// pool credential succeeded. The Central only persists the results.
|
||||
/// </summary>
|
||||
public record AgentDiscoveredDevice(
|
||||
string Ip,
|
||||
bool IsReachable,
|
||||
int[] OpenPorts,
|
||||
string? MacAddress,
|
||||
string? Vendor,
|
||||
string? Hostname,
|
||||
string? HttpServerHeader,
|
||||
int? HttpStatusCode,
|
||||
int? HttpPort,
|
||||
string? OnvifDeviceServiceUrl,
|
||||
string? OnvifName,
|
||||
string? OnvifHardware,
|
||||
int? OnvifPort,
|
||||
string? HomeKitName,
|
||||
string? HomeKitDeviceId,
|
||||
string? HomeKitModel,
|
||||
string? CredentialLabel = null);
|
||||
|
||||
/// <summary>Response to an agent's discovery submission.</summary>
|
||||
public record AgentDiscoverySubmitResponse(
|
||||
int Received,
|
||||
int New,
|
||||
int Updated);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// Pending discovery results (UI)
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A persisted discovery result exposed to the UI for confirmation.</summary>
|
||||
public record PendingDiscoveryResponse(
|
||||
Guid Id,
|
||||
Guid SiteId,
|
||||
string IpAddress,
|
||||
string? MacAddress,
|
||||
string? Vendor,
|
||||
string? Hostname,
|
||||
bool IsReachable,
|
||||
string DetectedType,
|
||||
string DiscoveryMethod,
|
||||
int[] OpenPorts,
|
||||
string? OnvifDeviceServiceUrl,
|
||||
string? OnvifName,
|
||||
string? OnvifHardware,
|
||||
int? OnvifPort,
|
||||
string? HttpServerHeader,
|
||||
int? HttpStatusCode,
|
||||
int? HttpPort,
|
||||
DateTime ProbedAt,
|
||||
bool IsProcessed,
|
||||
string[] StreamUrls);
|
||||
|
||||
/// <summary>Request to reject (ignore) a pending discovery result.</summary>
|
||||
public record RejectDiscoveryRequest(Guid ResultId);
|
||||
|
||||
/// <summary>Result of a scan-now request broadcast to site agents.</summary>
|
||||
public record ScanNowResponse(int AgentsNotified);
|
||||
@@ -0,0 +1,17 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Discovery.Commands.RejectDiscovery;
|
||||
|
||||
public record RejectDiscoveryCommand(Guid ResultId) : IRequest<ServiceResult>;
|
||||
|
||||
public class RejectDiscoveryHandler : IRequestHandler<RejectDiscoveryCommand, ServiceResult>
|
||||
{
|
||||
private readonly ICameraDiscoveryService _discovery;
|
||||
|
||||
public RejectDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
|
||||
|
||||
public async Task<ServiceResult> Handle(RejectDiscoveryCommand request, CancellationToken cancellationToken)
|
||||
=> await _discovery.RejectDiscoveryAsync(request.ResultId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Discovery.Commands.RequestSiteScan;
|
||||
|
||||
public record RequestSiteScanCommand(Guid SiteId) : IRequest<ServiceResult<ScanNowResponse>>;
|
||||
|
||||
/// <summary>
|
||||
/// Ask every online agent of a site to run an immediate network scan.
|
||||
/// Delivery is best-effort over SignalR — offline agents pick up the change
|
||||
/// on their periodic scan schedule anyway.
|
||||
/// </summary>
|
||||
public class RequestSiteScanHandler : IRequestHandler<RequestSiteScanCommand, ServiceResult<ScanNowResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly IConfigBroadcastService _broadcast;
|
||||
|
||||
public RequestSiteScanHandler(IApplicationDbContext context, IConfigBroadcastService broadcast)
|
||||
{
|
||||
_context = context;
|
||||
_broadcast = broadcast;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<ScanNowResponse>> Handle(
|
||||
RequestSiteScanCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
|
||||
if (!siteExists)
|
||||
return ServiceResult<ScanNowResponse>.NotFound("Site not found");
|
||||
|
||||
var agents = await _context.Agents
|
||||
.Where(a => a.SiteId == request.SiteId && !a.IsDeleted)
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var notified = 0;
|
||||
foreach (var agent in agents)
|
||||
{
|
||||
// Only connected agents receive the push; offline agents scan on schedule.
|
||||
await _broadcast.NotifyAgentSettingChanged(
|
||||
agent.Id, "discovery.scan.requested", "1", cancellationToken).ConfigureAwait(false);
|
||||
notified++;
|
||||
}
|
||||
|
||||
return ServiceResult<ScanNowResponse>.Success(new ScanNowResponse(notified));
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Discovery.Queries.ListPendingDiscoveries;
|
||||
|
||||
public record ListPendingDiscoveriesQuery(Guid SiteId) : IRequest<ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>>;
|
||||
|
||||
public class ListPendingDiscoveriesHandler : IRequestHandler<ListPendingDiscoveriesQuery, ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>>
|
||||
{
|
||||
private readonly ICameraDiscoveryService _discovery;
|
||||
|
||||
public ListPendingDiscoveriesHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
|
||||
|
||||
public async Task<ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>> Handle(
|
||||
ListPendingDiscoveriesQuery request, CancellationToken cancellationToken)
|
||||
=> await _discovery.ListPendingDiscoveriesAsync(request.SiteId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypted envelope carrying the site's camera credential pool to an agent.
|
||||
///
|
||||
/// The envelope is sealed with AES-256-GCM using a key derived from the
|
||||
/// agent's API key (SHA-256). The Central only ever stores the SHA-256 hash
|
||||
/// of the API key (<see cref="Heimdall.Domain.Entities.Agent.ApiKeyHash"/>),
|
||||
/// so the pair it ships is decryptable only by the agent that holds the
|
||||
/// plaintext API key — a third party intercepting the config payload cannot
|
||||
/// recover the login/password pairs.
|
||||
/// </summary>
|
||||
public static class AgentCredentialEnvelope
|
||||
{
|
||||
private const string Prefix = "v1:";
|
||||
private const int NonceSize = 12;
|
||||
private const int TagSize = 16;
|
||||
|
||||
/// <summary>
|
||||
/// Derive the AES key for an agent from its API key hash (hex SHA-256 of
|
||||
/// the plaintext API key, as stored on the Agent entity).
|
||||
/// </summary>
|
||||
public static byte[] DeriveKeyFromApiKeyHash(string apiKeyHash)
|
||||
=> Convert.FromHexString(apiKeyHash);
|
||||
|
||||
/// <summary>Derive the AES key from the plaintext API key (agent side).</summary>
|
||||
public static byte[] DeriveKeyFromApiKey(string apiKey)
|
||||
=> SHA256.HashData(Encoding.UTF8.GetBytes(apiKey));
|
||||
|
||||
public static string Encrypt(IReadOnlyList<AgentCameraCredential> credentials, byte[] key)
|
||||
{
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(credentials.ToArray());
|
||||
var nonce = RandomNumberGenerator.GetBytes(NonceSize);
|
||||
var ciphertext = new byte[payload.Length];
|
||||
var tag = new byte[TagSize];
|
||||
|
||||
using var aes = new AesGcm(key, TagSize);
|
||||
aes.Encrypt(nonce, payload, ciphertext, tag);
|
||||
|
||||
var combined = new byte[NonceSize + TagSize + ciphertext.Length];
|
||||
nonce.CopyTo(combined, 0);
|
||||
tag.CopyTo(combined, NonceSize);
|
||||
ciphertext.CopyTo(combined, NonceSize + TagSize);
|
||||
|
||||
return Prefix + Convert.ToBase64String(combined);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<AgentCameraCredential> Decrypt(string envelope, byte[] key)
|
||||
{
|
||||
if (!envelope.StartsWith(Prefix, StringComparison.Ordinal))
|
||||
throw new CryptographicException("Invalid credential envelope format");
|
||||
|
||||
var combined = Convert.FromBase64String(envelope[Prefix.Length..]);
|
||||
if (combined.Length < NonceSize + TagSize)
|
||||
throw new CryptographicException("Credential envelope too short");
|
||||
|
||||
var nonce = combined[..NonceSize];
|
||||
var tag = combined[NonceSize..(NonceSize + TagSize)];
|
||||
var ciphertext = combined[(NonceSize + TagSize)..];
|
||||
var payload = new byte[ciphertext.Length];
|
||||
|
||||
using var aes = new AesGcm(key, TagSize);
|
||||
aes.Decrypt(nonce, ciphertext, tag, payload);
|
||||
|
||||
return JsonSerializer.Deserialize<AgentCameraCredential[]>(payload) ?? [];
|
||||
}
|
||||
}
|
||||
@@ -79,4 +79,26 @@ public interface ICameraDiscoveryService
|
||||
/// </summary>
|
||||
Task<ServiceResult<CameraCheckResponse>> CheckDuplicateAsync(
|
||||
CheckDuplicateRequest request, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Receive a batch of devices probed by an agent's network scan. Persists
|
||||
/// them as CameraDiscoveryResult (upsert by site+IP for unprocessed results),
|
||||
/// then enriches each candidate: authenticated ONVIF GetDeviceInformation
|
||||
/// using the site's declared credential pool, and candidate stream URL
|
||||
/// building from the built-in camera database.
|
||||
/// </summary>
|
||||
Task<ServiceResult<AgentDiscoverySubmitResponse>> SubmitAgentDiscoveriesAsync(
|
||||
Guid agentId, IReadOnlyList<AgentDiscoveredDevice> devices, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// List pending (unprocessed) discovery results for a site, newest first.
|
||||
/// </summary>
|
||||
Task<ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>> ListPendingDiscoveriesAsync(
|
||||
Guid siteId, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Mark a discovery result as rejected (ignored) so it no longer appears
|
||||
/// in the pending list. Does not delete the row.
|
||||
/// </summary>
|
||||
Task<ServiceResult> RejectDiscoveryAsync(Guid resultId, CancellationToken ct);
|
||||
}
|
||||
+40
-1
@@ -1,4 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Security;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -10,8 +12,13 @@ public class GetEffectiveAgentConfigQueryHandler
|
||||
: IRequestHandler<GetEffectiveAgentConfigQuery, ServiceResult<Dictionary<string, string>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ICredentialProtector _protector;
|
||||
|
||||
public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db) => _db = db;
|
||||
public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db, ICredentialProtector protector)
|
||||
{
|
||||
_db = db;
|
||||
_protector = protector;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<Dictionary<string, string>>> Handle(
|
||||
GetEffectiveAgentConfigQuery request, CancellationToken ct)
|
||||
@@ -29,6 +36,38 @@ public class GetEffectiveAgentConfigQueryHandler
|
||||
foreach (var s in agentSettings)
|
||||
config[s.Key] = s.Value;
|
||||
|
||||
// ── Camera credential pool (encrypted, decryptable only by the agent) ──
|
||||
// The agent lives on the camera network, so it must own the authenticated
|
||||
// ONVIF enrichment. The Central ships the site's credential pairs inside
|
||||
// an AES-GCM envelope keyed by the agent's API key hash. The agent can
|
||||
// decrypt it with its plaintext API key; nobody else can.
|
||||
var agent = await _db.Agents
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(a => a.Id == request.AgentId, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (agent is not null && !string.IsNullOrEmpty(agent.ApiKeyHash))
|
||||
{
|
||||
var credentials = await _db.SiteCredentials
|
||||
.AsNoTracking()
|
||||
.Where(c => c.SiteId == agent.SiteId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (credentials.Count > 0)
|
||||
{
|
||||
var pairs = credentials
|
||||
.Select(c => new AgentCameraCredential(
|
||||
c.Label,
|
||||
c.Username,
|
||||
_protector.Decrypt(c.Password)))
|
||||
.ToList();
|
||||
|
||||
var key = AgentCredentialEnvelope.DeriveKeyFromApiKeyHash(agent.ApiKeyHash);
|
||||
config["discovery.credentials"] = AgentCredentialEnvelope.Encrypt(pairs, key);
|
||||
}
|
||||
}
|
||||
|
||||
return ServiceResult<Dictionary<string, string>>.Success(config);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.SiteCredentials.Commands.AddSiteCredential;
|
||||
|
||||
public record AddSiteCredentialCommand(
|
||||
Guid SiteId,
|
||||
string Label,
|
||||
string Username,
|
||||
string Password) : IRequest<ServiceResult<SiteCredentialResponse>>;
|
||||
|
||||
public class AddSiteCredentialHandler : IRequestHandler<AddSiteCredentialCommand, ServiceResult<SiteCredentialResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly ICredentialProtector _protector;
|
||||
|
||||
public AddSiteCredentialHandler(IApplicationDbContext context, ICredentialProtector protector)
|
||||
{
|
||||
_context = context;
|
||||
_protector = protector;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<SiteCredentialResponse>> Handle(
|
||||
AddSiteCredentialCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Label))
|
||||
return ServiceResult<SiteCredentialResponse>.Failure("Label is required");
|
||||
if (string.IsNullOrWhiteSpace(request.Username))
|
||||
return ServiceResult<SiteCredentialResponse>.Failure("Username is required");
|
||||
if (string.IsNullOrWhiteSpace(request.Password))
|
||||
return ServiceResult<SiteCredentialResponse>.Failure("Password is required");
|
||||
|
||||
var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
|
||||
if (!siteExists)
|
||||
return ServiceResult<SiteCredentialResponse>.NotFound("Site not found");
|
||||
|
||||
var duplicate = await _context.SiteCredentials
|
||||
.AnyAsync(c => c.SiteId == request.SiteId
|
||||
&& (c.Label == request.Label || c.Username == request.Username),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (duplicate)
|
||||
return ServiceResult<SiteCredentialResponse>.Conflict("A credential with this label or username already exists for this site");
|
||||
|
||||
var credential = new SiteCredential(
|
||||
request.SiteId,
|
||||
request.Label.Trim(),
|
||||
request.Username.Trim(),
|
||||
_protector.Encrypt(request.Password));
|
||||
|
||||
_context.SiteCredentials.Add(credential);
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<SiteCredentialResponse>.Success(new SiteCredentialResponse(
|
||||
credential.Id, credential.SiteId, credential.Label, credential.Username,
|
||||
credential.CreatedAt, credential.LastUsedAt));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.SiteCredentials.Commands.DeleteSiteCredential;
|
||||
|
||||
public record DeleteSiteCredentialCommand(Guid SiteId, Guid CredentialId) : IRequest<ServiceResult>;
|
||||
|
||||
public class DeleteSiteCredentialHandler : IRequestHandler<DeleteSiteCredentialCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public DeleteSiteCredentialHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult> Handle(
|
||||
DeleteSiteCredentialCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var credential = await _context.SiteCredentials
|
||||
.FirstOrDefaultAsync(c => c.Id == request.CredentialId && c.SiteId == request.SiteId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (credential is null)
|
||||
return ServiceResult.NotFound("Credential not found for this site");
|
||||
|
||||
_context.SiteCredentials.Remove(credential);
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.SiteCredentials.Queries.ListSiteCredentials;
|
||||
|
||||
public record ListSiteCredentialsQuery(Guid SiteId) : IRequest<ServiceResult<IReadOnlyList<SiteCredentialResponse>>>;
|
||||
|
||||
public class ListSiteCredentialsHandler : IRequestHandler<ListSiteCredentialsQuery, ServiceResult<IReadOnlyList<SiteCredentialResponse>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public ListSiteCredentialsHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<IReadOnlyList<SiteCredentialResponse>>> Handle(
|
||||
ListSiteCredentialsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
|
||||
if (!siteExists)
|
||||
return ServiceResult<IReadOnlyList<SiteCredentialResponse>>.NotFound("Site not found");
|
||||
|
||||
var credentials = await _context.SiteCredentials
|
||||
.Where(c => c.SiteId == request.SiteId)
|
||||
.OrderBy(c => c.CreatedAt)
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var response = credentials
|
||||
.Select(c => new SiteCredentialResponse(
|
||||
c.Id, c.SiteId, c.Label, c.Username, c.CreatedAt, c.LastUsedAt))
|
||||
.ToList();
|
||||
|
||||
return ServiceResult<IReadOnlyList<SiteCredentialResponse>>.Success(response);
|
||||
}
|
||||
}
|
||||
@@ -116,5 +116,11 @@ public class CameraDiscoveryResult : Entity<Guid>
|
||||
Vendor = vendor;
|
||||
}
|
||||
|
||||
public void SetHostname(string? hostname)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(hostname))
|
||||
Hostname = hostname;
|
||||
}
|
||||
|
||||
public void MarkProcessed() => IsProcessed = true;
|
||||
}
|
||||
@@ -30,6 +30,10 @@ public class Site : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
private readonly List<Camera> _cameras = [];
|
||||
public IReadOnlyCollection<Camera> Cameras => _cameras.AsReadOnly();
|
||||
|
||||
/// <summary>Credential pairs declared for this site (used by camera discovery).</summary>
|
||||
private readonly List<SiteCredential> _credentials = [];
|
||||
public IReadOnlyCollection<SiteCredential> Credentials => _credentials.AsReadOnly();
|
||||
|
||||
private Site() { } // EF Core
|
||||
|
||||
public Site(string name, string? address = null, string? timezone = null)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// A credential pair (username/password) declared for a site, used by agents
|
||||
/// to authenticate against cameras discovered on the site's network.
|
||||
/// The password is encrypted at rest via
|
||||
/// <see cref="Heimdall.Infrastructure.Security.ICredentialProtector"/> (applied in the
|
||||
/// application/service layer before storage) — never stored in plain text.
|
||||
/// </summary>
|
||||
public class SiteCredential : Entity<Guid>
|
||||
{
|
||||
public Guid SiteId { get; private set; }
|
||||
public Site Site { get; private set; } = null!;
|
||||
|
||||
/// <summary>Human-readable label, e.g. "admin principal" or "comptes NVR".</summary>
|
||||
public string Label { get; private set; } = string.Empty;
|
||||
|
||||
public string Username { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Encrypted via ICredentialProtector at the service layer.</summary>
|
||||
public string Password { get; private set; } = string.Empty;
|
||||
|
||||
public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
/// <summary>Last time a discovery successfully used this credential pair.</summary>
|
||||
public DateTime? LastUsedAt { get; private set; }
|
||||
|
||||
private SiteCredential() { } // EF Core
|
||||
|
||||
public SiteCredential(Guid siteId, string label, string username, string password)
|
||||
: base(Guid.NewGuid())
|
||||
{
|
||||
SiteId = siteId;
|
||||
Label = label;
|
||||
Username = username;
|
||||
Password = password;
|
||||
}
|
||||
|
||||
public void Update(string label, string username, string password)
|
||||
{
|
||||
Label = label;
|
||||
Username = username;
|
||||
Password = password;
|
||||
}
|
||||
|
||||
public void MarkUsed() => LastUsedAt = DateTime.UtcNow;
|
||||
}
|
||||
@@ -21,6 +21,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
|
||||
// Domain entities
|
||||
public DbSet<Site> Sites => Set<Site>();
|
||||
public DbSet<SiteCredential> SiteCredentials => Set<SiteCredential>();
|
||||
public DbSet<Agent> Agents => Set<Agent>();
|
||||
public DbSet<Camera> Cameras => Set<Camera>();
|
||||
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class SiteCredentialConfiguration : IEntityTypeConfiguration<SiteCredential>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<SiteCredential> builder)
|
||||
{
|
||||
builder.ToTable("site_credentials");
|
||||
|
||||
builder.HasKey(c => c.Id);
|
||||
|
||||
builder.Property(c => c.Label)
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(c => c.Username)
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false);
|
||||
|
||||
// Password is encrypted (ICredentialProtector) — column must be large enough
|
||||
// for the ciphertext (base64 of AesGcm output + tag + nonce).
|
||||
builder.Property(c => c.Password)
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(c => c.CreatedAt)
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
builder.Property(c => c.LastUsedAt);
|
||||
|
||||
// ── Indexes ─────────────────────────────────────────────────
|
||||
builder.HasIndex(c => c.SiteId);
|
||||
|
||||
// ── Relationships ───────────────────────────────────────────
|
||||
builder.HasOne(c => c.Site)
|
||||
.WithMany(s => s.Credentials)
|
||||
.HasForeignKey(c => c.SiteId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
+1831
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSiteCredentials : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "site_credentials",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
SiteId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Label = table.Column<string>(type: "character varying(100)", unicode: false, maxLength: 100, nullable: false),
|
||||
Username = table.Column<string>(type: "character varying(200)", unicode: false, maxLength: 200, nullable: false),
|
||||
Password = table.Column<string>(type: "character varying(2000)", unicode: false, maxLength: 2000, nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
LastUsedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_site_credentials", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_site_credentials_sites_SiteId",
|
||||
column: x => x.SiteId,
|
||||
principalTable: "sites",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_site_credentials_SiteId",
|
||||
table: "site_credentials",
|
||||
column: "SiteId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "site_credentials");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1302,6 +1302,48 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("sites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("Label")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("SiteId");
|
||||
|
||||
b.ToTable("site_credentials", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
@@ -1638,6 +1680,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Person");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
|
||||
.WithMany("Credentials")
|
||||
.HasForeignKey("SiteId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Site");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Group", "Group")
|
||||
@@ -1766,6 +1819,8 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Agents");
|
||||
|
||||
b.Navigation("Cameras");
|
||||
|
||||
b.Navigation("Credentials");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
|
||||
// Popular brands
|
||||
new("brand", "b:hikvision", "Hikvision"),
|
||||
new("brand", "b:dahua", "Dahua"),
|
||||
new("brand", "b:imou", "Imou"),
|
||||
new("brand", "b:axis", "Axis Communications"),
|
||||
new("brand", "b:vivotek", "Vivotek"),
|
||||
new("brand", "b:amcrest", "Amcrest"),
|
||||
@@ -56,6 +57,12 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
|
||||
// Common models
|
||||
new("model", "m:hikvision:ds-2cd2t47", "Hikvision DS-2CD2T47G2-L"),
|
||||
new("model", "m:dahua:sd22204", "Dahua SD22204"),
|
||||
new("model", "m:imou:ipc-t2a30p", "Imou IPC-T2A30P"),
|
||||
new("model", "m:imou:ipc-a22ep", "Imou IPC-A22EP"),
|
||||
new("model", "m:imou:ipc-s41fp", "Imou IPC-S41FP"),
|
||||
new("model", "m:imou:ipc-e22cp", "Imou IPC-E22CP"),
|
||||
new("model", "m:imou:ranger", "Imou Ranger"),
|
||||
new("model", "m:imou:cue2", "Imou Cue2"),
|
||||
new("model", "m:axis:m3085", "Axis M3085-V"),
|
||||
new("model", "m:amcrest:ip8m", "Amcrest IP8M-T2499EW"),
|
||||
new("model", "m:tp-link:tc70", "TP-Link Tapo TC70"),
|
||||
@@ -75,6 +82,10 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
|
||||
"http://{IP}:80/onvif/device_service"],
|
||||
["b:dahua"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0",
|
||||
"rtsp://{USERNAME}:{PASSWORD}@{IP}:8554/Streaming/Channels/{CHANNEL}01"],
|
||||
// Imou (Dahua consumer brand): Dahua-style RTSP + HTTP snapshot/MJPEG CGI
|
||||
["b:imou"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0",
|
||||
"http://{IP}:80/video.mjpg?oids=1&username={USERNAME}&password={PASSWORD}",
|
||||
"http://{IP}:80/cgi-bin/snapshot.cgi?loginuse={USERNAME}&loginpas={PASSWORD}"],
|
||||
["b:axis"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/axis-media/media.amp",
|
||||
"http://{IP}:80/axis-cgi/mjpg/video.cgi"],
|
||||
["b:vivotek"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/live.sdp"],
|
||||
@@ -469,6 +480,308 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Agent-submitted discovery (agent → central) ────────────────────
|
||||
|
||||
public async Task<ServiceResult<AgentDiscoverySubmitResponse>> SubmitAgentDiscoveriesAsync(
|
||||
Guid agentId, IReadOnlyList<AgentDiscoveredDevice> devices, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var agent = await db.Agents.FirstOrDefaultAsync(a => a.Id == agentId, ct).ConfigureAwait(false);
|
||||
if (agent is null)
|
||||
return ServiceResult<AgentDiscoverySubmitResponse>.NotFound("Agent not found");
|
||||
|
||||
var siteId = agent.SiteId;
|
||||
|
||||
// Site credential pool, decrypted (tracked so LastUsedAt persists).
|
||||
var credentials = await db.SiteCredentials
|
||||
.Where(c => c.SiteId == siteId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
var pool = credentials
|
||||
.Select(c => (Credential: c, Password: _credentialProtector.Decrypt(c.Password)))
|
||||
.ToList();
|
||||
|
||||
var newCount = 0;
|
||||
var updatedCount = 0;
|
||||
|
||||
foreach (var device in devices)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(device.Ip) || !IPAddress.TryParse(device.Ip, out _))
|
||||
continue;
|
||||
|
||||
// Upsert: reuse an existing unprocessed result for site+IP.
|
||||
var result = await db.CameraDiscoveryResults
|
||||
.Include(r => r.DiscoveredStreams)
|
||||
.FirstOrDefaultAsync(r => r.SiteId == siteId && r.IpAddress == device.Ip && !r.IsProcessed, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (result is null)
|
||||
{
|
||||
result = new CameraDiscoveryResult(siteId, device.Ip);
|
||||
db.CameraDiscoveryResults.Add(result);
|
||||
newCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
updatedCount++;
|
||||
}
|
||||
|
||||
ApplyAgentProbeData(result, device);
|
||||
|
||||
// The agent performs the authenticated ONVIF enrichment itself
|
||||
// (it is on the camera network and holds the site's credential
|
||||
// pool via the encrypted agent config). When it reports the label
|
||||
// of the credential that succeeded, mark it as used.
|
||||
if (!string.IsNullOrEmpty(device.CredentialLabel))
|
||||
{
|
||||
var used = pool.FirstOrDefault(p =>
|
||||
string.Equals(p.Credential.Label, device.CredentialLabel, StringComparison.Ordinal));
|
||||
if (used.Credential is not null)
|
||||
{
|
||||
used.Credential.MarkUsed();
|
||||
_logger.LogInformation(
|
||||
"Agent discovery {Ip} authenticated with credential '{Label}' (reported by agent)",
|
||||
device.Ip, device.CredentialLabel);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Build candidate stream URLs ─────────────────────────────
|
||||
await BuildCandidateStreamUrlsAsync(db, result, device, pool, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Agent {AgentId} submitted {Total} devices: {New} new, {Updated} updated (site {SiteId})",
|
||||
agentId, devices.Count, newCount, updatedCount, siteId);
|
||||
|
||||
return ServiceResult<AgentDiscoverySubmitResponse>.Success(
|
||||
new AgentDiscoverySubmitResponse(devices.Count, newCount, updatedCount));
|
||||
}
|
||||
|
||||
private static void ApplyAgentProbeData(CameraDiscoveryResult result, AgentDiscoveredDevice device)
|
||||
{
|
||||
var mac = device.MacAddress ?? result.MacAddress;
|
||||
|
||||
// The agent reports the ONVIF manufacturer (device.OnvifName) when it
|
||||
// authenticated successfully — prefer it over the MAC OUI (more
|
||||
// reliable, e.g. Imou reports Dahua/Imou while sharing OUIs).
|
||||
var vendor = device.Vendor;
|
||||
if (vendor is null && !string.IsNullOrEmpty(device.OnvifName))
|
||||
vendor = NormalizeVendor(device.OnvifName);
|
||||
vendor ??= result.Vendor ?? (mac is not null ? ResolveOuiVendor(mac) : null);
|
||||
|
||||
if (!string.IsNullOrEmpty(mac) || !string.IsNullOrEmpty(vendor))
|
||||
result.SetArpInfo(mac ?? string.Empty, vendor);
|
||||
result.SetHostname(device.Hostname);
|
||||
|
||||
if (device.OpenPorts.Length > 0)
|
||||
result.SetOpenPorts(device.OpenPorts);
|
||||
|
||||
if (!string.IsNullOrEmpty(device.HttpServerHeader) || device.HttpStatusCode is not null)
|
||||
result.SetHttpResult(device.HttpPort ?? 80, device.HttpStatusCode ?? 0, device.HttpServerHeader);
|
||||
|
||||
if (!string.IsNullOrEmpty(device.HomeKitName) && !string.IsNullOrEmpty(device.HomeKitDeviceId))
|
||||
result.SetHomeKitResult(device.HomeKitName, device.HomeKitDeviceId, device.HomeKitModel ?? string.Empty);
|
||||
|
||||
if (!string.IsNullOrEmpty(device.OnvifDeviceServiceUrl) || device.OnvifPort is not null)
|
||||
result.SetOnvifResult(
|
||||
device.OnvifDeviceServiceUrl ?? result.OnvifDeviceServiceUrl ?? string.Empty,
|
||||
device.OnvifName ?? result.OnvifName,
|
||||
device.OnvifHardware ?? result.OnvifHardware,
|
||||
device.OnvifPort ?? 80);
|
||||
|
||||
// Classification (mirrors ClassifyCamera for agent-submitted data).
|
||||
var (type, method) = ClassifyAgentDevice(device);
|
||||
result.MarkReachable(type, method);
|
||||
}
|
||||
|
||||
private static (DetectedCameraType type, CameraDiscoveryMethod method) ClassifyAgentDevice(AgentDiscoveredDevice device)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(device.OnvifHardware) || !string.IsNullOrEmpty(device.OnvifDeviceServiceUrl))
|
||||
return (DetectedCameraType.Standard, CameraDiscoveryMethod.OnvifWsDiscovery);
|
||||
|
||||
if (!string.IsNullOrEmpty(device.HomeKitName))
|
||||
return (DetectedCameraType.HomeKit, CameraDiscoveryMethod.MdnsHomeKit);
|
||||
|
||||
var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty;
|
||||
if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("axis"))
|
||||
return (DetectedCameraType.Standard, CameraDiscoveryMethod.HttpProbe);
|
||||
|
||||
if (device.OpenPorts.Contains(8899) || device.OpenPorts.Contains(37777))
|
||||
return (DetectedCameraType.Nvr, CameraDiscoveryMethod.NetworkScan);
|
||||
|
||||
if (device.OpenPorts.Contains(554) || device.OpenPorts.Contains(8554))
|
||||
return (DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan);
|
||||
|
||||
return (DetectedCameraType.Unknown, CameraDiscoveryMethod.NetworkScan);
|
||||
}
|
||||
|
||||
private async Task BuildCandidateStreamUrlsAsync(
|
||||
AppDbContext db,
|
||||
CameraDiscoveryResult result,
|
||||
AgentDiscoveredDevice device,
|
||||
List<(SiteCredential Credential, string Password)> pool,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var existing = result.DiscoveredStreams.Select(s => s.Url).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// Pick the credential pair used for ONVIF auth (or the first pool entry as a guess).
|
||||
string? username = null;
|
||||
string? password = null;
|
||||
if (pool.Count > 0)
|
||||
{
|
||||
username = pool[0].Credential.Username;
|
||||
password = pool[0].Password;
|
||||
}
|
||||
|
||||
var ids = new List<string> { "p:onvif", "p:rtsp-h264", "p:rtsp-h265", "p:mjpeg" };
|
||||
// Prefer the enriched vendor (ONVIF manufacturer) over the raw device vendor.
|
||||
var vendorKey = (result.Vendor ?? device.Vendor)?.ToLowerInvariant();
|
||||
if (vendorKey is not null && StreamTemplates.ContainsKey($"b:{vendorKey}"))
|
||||
ids.Insert(0, $"b:{vendorKey}");
|
||||
|
||||
var buildRequest = new StreamBuildRequest(
|
||||
[.. ids], device.Ip, username, password, Channel: 0,
|
||||
PortFilter: device.OpenPorts.Contains(554) ? [554] : device.OpenPorts);
|
||||
var buildResult = await BuildStreamUrlsAsync(buildRequest, ct).ConfigureAwait(false);
|
||||
if (!buildResult.IsSuccess || buildResult.Data is null)
|
||||
return;
|
||||
|
||||
foreach (var url in buildResult.Data.Streams)
|
||||
{
|
||||
if (existing.Contains(url))
|
||||
continue;
|
||||
|
||||
// Add through the DbSet directly — adding via the loaded navigation
|
||||
// collection triggers an EF Core UPDATE-on-new-child bug with SQLite.
|
||||
db.DiscoveredStreams.Add(new DiscoveredStreamUrl(
|
||||
result.Id, url, ProtocolFromUrl(url), [], 0, 0, 0,
|
||||
isMainStream: false, isAlive: false));
|
||||
existing.Add(url);
|
||||
}
|
||||
}
|
||||
|
||||
private static StreamProtocol ProtocolFromUrl(string url)
|
||||
{
|
||||
if (url.StartsWith("rtsp://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtsp;
|
||||
if (url.StartsWith("rtsps://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtsps;
|
||||
if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Https;
|
||||
if (url.StartsWith("rtmp://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtmp;
|
||||
if (url.StartsWith("rtmps://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtmps;
|
||||
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Http;
|
||||
return StreamProtocol.Rtsp;
|
||||
}
|
||||
|
||||
// ─── Pending discovery listing / rejection ──────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Minimal OUI → vendor resolution for common camera manufacturers.
|
||||
/// The Central cannot read the camera network's ARP table, so the vendor
|
||||
/// is resolved from the MAC prefix reported by the agent. Note: OUIs are
|
||||
/// ambiguous across brands (Imou shares Dahua/Hikvision OUIs) — prefer
|
||||
/// <see cref="NormalizeVendor"/> from the ONVIF manufacturer when available.
|
||||
/// </summary>
|
||||
private static readonly (string Prefix, string Vendor)[] OuiTable =
|
||||
[
|
||||
("00:0F:FF", "Hikvision"), ("44:19:B6", "Hikvision"), ("3C:EF:8C", "Hikvision"),
|
||||
("54:C4:15", "Hikvision"), ("90:02:A9", "Hikvision"), ("9C:8E:99", "Hikvision"),
|
||||
("E0:50:8B", "Hikvision"), ("50:6A:03", "Hikvision"),
|
||||
("9C:8E:99", "Dahua"), ("3C:EF:8C", "Dahua"), ("C4:2F:90", "Dahua"),
|
||||
("E0:50:8B", "Dahua"), ("58:23:8C", "Dahua"), ("A0:BD:1D", "Dahua"),
|
||||
("00:1C:27", "Axis Communications"), ("00:40:8C", "Axis Communications"),
|
||||
("AC:CC:8E", "Axis Communications"), ("B8:A4:4F", "Axis Communications"),
|
||||
("3C:EF:8C", "Amcrest"), ("9C:8E:99", "Amcrest"),
|
||||
("58:23:8C", "Uniview"), ("3C:EF:8C", "Uniview"),
|
||||
("50:C7:BF", "TP-Link"), ("60:32:B1", "TP-Link"), ("F4:F2:6D", "TP-Link"),
|
||||
];
|
||||
|
||||
private static string? ResolveOuiVendor(string mac)
|
||||
{
|
||||
var normalized = mac.Replace(":", string.Empty, StringComparison.OrdinalIgnoreCase)
|
||||
.Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
if (normalized.Length < 6)
|
||||
return null;
|
||||
|
||||
var prefix = normalized[..6].ToUpperInvariant();
|
||||
foreach (var (oui, vendor) in OuiTable)
|
||||
{
|
||||
if (oui.Replace(":", string.Empty).Equals(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
return vendor;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Map an ONVIF manufacturer name to a camera-database vendor key
|
||||
/// (b:xxx used in <see cref="StreamTemplates"/>). Returns null when the
|
||||
/// manufacturer is unknown — the generic templates still apply.
|
||||
/// </summary>
|
||||
private static string? NormalizeVendor(string? manufacturer)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(manufacturer))
|
||||
return null;
|
||||
|
||||
var m = manufacturer.ToLowerInvariant();
|
||||
if (m.Contains("hikvision")) return "hikvision";
|
||||
if (m.Contains("imou") || m.Contains("lechange")) return "imou";
|
||||
if (m.Contains("dahua")) return "dahua";
|
||||
if (m.Contains("axis")) return "axis";
|
||||
if (m.Contains("vivotek")) return "vivotek";
|
||||
if (m.Contains("amcrest")) return "amcrest";
|
||||
if (m.Contains("panasonic")) return "panasonic";
|
||||
if (m.Contains("bosch")) return "bosch";
|
||||
if (m.Contains("samsung")) return "samsung";
|
||||
if (m.Contains("sony")) return "sony";
|
||||
if (m.Contains("uniview")) return "uniview";
|
||||
if (m.Contains("tp-link") || m.Contains("tapo")) return "tp-link";
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>> ListPendingDiscoveriesAsync(
|
||||
Guid siteId, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var results = await db.CameraDiscoveryResults
|
||||
.Include(r => r.DiscoveredStreams)
|
||||
.Where(r => r.SiteId == siteId && !r.IsProcessed)
|
||||
.OrderByDescending(r => r.ProbedAt)
|
||||
.Take(200)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var response = results.Select(r => new PendingDiscoveryResponse(
|
||||
r.Id, r.SiteId, r.IpAddress, r.MacAddress, r.Vendor, r.Hostname, r.IsReachable,
|
||||
r.DetectedType.ToString(), r.DiscoveryMethod.ToString(), r.OpenPorts,
|
||||
r.OnvifDeviceServiceUrl, r.OnvifName, r.OnvifHardware, r.OnvifPort,
|
||||
r.HttpServerHeader, r.HttpStatusCode, r.HttpPort,
|
||||
r.ProbedAt, r.IsProcessed,
|
||||
r.DiscoveredStreams.Select(s => s.Url).ToArray()))
|
||||
.ToList();
|
||||
|
||||
return ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>.Success(response);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> RejectDiscoveryAsync(Guid resultId, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var result = await db.CameraDiscoveryResults
|
||||
.FirstOrDefaultAsync(r => r.Id == resultId && !r.IsProcessed, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (result is null)
|
||||
return ServiceResult.NotFound("Discovery result not found or already processed");
|
||||
|
||||
result.MarkProcessed();
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("Discovery result {ResultId} ({Ip}) rejected", resultId, result.IpAddress);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
// ─── Private Helpers ──────────────────────────────────────────────
|
||||
|
||||
private static (DetectedCameraType type, CameraDiscoveryMethod method) ClassifyCamera(
|
||||
|
||||
@@ -19,4 +19,22 @@ public interface IOnvifProbeService
|
||||
/// Returns null if no ONVIF device is detected.
|
||||
/// </summary>
|
||||
Task<OnvifDeviceInfo?> ProbeAsync(string ipAddress, int port = 3702, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Probe an IP address for ONVIF services, authenticating the
|
||||
/// GetDeviceInformation call with the given credentials (WS-UsernameToken,
|
||||
/// PasswordDigest with PasswordText fallback). Pass null credentials to
|
||||
/// fall back to the unauthenticated probe.
|
||||
/// </summary>
|
||||
Task<OnvifDeviceInfo?> ProbeWithCredentialsAsync(
|
||||
string ipAddress, string? username, string? password, int port = 3702, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Query a known ONVIF device service URL (e.g. http://ip/onvif/device_service)
|
||||
/// directly — no WS-Discovery round-trip — with optional credentials.
|
||||
/// Use this when the agent already found the XAddr but the device
|
||||
/// information call needs authentication.
|
||||
/// </summary>
|
||||
Task<OnvifDeviceInfo?> ProbeDeviceServiceAsync(
|
||||
string deviceServiceUrl, string? username, string? password, CancellationToken ct = default);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -22,6 +24,8 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
private static readonly XNamespace TdnNs = "http://www.onvif.org/ver10/network/wsdl";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace TdsNs = "http://www.onvif.org/ver10/device/wsdl";
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
|
||||
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<OnvifProbeService> _logger;
|
||||
@@ -36,10 +40,20 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
}
|
||||
|
||||
public async Task<OnvifDeviceInfo?> ProbeAsync(string ipAddress, int port = 3702, CancellationToken ct = default)
|
||||
=> await ProbeWithCredentialsAsync(ipAddress, null, null, port, ct).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// ONVIF WS-Discovery probe with optional HTTP Basic-style WS-Security
|
||||
/// credentials for the GetDeviceInformation call. Many cameras refuse the
|
||||
/// device information request without a valid UsernameToken, so passing the
|
||||
/// site's declared credential pairs lets discovery identify protected cameras.
|
||||
/// </summary>
|
||||
public async Task<OnvifDeviceInfo?> ProbeWithCredentialsAsync(
|
||||
string ipAddress, string? username, string? password, int port = 3702, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("ONVIF probing {Ip}:{Port}", ipAddress, port);
|
||||
_logger.LogDebug("ONVIF probing {Ip}:{Port} (auth={HasAuth})", ipAddress, port, username is not null);
|
||||
|
||||
// Step 1: Send WS-Discovery Probe via UDP unicast
|
||||
using var udpClient = new UdpClient();
|
||||
@@ -63,18 +77,7 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
|
||||
// Step 4: Try to get device information from first XAddr
|
||||
var deviceUrl = xaddrs[0];
|
||||
var deviceInfo = await GetDeviceInformationAsync(deviceUrl, ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug(
|
||||
"ONVIF device found at {Ip}:{Port} — {Name} ({Hardware})",
|
||||
ipAddress, port, deviceInfo?.Manufacturer ?? "unknown", deviceInfo?.Model ?? "unknown");
|
||||
|
||||
return new OnvifDeviceInfo(
|
||||
DeviceServiceUrl: deviceUrl,
|
||||
Port: port,
|
||||
Name: deviceInfo?.Manufacturer,
|
||||
Hardware: deviceInfo?.Model,
|
||||
Location: null);
|
||||
return await ProbeDeviceServiceAsync(deviceUrl, username, password, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
||||
{
|
||||
@@ -92,6 +95,28 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<OnvifDeviceInfo?> ProbeDeviceServiceAsync(
|
||||
string deviceServiceUrl, string? username, string? password, CancellationToken ct = default)
|
||||
{
|
||||
var deviceInfo = await GetDeviceInformationAsync(deviceServiceUrl, username, password, ct).ConfigureAwait(false);
|
||||
if (deviceInfo is null)
|
||||
{
|
||||
_logger.LogDebug("ONVIF device service {Url} returned no device information", deviceServiceUrl);
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"ONVIF device service {Url} — {Name} ({Hardware})",
|
||||
deviceServiceUrl, deviceInfo.Manufacturer ?? "unknown", deviceInfo.Model ?? "unknown");
|
||||
|
||||
return new OnvifDeviceInfo(
|
||||
DeviceServiceUrl: deviceServiceUrl,
|
||||
Port: 80,
|
||||
Name: deviceInfo.Manufacturer,
|
||||
Hardware: deviceInfo.Model,
|
||||
Location: null);
|
||||
}
|
||||
|
||||
private static byte[] BuildProbeMessage()
|
||||
{
|
||||
var messageId = Guid.NewGuid().ToString();
|
||||
@@ -140,38 +165,49 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
return (xaddrs, scopes, types);
|
||||
}
|
||||
|
||||
private async Task<OnvifDeviceDetail?> GetDeviceInformationAsync(string deviceServiceUrl, CancellationToken ct)
|
||||
private async Task<OnvifDeviceDetail?> GetDeviceInformationAsync(
|
||||
string deviceServiceUrl, string? username, string? password, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient("Discovery");
|
||||
client.Timeout = HttpTimeout;
|
||||
|
||||
var soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
|
||||
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
|
||||
xmlns:tds=""{TdsNs.NamespaceName}"">
|
||||
<soap:Body>
|
||||
<tds:GetDeviceInformation />
|
||||
</soap:Body>
|
||||
</soap:Envelope>";
|
||||
// Try PasswordDigest first (ONVIF standard), fall back to PasswordText
|
||||
// for cameras with laxer WS-Security implementations.
|
||||
var attempts = username is null
|
||||
? new[] { BuildSoapEnvelope(username, password, passwordType: null) }
|
||||
: new[]
|
||||
{
|
||||
BuildSoapEnvelope(username, password, passwordType: "PasswordDigest"),
|
||||
BuildSoapEnvelope(username, password, passwordType: "PasswordText"),
|
||||
};
|
||||
|
||||
using var content = new StringContent(soapBody, Encoding.UTF8, "application/soap+xml");
|
||||
using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
foreach (var soapBody in attempts)
|
||||
{
|
||||
using var content = new StringContent(soapBody, Encoding.UTF8, "application/soap+xml");
|
||||
using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
continue;
|
||||
|
||||
var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var doc = XDocument.Parse(responseXml);
|
||||
var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var doc = XDocument.Parse(responseXml);
|
||||
|
||||
var body = doc.Root?.Element(SoapNs + "Body");
|
||||
var info = body?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
|
||||
var body = doc.Root?.Element(SoapNs + "Body");
|
||||
var info = body?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
|
||||
|
||||
return info is null ? null : new OnvifDeviceDetail(
|
||||
info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("FirmwareVersion", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("SerialNumber", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("HardwareId", TdsNs.NamespaceName))?.Value);
|
||||
if (info is not null)
|
||||
{
|
||||
return new OnvifDeviceDetail(
|
||||
info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("FirmwareVersion", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("SerialNumber", TdsNs.NamespaceName))?.Value,
|
||||
info.Element(XName.Get("HardwareId", TdsNs.NamespaceName))?.Value);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
@@ -180,6 +216,57 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildSoapEnvelope(string? username, string? password, string? passwordType)
|
||||
{
|
||||
var securityHeader = string.Empty;
|
||||
if (username is not null && passwordType is not null)
|
||||
{
|
||||
if (passwordType == "PasswordDigest")
|
||||
{
|
||||
var nonce = new byte[16];
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
var created = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
|
||||
// ONVIF WS-Security PasswordDigest is defined by the standard to use SHA1
|
||||
// (digest = Base64(SHA1(nonce + created + password))). Required for
|
||||
// interoperability with ONVIF cameras — not used for application security.
|
||||
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
|
||||
var digest = SHA1.HashData([.. nonce, .. Encoding.UTF8.GetBytes(created + password)]);
|
||||
#pragma warning restore CA5350
|
||||
securityHeader = $@"
|
||||
<soap:Header>
|
||||
<Security xmlns=""{WsseNs.NamespaceName}"">
|
||||
<UsernameToken>
|
||||
<Username>{username}</Username>
|
||||
<Password Type=""{WsseNs.NamespaceName}#PasswordDigest"">{Convert.ToBase64String(digest)}</Password>
|
||||
<Nonce>{Convert.ToBase64String(nonce)}</Nonce>
|
||||
<Created>{created}</Created>
|
||||
</UsernameToken>
|
||||
</Security>
|
||||
</soap:Header>";
|
||||
}
|
||||
else
|
||||
{
|
||||
securityHeader = $@"
|
||||
<soap:Header>
|
||||
<Security xmlns=""{WsseNs.NamespaceName}"">
|
||||
<UsernameToken>
|
||||
<Username>{username}</Username>
|
||||
<Password Type=""{WsseNs.NamespaceName}#PasswordText"">{password}</Password>
|
||||
</UsernameToken>
|
||||
</Security>
|
||||
</soap:Header>";
|
||||
}
|
||||
}
|
||||
|
||||
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
|
||||
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
|
||||
xmlns:tds=""{TdsNs.NamespaceName}"">{securityHeader}
|
||||
<soap:Body>
|
||||
<tds:GetDeviceInformation />
|
||||
</soap:Body>
|
||||
</soap:Envelope>";
|
||||
}
|
||||
|
||||
private sealed record OnvifDeviceDetail(
|
||||
string? Manufacturer,
|
||||
string? Model,
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
@page "/sites/{SiteId:guid}/discoveries"
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Nav
|
||||
|
||||
<MudText Typo="Typo.h1" Class="mb-1">
|
||||
<i class="fas fa-radar mr-2"></i>
|
||||
Caméras détectées
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
|
||||
Résultats des scans réseau effectués par les agents du site. Les caméras compatibles
|
||||
sont détectées automatiquement ; confirmez celles à ajouter.
|
||||
</MudText>
|
||||
|
||||
<div class="d-flex justify-space-between align-center mb-4">
|
||||
<div>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@ScanNow" Disabled="@_scanning">
|
||||
@if (_scanning) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
<MudIcon Icon="@Icons.Material.Filled.Radar" Class="mr-1" /> Scanner maintenant
|
||||
</MudButton>
|
||||
<MudTooltip Text="Rafraîchir la liste">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Refresh" OnClick="@LoadDiscoveries" Class="ml-2" />
|
||||
</MudTooltip>
|
||||
</div>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Default" OnClick="@(() => Nav.NavigateTo($"/sites/{SiteId}"))">
|
||||
← Retour au site
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
@if (_scanning)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
Scan demandé aux agents du site. Les résultats arrivent dans quelques instants…
|
||||
</MudAlert>
|
||||
}
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_discoveries.Count == 0)
|
||||
{
|
||||
<MudPaper Elevation="2" Class="pa-6 text-center" Style="border-radius: 12px;">
|
||||
<MudIcon Icon="@Icons.Material.Filled.VideocamOff" Size="Size.Large" Color="Color.Default" />
|
||||
<MudText Typo="Typo.h6" Class="mt-2">Aucune caméra détectée</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
|
||||
Lancez un scan avec « Scanner maintenant » (les agents doivent être en ligne),
|
||||
ou vérifiez que des identifiants caméras sont déclarés sur le site.
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_discoveries" Hover="true" Striped="true" Elevation="2">
|
||||
<HeaderContent>
|
||||
<MudTh>Adresse IP</MudTh>
|
||||
<MudTh>Marque / Modèle</MudTh>
|
||||
<MudTh>Type</MudTh>
|
||||
<MudTh>Ports</MudTh>
|
||||
<MudTh>Détecté le</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="IP">
|
||||
<strong>@context.IpAddress</strong>
|
||||
@if (!string.IsNullOrEmpty(context.MacAddress))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">@context.MacAddress</MudText>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Marque">
|
||||
@if (!string.IsNullOrEmpty(context.Vendor) || !string.IsNullOrEmpty(context.OnvifHardware))
|
||||
{
|
||||
<MudText Typo="Typo.body2">@(context.Vendor ?? "Inconnu")</MudText>
|
||||
@if (!string.IsNullOrEmpty(context.OnvifHardware))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">@context.OnvifHardware</MudText>
|
||||
}
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(context.HttpServerHeader))
|
||||
{
|
||||
<MudText Typo="Typo.body2">@context.HttpServerHeader</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Inconnue</MudText>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Type">
|
||||
<StatusChip Text="@FormatType(context.DetectedType)" Color="@TypeColor(context.DetectedType)"
|
||||
Icon="@Icons.Material.Filled.Videocam" />
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Ports">
|
||||
@if (context.OpenPorts.Length == 0) { <MudText Typo="Typo.body2">-</MudText> }
|
||||
else
|
||||
{
|
||||
<div class="d-flex flex-wrap" style="gap: 4px;">
|
||||
@foreach (var port in context.OpenPorts)
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@port</MudChip>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Détecté le">@context.ProbedAt.ToLocalTime().ToString("g")</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudTooltip Text="Ajouter cette caméra">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.AddCircle" Color="Color.Success"
|
||||
aria-label="Confirmer la caméra"
|
||||
OnClick="@(() => OpenConfirm(context))" />
|
||||
</MudTooltip>
|
||||
<MudTooltip Text="Ignorer cette détection">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Cancel" Color="Color.Default"
|
||||
aria-label="Ignorer la détection"
|
||||
OnClick="@(() => Reject(context))" />
|
||||
</MudTooltip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@* ─── Dialog de confirmation ─────────────────────────────────────── *@
|
||||
<MudOverlay Visible="@_confirmShow" OnClick="@(() => _confirmShow = false)" />
|
||||
<MudDialog @bind-Visible="_confirmShow" Options="new DialogOptions { MaxWidth = MaxWidth.Medium, FullWidth = true }">
|
||||
<TitleContent>
|
||||
<MudText Typo="Typo.h6">Ajouter la caméra @_confirm?.IpAddress</MudText>
|
||||
</TitleContent>
|
||||
<DialogContent>
|
||||
@if (_confirm is not null)
|
||||
{
|
||||
<MudTextField @bind-Value="_confirmName" Label="Nom de la caméra *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
|
||||
@if (_confirm.StreamUrls.Length > 0)
|
||||
{
|
||||
<MudSelect T="string" @bind-Value="_selectedStreamUrl" Label="Flux principal"
|
||||
Variant="Variant.Outlined" Class="mb-2" HelperText="URL construite automatiquement">
|
||||
@foreach (var url in _confirm.StreamUrls)
|
||||
{
|
||||
<MudSelectItem Value="@url"><code>@url</code></MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Class="mb-4">
|
||||
Aucune URL de flux n'a pu être construite pour cette caméra.
|
||||
</MudAlert>
|
||||
}
|
||||
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-4">
|
||||
@(_confirm.Vendor ?? "Marque inconnue")
|
||||
@if (!string.IsNullOrEmpty(_confirm.OnvifHardware)) { <text>· @_confirm.OnvifHardware</text> }
|
||||
@if (!string.IsNullOrEmpty(_confirm.MacAddress)) { <text>· @_confirm.MacAddress</text> }
|
||||
</MudText>
|
||||
|
||||
@if (!string.IsNullOrEmpty(_confirmError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_confirmError</MudAlert>
|
||||
}
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmShow = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Success" OnClick="@ConfirmCamera"
|
||||
Disabled="@(_confirming || string.IsNullOrWhiteSpace(_confirmName) || string.IsNullOrEmpty(_selectedStreamUrl))">
|
||||
@if (_confirming) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Ajouter la caméra
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid SiteId { get; set; }
|
||||
|
||||
private List<PendingDiscoveryItem> _discoveries = [];
|
||||
private bool _loading = true;
|
||||
private bool _scanning;
|
||||
|
||||
// Confirmation
|
||||
private PendingDiscoveryItem? _confirm;
|
||||
private bool _confirmShow;
|
||||
private bool _confirming;
|
||||
private string _confirmName = "";
|
||||
private string _selectedStreamUrl = "";
|
||||
private string _confirmError = "";
|
||||
private Guid? _siteAgentId;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadDiscoveries();
|
||||
await LoadSiteAgent();
|
||||
}
|
||||
|
||||
private async Task LoadDiscoveries()
|
||||
{
|
||||
_loading = true;
|
||||
try
|
||||
{
|
||||
_discoveries = await Api.GetPendingDiscoveriesAsync(SiteId);
|
||||
}
|
||||
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private async Task LoadSiteAgent()
|
||||
{
|
||||
try
|
||||
{
|
||||
var agents = await Api.GetAgentsBySiteAsync(SiteId, 1, 50);
|
||||
_siteAgentId = agents?.Items.FirstOrDefault()?.Id;
|
||||
}
|
||||
catch { /* best effort — la caméra sera créée sans agent assigné */ }
|
||||
}
|
||||
|
||||
private async Task ScanNow()
|
||||
{
|
||||
_scanning = true;
|
||||
try
|
||||
{
|
||||
var result = await Api.ScanNowAsync(SiteId);
|
||||
Snackbar.Add(
|
||||
result is { AgentsNotified: > 0 }
|
||||
? $"Scan demandé à {result.AgentsNotified} agent(s)"
|
||||
: "Scan demandé (aucun agent en ligne ?)",
|
||||
result is { AgentsNotified: > 0 } ? Severity.Success : Severity.Warning);
|
||||
await Task.Delay(TimeSpan.FromSeconds(8));
|
||||
await LoadDiscoveries();
|
||||
}
|
||||
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
|
||||
finally { _scanning = false; }
|
||||
}
|
||||
|
||||
private void OpenConfirm(PendingDiscoveryItem item)
|
||||
{
|
||||
_confirm = item;
|
||||
_confirmName = DefaultName(item);
|
||||
_selectedStreamUrl = item.StreamUrls.FirstOrDefault() ?? "";
|
||||
_confirmError = "";
|
||||
_confirmShow = true;
|
||||
}
|
||||
|
||||
private static string DefaultName(PendingDiscoveryItem item)
|
||||
{
|
||||
var vendor = item.Vendor ?? item.OnvifHardware ?? "Caméra";
|
||||
return $"{vendor} ({item.IpAddress})";
|
||||
}
|
||||
|
||||
private async Task ConfirmCamera()
|
||||
{
|
||||
if (_confirm is null || string.IsNullOrEmpty(_selectedStreamUrl)) return;
|
||||
_confirming = true;
|
||||
_confirmError = "";
|
||||
try
|
||||
{
|
||||
var (user, pass) = ExtractCredentials(_selectedStreamUrl);
|
||||
var camera = await Api.ConfirmDiscoveryAsync(
|
||||
SiteId, _confirm.Id, _confirmName.Trim(), _selectedStreamUrl,
|
||||
user, pass, _siteAgentId);
|
||||
if (camera is null)
|
||||
{
|
||||
_confirmError = "Impossible d'ajouter la caméra (déjà enregistrée ou erreur).";
|
||||
return;
|
||||
}
|
||||
Snackbar.Add($"Caméra \"{camera.Name}\" ajoutée", Severity.Success);
|
||||
_confirmShow = false;
|
||||
await LoadDiscoveries();
|
||||
}
|
||||
catch { _confirmError = UiErrors.OperationFailed(); }
|
||||
finally { _confirming = false; }
|
||||
}
|
||||
|
||||
private async Task Reject(PendingDiscoveryItem item)
|
||||
{
|
||||
if (await Api.RejectDiscoveryAsync(item.Id))
|
||||
{
|
||||
Snackbar.Add($"Détection {item.IpAddress} ignorée", Severity.Info);
|
||||
await LoadDiscoveries();
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Erreur lors de l'ignorance", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private static (string? User, string? Pass) ExtractCredentials(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri(url);
|
||||
if (!string.IsNullOrEmpty(uri.UserInfo))
|
||||
{
|
||||
var parts = uri.UserInfo.Split(':', 2);
|
||||
return (Uri.UnescapeDataString(parts[0]),
|
||||
parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : "");
|
||||
}
|
||||
}
|
||||
catch { /* URL invalide — pas de credentials */ }
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
private static string FormatType(string detectedType) => detectedType switch
|
||||
{
|
||||
"Standard" => "Caméra",
|
||||
"Nvr" => "NVR",
|
||||
"HomeKit" => "HomeKit",
|
||||
"Doorbell" => "Sonnette",
|
||||
_ => "Inconnu"
|
||||
};
|
||||
|
||||
private static Color TypeColor(string detectedType) => detectedType switch
|
||||
{
|
||||
"Standard" or "Nvr" => Color.Success,
|
||||
"HomeKit" => Color.Info,
|
||||
_ => Color.Default
|
||||
};
|
||||
}
|
||||
@@ -81,6 +81,62 @@ else
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@* Identifiants caméras (découverte automatique) *@
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<div class="d-flex justify-space-between align-center mb-4">
|
||||
<MudText Typo="Typo.h6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Lock" Class="mr-1" />
|
||||
Identifiants caméras
|
||||
</MudText>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small"
|
||||
OnClick="@(() => _showCredentialDialog = true)">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Ajouter
|
||||
</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
|
||||
Déclarez les couples login/mot de passe possibles des caméras de ce site.
|
||||
Les agents les utilisent pour authentifier et identifier automatiquement
|
||||
chaque caméra détectée sur le réseau.
|
||||
</MudText>
|
||||
|
||||
@if (_credentialsLoading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Size="Size.Small" />
|
||||
}
|
||||
else if (_credentials.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined">
|
||||
Aucun identifiant déclaré. La détection fonctionnera, mais les caméras
|
||||
protégées ne seront pas identifiées automatiquement.
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_credentials" Hover="true" Dense="true">
|
||||
<HeaderContent>
|
||||
<MudTh>Libellé</MudTh>
|
||||
<MudTh>Utilisateur</MudTh>
|
||||
<MudTh>Dernière utilisation</MudTh>
|
||||
<MudTh></MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Libellé">@context.Label</MudTd>
|
||||
<MudTd DataLabel="Utilisateur"><code>@context.Username</code></MudTd>
|
||||
<MudTd DataLabel="Dernière utilisation">
|
||||
@(context.LastUsedAt?.ToString("g") ?? "jamais")
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudTooltip Text="Supprimer cet identifiant">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small"
|
||||
Color="Color.Error" aria-label="Supprimer l'identifiant"
|
||||
OnClick="@(() => DeleteCredential(context))" />
|
||||
</MudTooltip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@* Navigation rapide *@
|
||||
<MudText Typo="Typo.h6" Class="mb-4">Gestion</MudText>
|
||||
<MudGrid>
|
||||
@@ -100,6 +156,14 @@ else
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Voir les agents</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudPaper Elevation="3" Class="pa-4 text-center" Style="border-radius: 12px; cursor: pointer;"
|
||||
@onclick="@(() => Nav.NavigateTo($"/sites/{Id}/discoveries"))">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Radar" Size="Size.Large" Color="Color.Warning" />
|
||||
<MudText Typo="Typo.h6" Class="mt-2">Détection</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Caméras détectées</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Default" Class="mt-4"
|
||||
@@ -108,6 +172,33 @@ else
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
@* ─── Ajout d'identifiant caméra ─────────────────────────────────── *@
|
||||
<MudOverlay Visible="@_showCredentialDialog" OnClick="@(() => _showCredentialDialog = false)" />
|
||||
<MudDialog @bind-Visible="_showCredentialDialog">
|
||||
<TitleContent><MudText Typo="Typo.h6">Ajouter un identifiant caméra</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudTextField @bind-Value="_newCredLabel" Label="Libellé *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true"
|
||||
HelperText="Ex : admin principal, compte NVR, ..." />
|
||||
<MudTextField @bind-Value="_newCredUsername" Label="Utilisateur *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudTextField @bind-Value="_newCredPassword" Label="Mot de passe *" Variant="Variant.Outlined"
|
||||
InputType="InputType.Password" Class="mb-4" Immediate="true" />
|
||||
@if (!string.IsNullOrEmpty(_credentialError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_credentialError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showCredentialDialog = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@AddCredential"
|
||||
Disabled="@(_savingCredential || string.IsNullOrWhiteSpace(_newCredLabel) || string.IsNullOrWhiteSpace(_newCredUsername) || string.IsNullOrWhiteSpace(_newCredPassword))">
|
||||
@if (_savingCredential) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Ajouter
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid Id { get; set; }
|
||||
|
||||
@@ -118,6 +209,16 @@ else
|
||||
private DateTime _tokenExpiresAt;
|
||||
private string _dockerComposeSnippet = "";
|
||||
|
||||
// ── Identifiants caméras ──────────────────────────────────────
|
||||
private List<SiteCredentialItem> _credentials = [];
|
||||
private bool _credentialsLoading = true;
|
||||
private bool _showCredentialDialog;
|
||||
private bool _savingCredential;
|
||||
private string _newCredLabel = "";
|
||||
private string _newCredUsername = "";
|
||||
private string _newCredPassword = "";
|
||||
private string _credentialError = "";
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
@@ -126,6 +227,55 @@ else
|
||||
}
|
||||
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
|
||||
await LoadCredentials();
|
||||
}
|
||||
|
||||
private async Task LoadCredentials()
|
||||
{
|
||||
_credentialsLoading = true;
|
||||
try
|
||||
{
|
||||
_credentials = await Api.GetSiteCredentialsAsync(Id);
|
||||
}
|
||||
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
|
||||
finally { _credentialsLoading = false; }
|
||||
}
|
||||
|
||||
private async Task AddCredential()
|
||||
{
|
||||
_savingCredential = true;
|
||||
_credentialError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.AddSiteCredentialAsync(Id, _newCredLabel, _newCredUsername, _newCredPassword);
|
||||
if (result is null)
|
||||
{
|
||||
_credentialError = "Erreur lors de l'ajout (libellé ou utilisateur déjà utilisé ?)";
|
||||
return;
|
||||
}
|
||||
Snackbar.Add("Identifiant ajouté", Severity.Success);
|
||||
_showCredentialDialog = false;
|
||||
_newCredLabel = "";
|
||||
_newCredUsername = "";
|
||||
_newCredPassword = "";
|
||||
await LoadCredentials();
|
||||
}
|
||||
catch { _credentialError = UiErrors.OperationFailed(); }
|
||||
finally { _savingCredential = false; }
|
||||
}
|
||||
|
||||
private async Task DeleteCredential(SiteCredentialItem credential)
|
||||
{
|
||||
if (await Api.DeleteSiteCredentialAsync(Id, credential.Id))
|
||||
{
|
||||
Snackbar.Add($"Identifiant \"{credential.Label}\" supprimé", Severity.Success);
|
||||
await LoadCredentials();
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Erreur lors de la suppression", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task GenerateToken()
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,75 @@ public class HeimdallApiClient
|
||||
return await response.Content.ReadFromJsonAsync<CameraItem>(Json);
|
||||
}
|
||||
|
||||
// ─── Site camera credentials ───────────────────────────────────
|
||||
|
||||
public async Task<List<SiteCredentialItem>> GetSiteCredentialsAsync(Guid siteId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<SiteCredentialItem>>(
|
||||
$"api/sites/{siteId}/credentials", Json) ?? [];
|
||||
}
|
||||
|
||||
public async Task<SiteCredentialItem?> AddSiteCredentialAsync(Guid siteId, string label, string username, string password)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync($"api/sites/{siteId}/credentials",
|
||||
new { label, username, password }, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<SiteCredentialItem>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteSiteCredentialAsync(Guid siteId, Guid credentialId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.DeleteAsync($"api/sites/{siteId}/credentials/{credentialId}");
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
// ─── Camera discovery (agent-submitted) ──────────────────────────
|
||||
|
||||
public async Task<List<PendingDiscoveryItem>> GetPendingDiscoveriesAsync(Guid siteId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<PendingDiscoveryItem>>(
|
||||
$"api/discovery/sites/{siteId}", Json) ?? [];
|
||||
}
|
||||
|
||||
public async Task<ScanNowResult?> ScanNowAsync(Guid siteId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/discovery/sites/{siteId}/scan-now", null);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<ScanNowResult>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> RejectDiscoveryAsync(Guid resultId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/discovery/{resultId}/reject", null);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<CameraItem?> ConfirmDiscoveryAsync(
|
||||
Guid siteId, Guid discoveryResultId, string name, string mainStreamUrl,
|
||||
string? username, string? password, Guid? agentId = null)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/discovery/confirm",
|
||||
new
|
||||
{
|
||||
siteId,
|
||||
discoveryResultId,
|
||||
name,
|
||||
mainStreamUrl,
|
||||
username,
|
||||
password,
|
||||
agentId
|
||||
}, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<CameraItem>(Json);
|
||||
}
|
||||
|
||||
// ─── Stats ────────────────────────────────────────────────────
|
||||
|
||||
// ─── Audit Logs ──────────────────────────────────────────────
|
||||
@@ -491,6 +560,44 @@ public class CameraItem
|
||||
|
||||
public record TokenResult(string Token, DateTime ExpiresAt);
|
||||
|
||||
// ─── Site credentials & discovery DTOs ─────────────────────────────
|
||||
|
||||
public class SiteCredentialItem
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid SiteId { get; set; }
|
||||
public string Label { get; set; } = "";
|
||||
public string Username { get; set; } = "";
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime? LastUsedAt { get; set; }
|
||||
}
|
||||
|
||||
public class PendingDiscoveryItem
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid SiteId { get; set; }
|
||||
public string IpAddress { get; set; } = "";
|
||||
public string? MacAddress { get; set; }
|
||||
public string? Vendor { get; set; }
|
||||
public string? Hostname { get; set; }
|
||||
public bool IsReachable { get; set; }
|
||||
public string DetectedType { get; set; } = "";
|
||||
public string DiscoveryMethod { get; set; } = "";
|
||||
public int[] OpenPorts { get; set; } = [];
|
||||
public string? OnvifDeviceServiceUrl { get; set; }
|
||||
public string? OnvifName { get; set; }
|
||||
public string? OnvifHardware { get; set; }
|
||||
public int? OnvifPort { get; set; }
|
||||
public string? HttpServerHeader { get; set; }
|
||||
public int? HttpStatusCode { get; set; }
|
||||
public int? HttpPort { get; set; }
|
||||
public DateTime ProbedAt { get; set; }
|
||||
public bool IsProcessed { get; set; }
|
||||
public string[] StreamUrls { get; set; } = [];
|
||||
}
|
||||
|
||||
public record ScanNowResult(int AgentsNotified);
|
||||
|
||||
public record StatsResult(
|
||||
int TotalSites,
|
||||
int TotalCameras,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Reflection;
|
||||
using Heimdall.Agent.Services;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
@@ -8,7 +10,7 @@ namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class ConfigReceiverServiceTests
|
||||
{
|
||||
private static ConfigReceiverService CreateService(AgentState? state = null)
|
||||
private static ConfigReceiverService CreateService(AgentState? state = null, AgentCredentialStore? store = null)
|
||||
{
|
||||
state ??= new AgentState { AgentId = Guid.Empty };
|
||||
var options = Options.Create(new AgentOptions
|
||||
@@ -18,7 +20,8 @@ public class ConfigReceiverServiceTests
|
||||
});
|
||||
var logger = Substitute.For<ILogger<ConfigReceiverService>>();
|
||||
var httpFactory = Substitute.For<IHttpClientFactory>();
|
||||
return new ConfigReceiverService(state, options, logger, httpFactory);
|
||||
var scanTrigger = new DiscoveryScanTrigger();
|
||||
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -123,6 +126,66 @@ public class ConfigReceiverServiceTests
|
||||
state.HeartbeatIntervalSeconds.ShouldBe(30);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplySetting_ScanRequested_DoesNotThrow()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
|
||||
var service = CreateService(state);
|
||||
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
|
||||
BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
method.ShouldNotBeNull();
|
||||
|
||||
// Scan request is fire-and-forget (triggered via DiscoveryScanTrigger)
|
||||
Record.Exception(() => method.Invoke(service, ["discovery.scan.requested", "1"]))
|
||||
.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplySetting_CredentialPool_DecryptsAndStores()
|
||||
{
|
||||
const string apiKey = "test-agent-api-key";
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
|
||||
var store = new AgentCredentialStore();
|
||||
var service = CreateService(state, store);
|
||||
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
|
||||
BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
method.ShouldNotBeNull();
|
||||
|
||||
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
|
||||
var envelope = AgentCredentialEnvelope.Encrypt(
|
||||
[new AgentCameraCredential("admin", "admin", "secret")], key);
|
||||
|
||||
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
|
||||
.ShouldBeNull();
|
||||
|
||||
store.Pool.Count.ShouldBe(1);
|
||||
store.Pool[0].Label.ShouldBe("admin");
|
||||
store.Pool[0].Password.ShouldBe("secret");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplySetting_CredentialPool_WrongKey_KeepsPreviousPool()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "real-key" };
|
||||
var store = new AgentCredentialStore();
|
||||
store.Set([new AgentCameraCredential("old", "old", "old")]);
|
||||
var service = CreateService(state, store);
|
||||
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
|
||||
BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
method.ShouldNotBeNull();
|
||||
|
||||
// Envelope encrypted with a DIFFERENT key than the agent's API key.
|
||||
var wrongKey = AgentCredentialEnvelope.DeriveKeyFromApiKey("other-key");
|
||||
var envelope = AgentCredentialEnvelope.Encrypt(
|
||||
[new AgentCameraCredential("new", "new", "new")], wrongKey);
|
||||
|
||||
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
|
||||
.ShouldBeNull();
|
||||
|
||||
store.Pool.Count.ShouldBe(1);
|
||||
store.Pool[0].Label.ShouldBe("old");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplySetting_InvalidHeartbeatInterval_DoesNotMutateState()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class NetworkCameraScannerTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("192.168.1.0/30", 2)]
|
||||
[InlineData("10.0.0.0/28", 14)]
|
||||
[InlineData("192.168.1.0/31", 2)]
|
||||
public void ExpandSubnet_ValidCidr_ReturnsExpectedCount(string cidr, int expected)
|
||||
{
|
||||
NetworkCameraScanner.ExpandSubnet(cidr).Count.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExpandSubnet_24Mask_Returns254Hosts()
|
||||
{
|
||||
var ips = NetworkCameraScanner.ExpandSubnet("192.168.1.0/24");
|
||||
ips.Count.ShouldBe(254);
|
||||
ips[0].ShouldBe("192.168.1.1");
|
||||
ips[^1].ShouldBe("192.168.1.254");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExpandSubnet_InvalidCidr_ReturnsEmpty()
|
||||
{
|
||||
NetworkCameraScanner.ExpandSubnet("invalid").ShouldBeEmpty();
|
||||
NetworkCameraScanner.ExpandSubnet("192.168.1.0").ShouldBeEmpty();
|
||||
NetworkCameraScanner.ExpandSubnet("192.168.1.0/33").ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DoesNotThrow()
|
||||
{
|
||||
var scanner = new NetworkCameraScanner(Substitute.For<ILogger<NetworkCameraScanner>>());
|
||||
scanner.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Discovery.Commands.RejectDiscovery;
|
||||
using Heimdall.Application.Discovery.Commands.RequestSiteScan;
|
||||
using Heimdall.Application.Discovery.Queries.ListPendingDiscoveries;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.Discovery;
|
||||
|
||||
public class AgentDiscoveryHandlersTests
|
||||
{
|
||||
// ─── Submit (agent → central) ─────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_should_delegate_to_discovery_service()
|
||||
{
|
||||
var service = Substitute.For<ICameraDiscoveryService>();
|
||||
var devices = new List<AgentDiscoveredDevice>
|
||||
{
|
||||
new("192.168.1.10", true, [80, 554], "AA:BB:CC:DD:EE:FF", "Hikvision",
|
||||
null, null, null, null, "http://192.168.1.10/onvif/device_service",
|
||||
null, null, 80, null, null, null)
|
||||
};
|
||||
service.SubmitAgentDiscoveriesAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyList<AgentDiscoveredDevice>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ServiceResult<AgentDiscoverySubmitResponse>.Success(new AgentDiscoverySubmitResponse(1, 1, 0)));
|
||||
var handler = new SubmitAgentDiscoveryHandler(service);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new SubmitAgentDiscoveryCommand(Guid.NewGuid(), devices), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.New.ShouldBe(1);
|
||||
await service.Received(1).SubmitAgentDiscoveriesAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<IReadOnlyList<AgentDiscoveredDevice>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ─── List pending ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task List_pending_should_delegate_to_discovery_service()
|
||||
{
|
||||
var service = Substitute.For<ICameraDiscoveryService>();
|
||||
var pending = new List<PendingDiscoveryResponse>
|
||||
{
|
||||
new(Guid.NewGuid(), Guid.NewGuid(), "192.168.1.10", "AA:BB:CC:DD:EE:FF", "Hikvision",
|
||||
null, true, "Standard", "OnvifWsDiscovery", [80, 554], null, null, null, null,
|
||||
null, null, null, DateTime.UtcNow, false, ["rtsp://192.168.1.10/stream1"])
|
||||
};
|
||||
service.ListPendingDiscoveriesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>.Success(pending));
|
||||
var handler = new ListPendingDiscoveriesHandler(service);
|
||||
|
||||
var result = await handler.Handle(new ListPendingDiscoveriesQuery(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Count.ShouldBe(1);
|
||||
result.Data[0].IpAddress.ShouldBe("192.168.1.10");
|
||||
}
|
||||
|
||||
// ─── Reject ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Reject_should_delegate_to_discovery_service()
|
||||
{
|
||||
var service = Substitute.For<ICameraDiscoveryService>();
|
||||
service.RejectDiscoveryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ServiceResult.Success());
|
||||
var handler = new RejectDiscoveryHandler(service);
|
||||
|
||||
var result = await handler.Handle(new RejectDiscoveryCommand(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
await service.Received(1).RejectDiscoveryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ─── Scan-now (broadcast aux agents du site) ──────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Scan_now_should_notify_online_agents_of_site()
|
||||
{
|
||||
var site = new Site("Site A");
|
||||
var agent1 = new Agent(site.Id, "Agent 1", "host1", "1.0.0");
|
||||
var agent2 = new Agent(site.Id, "Agent 2", "host2", "1.0.0");
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor([site]));
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor([agent1, agent2]));
|
||||
|
||||
var broadcast = Substitute.For<IConfigBroadcastService>();
|
||||
var handler = new RequestSiteScanHandler(context, broadcast);
|
||||
|
||||
var result = await handler.Handle(new RequestSiteScanCommand(site.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.AgentsNotified.ShouldBe(2);
|
||||
await broadcast.Received(1).NotifyAgentSettingChanged(agent1.Id, "discovery.scan.requested", "1", Arg.Any<CancellationToken>());
|
||||
await broadcast.Received(1).NotifyAgentSettingChanged(agent2.Id, "discovery.scan.requested", "1", Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scan_now_unknown_site_should_not_found()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>([]));
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([]));
|
||||
var broadcast = Substitute.For<IConfigBroadcastService>();
|
||||
var handler = new RequestSiteScanHandler(context, broadcast);
|
||||
|
||||
var result = await handler.Handle(new RequestSiteScanCommand(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
}
|
||||
+87
-8
@@ -1,4 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Security;
|
||||
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
@@ -8,10 +10,35 @@ namespace Heimdall.Application.Tests.Handlers.Settings;
|
||||
|
||||
public class GetEffectiveAgentConfigHandlerTests
|
||||
{
|
||||
private static readonly ICredentialProtector Protector = Substitute.For<ICredentialProtector>();
|
||||
private static readonly Guid AgentId = Guid.NewGuid();
|
||||
private static readonly Guid SiteId = Guid.NewGuid();
|
||||
|
||||
// Hex SHA-256 of "test-agent-api-key" — a realistic ApiKeyHash as stored on Agent.
|
||||
private static readonly string ApiKeyHash =
|
||||
Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes("test-agent-api-key"))).ToLowerInvariant();
|
||||
|
||||
private static IApplicationDbContext CreateContext(
|
||||
List<AppSetting>? appSettings = null,
|
||||
List<AgentSetting>? agentSettings = null,
|
||||
List<Agent>? agents = null,
|
||||
List<SiteCredential>? credentials = null)
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>(appSettings ?? []));
|
||||
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>(agentSettings ?? []));
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>(agents ?? []));
|
||||
context.SiteCredentials.Returns(MockDbSetHelper.CreateFor<SiteCredential>(credentials ?? []));
|
||||
|
||||
Protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
|
||||
Protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
|
||||
return context;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_effective_config_should_merge_app_and_agent_settings()
|
||||
{
|
||||
var agentId = Guid.NewGuid();
|
||||
var appSettings = new List<AppSetting>
|
||||
{
|
||||
new("global.key", "global-value", "General"),
|
||||
@@ -19,15 +46,13 @@ public class GetEffectiveAgentConfigHandlerTests
|
||||
};
|
||||
var agentSettings = new List<AgentSetting>
|
||||
{
|
||||
new(agentId, "shared.key", "agent-override"),
|
||||
new(agentId, "agent.only", "agent-value"),
|
||||
new(AgentId, "shared.key", "agent-override"),
|
||||
new(AgentId, "agent.only", "agent-value"),
|
||||
};
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>(appSettings));
|
||||
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>(agentSettings));
|
||||
var handler = new GetEffectiveAgentConfigQueryHandler(context);
|
||||
var context = CreateContext(appSettings: appSettings, agentSettings: agentSettings);
|
||||
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
||||
|
||||
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agentId), CancellationToken.None);
|
||||
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(AgentId), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
@@ -35,4 +60,58 @@ public class GetEffectiveAgentConfigHandlerTests
|
||||
result.Data["shared.key"].ShouldBe("agent-override");
|
||||
result.Data["agent.only"].ShouldBe("agent-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_effective_config_unknown_agent_should_not_include_credential_pool()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
||||
|
||||
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data!.ShouldNotContainKey("discovery.credentials");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_effective_config_agent_with_pool_should_ship_encrypted_credentials()
|
||||
{
|
||||
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
|
||||
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
|
||||
var credentials = new List<SiteCredential>
|
||||
{
|
||||
new(SiteId, "admin principal", "admin", Protector.Encrypt("secret-1")),
|
||||
new(SiteId, "compte NVR", "nvr", Protector.Encrypt("secret-2")),
|
||||
};
|
||||
var context = CreateContext(agents: [agent], credentials: credentials);
|
||||
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
||||
|
||||
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.ShouldContainKey("discovery.credentials");
|
||||
|
||||
// The envelope must decrypt only with the agent's key and reveal the pairs.
|
||||
var key = AgentCredentialEnvelope.DeriveKeyFromApiKeyHash(ApiKeyHash);
|
||||
var pool = AgentCredentialEnvelope.Decrypt(result.Data["discovery.credentials"], key);
|
||||
pool.Count.ShouldBe(2);
|
||||
pool.ShouldContain(c => c.Label == "admin principal" && c.Username == "admin" && c.Password == "secret-1");
|
||||
pool.ShouldContain(c => c.Label == "compte NVR" && c.Username == "nvr" && c.Password == "secret-2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_effective_config_agent_without_api_key_hash_should_not_ship_pool()
|
||||
{
|
||||
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0"); // never registered → no ApiKeyHash
|
||||
var context = CreateContext(agents: [agent]);
|
||||
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
||||
|
||||
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data!.ShouldNotContainKey("discovery.credentials");
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.SiteCredentials.Commands.AddSiteCredential;
|
||||
using Heimdall.Application.SiteCredentials.Commands.DeleteSiteCredential;
|
||||
using Heimdall.Application.SiteCredentials.Queries.ListSiteCredentials;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.SiteCredentials;
|
||||
|
||||
public class SiteCredentialHandlersTests
|
||||
{
|
||||
private readonly Site _site = new("Site A");
|
||||
private readonly ICredentialProtector _protector = Substitute.For<ICredentialProtector>();
|
||||
|
||||
public SiteCredentialHandlersTests()
|
||||
{
|
||||
_protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
|
||||
}
|
||||
|
||||
private IApplicationDbContext CreateContext(params SiteCredential[] credentials)
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor([_site]));
|
||||
context.SiteCredentials.Returns(MockDbSetHelper.CreateFor(credentials.ToList()));
|
||||
return context;
|
||||
}
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task List_should_return_site_credentials()
|
||||
{
|
||||
var cred = new SiteCredential(_site.Id, "admin principal", "admin", "enc_pwd");
|
||||
var context = CreateContext(cred);
|
||||
|
||||
var handler = new ListSiteCredentialsHandler(context);
|
||||
var result = await handler.Handle(new ListSiteCredentialsQuery(_site.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Count.ShouldBe(1);
|
||||
result.Data[0].Label.ShouldBe("admin principal");
|
||||
result.Data[0].Username.ShouldBe("admin");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_unknown_site_should_return_not_found()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new ListSiteCredentialsHandler(context);
|
||||
|
||||
var result = await handler.Handle(new ListSiteCredentialsQuery(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
// ─── Add ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Add_should_encrypt_password_and_save()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new AddSiteCredentialHandler(context, _protector);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new AddSiteCredentialCommand(_site.Id, "admin", "admin", "secret"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
_protector.Received(1).Encrypt("secret");
|
||||
await context.Received(1).SaveChangesWithRetryAsync(ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_missing_fields_should_fail()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new AddSiteCredentialHandler(context, _protector);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new AddSiteCredentialCommand(_site.Id, "", "admin", "secret"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_duplicate_label_should_conflict()
|
||||
{
|
||||
var existing = new SiteCredential(_site.Id, "admin", "admin", "enc");
|
||||
var context = CreateContext(existing);
|
||||
var handler = new AddSiteCredentialHandler(context, _protector);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new AddSiteCredentialCommand(_site.Id, "admin", "autre", "secret"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(409);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_unknown_site_should_not_found()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new AddSiteCredentialHandler(context, _protector);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new AddSiteCredentialCommand(Guid.NewGuid(), "admin", "admin", "secret"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_should_remove_credential()
|
||||
{
|
||||
var cred = new SiteCredential(_site.Id, "admin", "admin", "enc_pwd");
|
||||
var context = CreateContext(cred);
|
||||
var handler = new DeleteSiteCredentialHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new DeleteSiteCredentialCommand(_site.Id, cred.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
await context.Received(1).SaveChangesWithRetryAsync(ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_unknown_credential_should_not_found()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new DeleteSiteCredentialHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new DeleteSiteCredentialCommand(_site.Id, Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Data.Interceptors;
|
||||
using Heimdall.Infrastructure.Services;
|
||||
using Heimdall.Infrastructure.Services.Discovery;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Infrastructure.Tests;
|
||||
|
||||
public class AgentDiscoveryServiceTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
||||
private readonly IOnvifProbeService _onvif = Substitute.For<IOnvifProbeService>();
|
||||
private readonly ICredentialProtector _protector = Substitute.For<ICredentialProtector>();
|
||||
private readonly ILogger<CameraDiscoveryService> _logger = Substitute.For<ILogger<CameraDiscoveryService>>();
|
||||
|
||||
public AgentDiscoveryServiceTests()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
_dbFactory = CreateFactory(_connection);
|
||||
_protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
|
||||
_protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_connection?.Close();
|
||||
_connection?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private static TestDbContextFactory CreateFactory(SqliteConnection connection)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseSqlite(connection)
|
||||
.Options;
|
||||
|
||||
using var ctx = new AppDbContext(opts, new AuditInterceptor());
|
||||
ctx.Database.EnsureCreated();
|
||||
return new TestDbContextFactory(opts);
|
||||
}
|
||||
|
||||
private CameraDiscoveryService CreateService() => new(
|
||||
_dbFactory, _onvif,
|
||||
Substitute.For<IMdnsProbeService>(),
|
||||
Substitute.For<IHttpProbeService>(),
|
||||
Substitute.For<IArpProbeService>(),
|
||||
Substitute.For<IPortScanService>(),
|
||||
new StreamTesterService(Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<StreamTesterService>>()),
|
||||
_protector, _logger);
|
||||
|
||||
private async Task<(Guid SiteId, Guid AgentId)> SeedSiteAndAgentAsync(string siteName = "Site A")
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var site = new Site(siteName);
|
||||
var agent = new Agent(site.Id, "Agent 1", "host1", "1.0.0");
|
||||
db.Sites.Add(site);
|
||||
db.Agents.Add(agent);
|
||||
await db.SaveChangesAsync();
|
||||
return (site.Id, agent.Id);
|
||||
}
|
||||
|
||||
private static AgentDiscoveredDevice Device(string ip, params int[] ports) => new(
|
||||
ip, true, ports, "AA:BB:CC:DD:EE:FF", null, null, null, null, null,
|
||||
null, null, null, ports.Contains(3702) ? 3702 : null, null, null, null);
|
||||
|
||||
// ─── Submit ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_new_devices_should_create_discovery_results()
|
||||
{
|
||||
var (siteId, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
|
||||
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Received.ShouldBe(1);
|
||||
result.Data.New.ShouldBe(1);
|
||||
result.Data.Updated.ShouldBe(0);
|
||||
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var saved = await db.CameraDiscoveryResults.SingleAsync();
|
||||
saved.ShouldNotBeNull();
|
||||
saved.SiteId.ShouldBe(siteId);
|
||||
saved.IpAddress.ShouldBe("192.168.1.10");
|
||||
saved.MacAddress.ShouldBe("AA:BB:CC:DD:EE:FF");
|
||||
saved.IsProcessed.ShouldBeFalse();
|
||||
saved.OpenPorts.ShouldBe([80, 554]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_same_ip_should_update_not_duplicate()
|
||||
{
|
||||
var (_, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
|
||||
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None);
|
||||
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.New.ShouldBe(0);
|
||||
result.Data.Updated.ShouldBe(1);
|
||||
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
db.CameraDiscoveryResults.Count().ShouldBe(1);
|
||||
var savedAgain = await db.CameraDiscoveryResults.SingleAsync();
|
||||
savedAgain.ShouldNotBeNull();
|
||||
savedAgain.OpenPorts.ShouldBe([80, 554]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_unknown_agent_should_not_found()
|
||||
{
|
||||
var service = CreateService();
|
||||
var result = await service.SubmitAgentDiscoveriesAsync(Guid.NewGuid(), [Device("192.168.1.10", 80)], CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_should_persist_agent_enriched_onvif_and_mark_credential_used()
|
||||
{
|
||||
var (siteId, agentId) = await SeedSiteAndAgentAsync();
|
||||
await using (var seedDb = await _dbFactory.CreateDbContextAsync())
|
||||
{
|
||||
seedDb.SiteCredentials.Add(new SiteCredential(siteId, "admin", "admin", _protector.Encrypt("secret")));
|
||||
await seedDb.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var service = CreateService();
|
||||
|
||||
// The agent is on the camera network: it already performed the authenticated
|
||||
// ONVIF enrichment (OnvifName = manufacturer, OnvifHardware = model) and
|
||||
// reports which credential label succeeded. The Central only persists.
|
||||
var device = new AgentDiscoveredDevice(
|
||||
"192.168.1.10", true, [3702], "3C:EF:8C:12:34:56", null, null, null, null, null,
|
||||
"http://192.168.1.10/onvif/device_service", "Hikvision", "DS-2CD2T47", 3702,
|
||||
null, null, null, CredentialLabel: "admin");
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None);
|
||||
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync();
|
||||
saved.OnvifHardware.ShouldBe("DS-2CD2T47");
|
||||
saved.OnvifName.ShouldBe("Hikvision");
|
||||
saved.Vendor.ShouldBe("hikvision"); // normalisé depuis le fabricant ONVIF remonté par l'agent
|
||||
saved.OnvifDeviceServiceUrl.ShouldBe("http://192.168.1.10/onvif/device_service");
|
||||
saved.DiscoveredStreams.Count.ShouldBeGreaterThan(0);
|
||||
|
||||
var cred = await db.SiteCredentials.SingleAsync();
|
||||
cred.LastUsedAt.ShouldNotBeNull(); // marqué via CredentialLabel remonté par l'agent
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_should_not_call_onvif_probe_on_central()
|
||||
{
|
||||
// The Central is not on the camera network: it must never probe ONVIF
|
||||
// itself for agent-submitted devices (authenticated enrichment is the
|
||||
// agent's job). Persisting raw data without enrichment must not throw.
|
||||
var (_, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
|
||||
var device = Device("192.168.1.10", 3702);
|
||||
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
await _onvif.DidNotReceiveWithAnyArgs().ProbeWithCredentialsAsync(
|
||||
Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _onvif.DidNotReceiveWithAnyArgs().ProbeDeviceServiceAsync(
|
||||
Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_should_build_candidate_stream_urls()
|
||||
{
|
||||
var (_, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.20", 554)], CancellationToken.None);
|
||||
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync();
|
||||
saved.DiscoveredStreams.Select(s => s.Url).ShouldContain(u => u.Contains("192.168.1.20"));
|
||||
}
|
||||
|
||||
// ─── List pending ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task List_pending_should_return_only_unprocessed_results()
|
||||
{
|
||||
var (siteId, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80), Device("192.168.1.11", 80)], CancellationToken.None);
|
||||
|
||||
// Reject one of them
|
||||
await using (var db = await _dbFactory.CreateDbContextAsync())
|
||||
{
|
||||
var first = await db.CameraDiscoveryResults.FirstAsync();
|
||||
first.MarkProcessed();
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var result = await service.ListPendingDiscoveriesAsync(siteId, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Count.ShouldBe(1);
|
||||
result.Data[0].IpAddress.ShouldBe("192.168.1.11");
|
||||
result.Data.ShouldNotContain(d => d.IpAddress == "192.168.1.10");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_pending_unknown_site_returns_empty()
|
||||
{
|
||||
var service = CreateService();
|
||||
var result = await service.ListPendingDiscoveriesAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
// ─── Reject ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Reject_should_mark_result_processed()
|
||||
{
|
||||
var (_, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
|
||||
|
||||
await using (var db = await _dbFactory.CreateDbContextAsync())
|
||||
{
|
||||
var saved = await db.CameraDiscoveryResults.SingleAsync();
|
||||
var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
}
|
||||
|
||||
await using var db2 = await _dbFactory.CreateDbContextAsync();
|
||||
(await db2.CameraDiscoveryResults.SingleAsync()).IsProcessed.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reject_already_processed_should_not_found()
|
||||
{
|
||||
var (_, agentId) = await SeedSiteAndAgentAsync();
|
||||
var service = CreateService();
|
||||
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
|
||||
|
||||
await using (var db = await _dbFactory.CreateDbContextAsync())
|
||||
{
|
||||
var saved = await db.CameraDiscoveryResults.SingleAsync();
|
||||
saved.ShouldNotBeNull();
|
||||
await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
|
||||
var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
|
||||
: IDbContextFactory<AppDbContext>
|
||||
{
|
||||
private static readonly AuditInterceptor Audit = new();
|
||||
|
||||
public AppDbContext CreateDbContext() => new(opts, Audit);
|
||||
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
|
||||
=> Task.FromResult(new AppDbContext(opts, Audit));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Net;
|
||||
using Heimdall.Infrastructure.Services.Discovery;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
@@ -17,4 +18,90 @@ public class OnvifProbeServiceTests
|
||||
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProbeDeviceService_with_credentials_should_send_ws_security_header()
|
||||
{
|
||||
string? capturedBody = null;
|
||||
var handler = new StubHttpMessageHandler(request =>
|
||||
{
|
||||
capturedBody = request.Content?.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
const string soapResponse = """
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
|
||||
xmlns:tds="http://www.onvif.org/ver10/device/wsdl">
|
||||
<soap:Body>
|
||||
<tds:GetDeviceInformationResponse>
|
||||
<tds:Manufacturer>Hikvision</tds:Manufacturer>
|
||||
<tds:Model>DS-2CD2T47</tds:Model>
|
||||
</tds:GetDeviceInformationResponse>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
||||
""";
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(soapResponse, System.Text.Encoding.UTF8, "application/soap+xml")
|
||||
};
|
||||
});
|
||||
|
||||
_httpClientFactory.CreateClient("Discovery").Returns(new HttpClient(handler));
|
||||
|
||||
var service = new OnvifProbeService(_httpClientFactory, _logger);
|
||||
var result = await service.ProbeDeviceServiceAsync(
|
||||
"http://192.168.1.10/onvif/device_service", "admin", "secret", CancellationToken.None);
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.Name.ShouldBe("Hikvision");
|
||||
result.Hardware.ShouldBe("DS-2CD2T47");
|
||||
capturedBody.ShouldNotBeNull();
|
||||
capturedBody.ShouldContain("<Security xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
|
||||
capturedBody.ShouldContain("<Username>admin</Username>");
|
||||
capturedBody.ShouldContain("PasswordDigest");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProbeDeviceService_without_credentials_should_send_no_security_header()
|
||||
{
|
||||
string? capturedBody = null;
|
||||
var handler = new StubHttpMessageHandler(request =>
|
||||
{
|
||||
capturedBody = request.Content?.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
const string soapResponse = """
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
|
||||
xmlns:tds="http://www.onvif.org/ver10/device/wsdl">
|
||||
<soap:Body>
|
||||
<tds:GetDeviceInformationResponse>
|
||||
<tds:Manufacturer>Axis</tds:Manufacturer>
|
||||
<tds:Model>M3085</tds:Model>
|
||||
</tds:GetDeviceInformationResponse>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
||||
""";
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(soapResponse, System.Text.Encoding.UTF8, "application/soap+xml")
|
||||
};
|
||||
});
|
||||
|
||||
_httpClientFactory.CreateClient("Discovery").Returns(new HttpClient(handler));
|
||||
|
||||
var service = new OnvifProbeService(_httpClientFactory, _logger);
|
||||
var result = await service.ProbeDeviceServiceAsync(
|
||||
"http://192.168.1.11/onvif/device_service", null, null, CancellationToken.None);
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.Name.ShouldBe("Axis");
|
||||
capturedBody.ShouldNotBeNull();
|
||||
capturedBody.ShouldNotContain("Security");
|
||||
}
|
||||
|
||||
/// <summary>HttpMessageHandler stub for capturing request bodies.</summary>
|
||||
private sealed class StubHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> responder)
|
||||
: HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request, CancellationToken ct)
|
||||
=> Task.FromResult(responder(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Bunit;
|
||||
using Heimdall.Web.Components.Pages;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MudBlazor;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
public class DiscoveriesPageTests : PageTestBase
|
||||
{
|
||||
private static readonly Guid SiteId = Guid.NewGuid();
|
||||
private static readonly Guid DiscoveryId = Guid.NewGuid();
|
||||
|
||||
private static PendingDiscoveryItem Discovery(
|
||||
string ip = "192.168.1.10",
|
||||
string? vendor = "Hikvision",
|
||||
string? hardware = "DS-2CD2T47",
|
||||
string[]? urls = null) => new()
|
||||
{
|
||||
Id = DiscoveryId,
|
||||
SiteId = SiteId,
|
||||
IpAddress = ip,
|
||||
MacAddress = "3C:EF:8C:12:34:56",
|
||||
Vendor = vendor,
|
||||
OnvifHardware = hardware,
|
||||
IsReachable = true,
|
||||
DetectedType = "Standard",
|
||||
DiscoveryMethod = "OnvifWsDiscovery",
|
||||
OpenPorts = [80, 554, 3702],
|
||||
OnvifDeviceServiceUrl = $"http://{ip}/onvif/device_service",
|
||||
OnvifName = vendor,
|
||||
OnvifPort = 3702,
|
||||
ProbedAt = DateTime.UtcNow.AddMinutes(-2),
|
||||
StreamUrls = urls ?? [$"rtsp://{ip}:554/stream1"],
|
||||
};
|
||||
|
||||
private static AgentItem Agent() => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
SiteId = SiteId,
|
||||
Name = "Agent 1",
|
||||
Hostname = "host1",
|
||||
Status = "Online",
|
||||
};
|
||||
|
||||
private void RouteDiscoveries(List<PendingDiscoveryItem> discoveries)
|
||||
{
|
||||
Handler.OnGet("api/discovery/sites/", discoveries);
|
||||
Handler.OnGet("api/agents/by-site/", new PagedData<AgentItem>([Agent()], 1, 1, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoveriesPage_AfficheListeDesDecouvertes()
|
||||
{
|
||||
RouteDiscoveries([Discovery()]);
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<DiscoveriesPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Caméras détectées");
|
||||
cut.Markup.ShouldContain("192.168.1.10");
|
||||
cut.Markup.ShouldContain("Hikvision");
|
||||
cut.Markup.ShouldContain("DS-2CD2T47");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoveriesPage_AucuneDecouverte_AfficheMessage()
|
||||
{
|
||||
RouteDiscoveries([]);
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<DiscoveriesPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucune caméra détectée"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoveriesPage_ScanNow_NotifieAgents()
|
||||
{
|
||||
RouteDiscoveries([]);
|
||||
Handler.On(HttpMethod.Post, "scan-now", new ScanNowResult(2));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<DiscoveriesPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Scanner maintenant"));
|
||||
|
||||
cut.FindAll("button").Single(b => b.TextContent.Contains("Scanner maintenant")).Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var snackbar = Services.GetRequiredService<ISnackbar>();
|
||||
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
|
||||
.ShouldContain(m => m.Contains("2 agent", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoveriesPage_Confirmer_AjouteCamera()
|
||||
{
|
||||
RouteDiscoveries([Discovery()]);
|
||||
Handler.On(HttpMethod.Post, "confirm", new CameraItem
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
SiteId = SiteId,
|
||||
Name = "Hikvision (192.168.1.10)",
|
||||
Status = "Online",
|
||||
});
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<DiscoveriesPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("192.168.1.10"));
|
||||
|
||||
cut.FindAll("button[aria-label='Confirmer la caméra']")[0].Click();
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Ajouter la caméra 192.168.1.10"));
|
||||
|
||||
// Le nom par défaut est pré-rempli et l'URL de flux sélectionnée → bouton actif.
|
||||
cut.FindAll("button").Single(b => b.TextContent.Contains("Ajouter la caméra") && b.TextContent.Contains("Ajouter")).Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var snackbar = Services.GetRequiredService<ISnackbar>();
|
||||
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
|
||||
.ShouldContain(m => m.Contains("ajoutée", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoveriesPage_Rejeter_IgnoreDetection()
|
||||
{
|
||||
RouteDiscoveries([Discovery()]);
|
||||
Handler.On(HttpMethod.Post, $"api/discovery/{DiscoveryId}/reject", System.Net.HttpStatusCode.OK);
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<DiscoveriesPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("192.168.1.10"));
|
||||
|
||||
cut.FindAll("button[aria-label='Ignorer la détection']")[0].Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var snackbar = Services.GetRequiredService<ISnackbar>();
|
||||
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
|
||||
.ShouldContain(m => m.Contains("ignorée", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -104,4 +104,118 @@ public class SiteDetailTests : PageTestBase
|
||||
|
||||
cut.WaitForAssertion(() => nav.Uri.ShouldBe($"http://localhost/sites/{SiteId}/cameras"));
|
||||
}
|
||||
|
||||
// ─── Identifiants caméras (pool de credentials) ────────────────────
|
||||
|
||||
private static SiteCredentialItem Credential(string label, string username, DateTime? lastUsed = null) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
SiteId = SiteId,
|
||||
Label = label,
|
||||
Username = username,
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-3),
|
||||
LastUsedAt = lastUsed,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_AucunIdentifiant_AfficheMessage()
|
||||
{
|
||||
// Routes spécifiques AVANT la route générique (le handler matche par substring).
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty<SiteCredentialItem>());
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun identifiant déclaré"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_AfficheIdentifiantsDeclares()
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials",
|
||||
new List<SiteCredentialItem>
|
||||
{
|
||||
Credential("admin principal", "admin"),
|
||||
Credential("compte NVR", "nvr", DateTime.UtcNow.AddHours(-1)),
|
||||
});
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Identifiants caméras");
|
||||
cut.Markup.ShouldContain("admin principal");
|
||||
cut.Markup.ShouldContain("compte NVR");
|
||||
cut.Markup.ShouldContain("<code>admin</code>");
|
||||
cut.Markup.ShouldContain("<code>nvr</code>");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_AjouterIdentifiant_PostEtAffiche()
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", new List<SiteCredentialItem>());
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Post, $"api/sites/{SiteId}/credentials",
|
||||
Credential("admin principal", "admin"));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Identifiants caméras"));
|
||||
|
||||
// Ouvrir le dialog d'ajout (bouton "Ajouter" de la section, pas du dialog).
|
||||
cut.FindAll("button").First(b => b.TextContent.Trim() == "Ajouter").Click();
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Ajouter un identifiant caméra"));
|
||||
|
||||
// Remplir les 3 champs (Immediate=true → .Input). Les seuls inputs de la
|
||||
// page sont ceux du dialog d'ajout.
|
||||
var inputs = cut.FindAll("input");
|
||||
inputs.Count.ShouldBeGreaterThanOrEqualTo(3);
|
||||
inputs[0].Input("admin principal");
|
||||
inputs[1].Input("admin");
|
||||
inputs[2].Input("secret");
|
||||
|
||||
// Le bouton "Ajouter" du dialog s'active une fois les 3 champs remplis.
|
||||
// (Le provider du dialog est rendu AVANT le contenu de la page : cibler
|
||||
// les actions du dialog, pas tous les boutons "Ajouter".)
|
||||
cut.FindAll("div.mud-dialog-actions button")
|
||||
.Single(b => b.TextContent.Trim() == "Ajouter")
|
||||
.Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var snackbar = Services.GetRequiredService<ISnackbar>();
|
||||
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
|
||||
.ShouldContain("Identifiant ajouté");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_SupprimerIdentifiant_DeleteEtAffiche()
|
||||
{
|
||||
var cred = Credential("admin principal", "admin");
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", new List<SiteCredentialItem> { cred });
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Delete, $"api/sites/{SiteId}/credentials/{cred.Id}", System.Net.HttpStatusCode.NoContent);
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("admin principal"));
|
||||
|
||||
cut.FindAll("button[aria-label=\"Supprimer l'identifiant\"]")[0].Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var snackbar = Services.GetRequiredService<ISnackbar>();
|
||||
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
|
||||
.ShouldContain(m => m.Contains("supprimé", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user