From f8f2b08d295cd6ea520563dd500c649a8c35ff31 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 11 Aug 2026 16:15:41 +0200 Subject: [PATCH] =?UTF-8?q?feat(agent):=20enrichissement=20ONVIF=20authent?= =?UTF-8?q?ifi=C3=A9=20c=C3=B4t=C3=A9=20agent=20=E2=80=94=20pool=20chiffr?= =?UTF-8?q?=C3=A9=20via=20config=20(#49)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/49 --- src/Heimdall.Agent/AgentOptions.cs | 7 + src/Heimdall.Agent/Program.cs | 4 + .../Services/AgentCredentialStore.cs | 20 + .../Services/AgentDiscoveryService.cs | 132 ++ .../Services/ConfigReceiverService.cs | 61 +- .../Services/DiscoveryScanTrigger.cs | 20 + .../Services/NetworkCameraScanner.cs | 546 +++++ .../SubmitAgentDiscoveryCommand.cs | 22 + .../Common/IApplicationDbContext.cs | 1 + .../DTOs/SiteCredentialDto.cs | 98 + .../RejectDiscovery/RejectDiscoveryCommand.cs | 17 + .../RequestSiteScan/RequestSiteScanCommand.cs | 50 + .../ListPendingDiscoveriesQuery.cs | 19 + .../Security/AgentCredentialEnvelope.cs | 72 + .../Services/ICameraDiscoveryService.cs | 22 + .../GetEffectiveAgentConfigQuery.cs | 41 +- .../AddSiteCredentialCommand.cs | 61 + .../DeleteSiteCredentialCommand.cs | 30 + .../ListSiteCredentialsQuery.cs | 36 + .../Entities/CameraDiscoveryResult.cs | 6 + src/Heimdall.Domain/Entities/Site.cs | 4 + .../Entities/SiteCredential.cs | 49 + .../Data/AppDbContext.cs | 1 + .../SiteCredentialConfiguration.cs | 43 + ...60811120321_AddSiteCredentials.Designer.cs | 1831 +++++++++++++++++ .../20260811120321_AddSiteCredentials.cs | 50 + .../Migrations/AppDbContextModelSnapshot.cs | 55 + .../Discovery/CameraDiscoveryService.cs | 313 +++ .../Services/Discovery/IOnvifProbeService.cs | 18 + .../Services/Discovery/OnvifProbeService.cs | 157 +- .../Components/Pages/DiscoveriesPage.razor | 319 +++ .../Components/Pages/SiteDetail.razor | 150 ++ .../Controllers/AgentsController.cs | 22 + .../Controllers/DiscoveryController.cs | 42 + .../Controllers/SettingsController.cs | 26 +- .../Controllers/SitesController.cs | 65 +- .../Services/HeimdallApiClient.cs | 107 + .../ConfigReceiverServiceTests.cs | 67 +- .../NetworkCameraScannerTests.cs | 42 + .../Discovery/AgentDiscoveryHandlersTests.cs | 121 ++ .../GetEffectiveAgentConfigHandlerTests.cs | 95 +- .../SiteCredentialHandlersTests.cs | 143 ++ .../AgentDiscoveryServiceTests.cs | 278 +++ .../OnvifProbeServiceTests.cs | 87 + .../Components/Pages/DiscoveriesPageTests.cs | 151 ++ .../Components/Pages/SiteDetailTests.cs | 114 + 46 files changed, 5563 insertions(+), 52 deletions(-) create mode 100644 src/Heimdall.Agent/Services/AgentCredentialStore.cs create mode 100644 src/Heimdall.Agent/Services/AgentDiscoveryService.cs create mode 100644 src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs create mode 100644 src/Heimdall.Agent/Services/NetworkCameraScanner.cs create mode 100644 src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs create mode 100644 src/Heimdall.Application/DTOs/SiteCredentialDto.cs create mode 100644 src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs create mode 100644 src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs create mode 100644 src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs create mode 100644 src/Heimdall.Application/Security/AgentCredentialEnvelope.cs create mode 100644 src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs create mode 100644 src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs create mode 100644 src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs create mode 100644 src/Heimdall.Domain/Entities/SiteCredential.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.cs create mode 100644 src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor create mode 100644 tests/Heimdall.Agent.Tests/NetworkCameraScannerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Discovery/AgentDiscoveryHandlersTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/SiteCredentials/SiteCredentialHandlersTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs create mode 100644 tests/Heimdall.Web.Tests/Components/Pages/DiscoveriesPageTests.cs diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 2493dd4..524f059 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -35,6 +35,13 @@ public sealed class AgentOptions [Range(1, 20)] public int RegistrationMaxRetries { get; init; } = 5; + /// Interval between automatic camera network scans in seconds (default: 900 = 15 min). + [Range(60, 86400)] + public int DiscoveryIntervalSeconds { get; init; } = 900; + + /// Enable automatic camera discovery on the local network (default: true). + public bool DiscoveryEnabled { get; init; } = true; + /// Agent software version reported to Central. public string Version { get; init; } = "1.0.0"; } diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 1dc582b..68f5a79 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -61,8 +61,12 @@ builder.Services.AddSingleton(sp => }); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); // Health checks — used by Docker HEALTHCHECK builder.Services.AddHealthChecks() diff --git a/src/Heimdall.Agent/Services/AgentCredentialStore.cs b/src/Heimdall.Agent/Services/AgentCredentialStore.cs new file mode 100644 index 0000000..124b01a --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentCredentialStore.cs @@ -0,0 +1,20 @@ +using Heimdall.Application.DTOs; + +namespace Heimdall.Agent.Services; + +/// +/// 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 (writes) and +/// / +/// (reads). Never persisted to disk. +/// +public sealed class AgentCredentialStore +{ + private IReadOnlyList _pool = []; + + public IReadOnlyList Pool => Volatile.Read(ref _pool); + + public void Set(IReadOnlyList pool) + => Interlocked.Exchange(ref _pool, pool ?? []); +} diff --git a/src/Heimdall.Agent/Services/AgentDiscoveryService.cs b/src/Heimdall.Agent/Services/AgentDiscoveryService.cs new file mode 100644 index 0000000..7db9720 --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentDiscoveryService.cs @@ -0,0 +1,132 @@ +using System.Net.Http.Json; +using Heimdall.Application.DTOs; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// +/// 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 ) +/// 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 +/// seconds, and on demand +/// via (pushed by Central over SignalR). +/// +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 _logger; + + public AgentDiscoveryService( + AgentState state, + IOptions options, + NetworkCameraScanner scanner, + DiscoveryScanTrigger trigger, + AgentCredentialStore credentialStore, + IHttpClientFactory httpClientFactory, + ILogger 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(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)"); + } + } +} diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index 2296077..90abb7f 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -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 _logger; private readonly IHttpClientFactory _httpClientFactory; + private readonly DiscoveryScanTrigger _scanTrigger; + private readonly AgentCredentialStore _credentialStore; private HubConnection? _connection; public ConfigReceiverService( AgentState state, IOptions options, ILogger 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; } } + /// + /// 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). + /// + 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>(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) { diff --git a/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs b/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs new file mode 100644 index 0000000..25bbb64 --- /dev/null +++ b/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs @@ -0,0 +1,20 @@ +using System.Threading.Channels; + +namespace Heimdall.Agent.Services; + +/// +/// Shared trigger allowing ConfigReceiverService (SignalR "scan now" push) +/// to wake the AgentDiscoveryService for an immediate network scan. +/// +public sealed class DiscoveryScanTrigger +{ + private readonly Channel _channel = Channel.CreateBounded( + new BoundedChannelOptions(4) { FullMode = BoundedChannelFullMode.DropWrite }); + + public void Trigger() + { + _channel.Writer.TryWrite(true); + } + + public ValueTask WaitAsync(CancellationToken ct) => _channel.Reader.ReadAsync(ct); +} diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs new file mode 100644 index 0000000..d02ac59 --- /dev/null +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -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; + +/// +/// 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 +/// authenticated 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. +/// +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 _logger; + private readonly string? _localIp; + + public NetworkCameraScanner(ILogger logger) + { + _logger = logger; + _localIp = GetLocalIpv4(); + } + + /// + /// Scan the local subnet for camera-like devices. Returns an empty list + /// when the local network cannot be determined. When + /// 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. + /// + public async Task> ScanAsync( + CancellationToken ct, IReadOnlyList? 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(); + 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 ProbeHostAsync( + string ip, IReadOnlyList? 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> ScanPortsAsync(string ip, CancellationToken ct) + { + var open = new ConcurrentBag(); + 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 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 ProbeOnvifAsync( + string ip, int port, IReadOnlyList? 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 = $@" + + + {WsdNs.NamespaceName}/Probe + uuid:{messageId} + urn:schemas-xmlsoap-org:ws:2005:04:discovery + + + + tdn:NetworkVideoTransmitter + + +"; + + 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; + } + } + + /// + /// 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. + /// + private async Task GetDeviceInformationWithCredentialsAsync( + string deviceServiceUrl, IReadOnlyList? 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 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; + } + } + + /// + /// Build the GetDeviceInformation SOAP envelope, adding a WS-Security + /// UsernameToken when credentials are provided (PasswordDigest or + /// PasswordText, matching ONVIF interop requirements). + /// + 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 = $@" + + + + {username} + {Convert.ToBase64String(digest)} + {Convert.ToBase64String(nonce)} + {created} + + + "; + } + else + { + securityHeader = $@" + + + + {username} + {password} + + + "; + } + } + + return $@" +{securityHeader} + + + +"; + } + + // ─── 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; + } + + /// + /// 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. + /// + 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; + } + + /// Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP. + 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; + } + + /// Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536). + internal static List 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((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; + } + + /// Read the ARP table (/proc/net/arp) to resolve an IP's MAC address. + 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); +} diff --git a/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs b/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs new file mode 100644 index 0000000..0281294 --- /dev/null +++ b/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs @@ -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 Devices) : IRequest>; + +public class SubmitAgentDiscoveryHandler : IRequestHandler> +{ + private readonly ICameraDiscoveryService _discovery; + + public SubmitAgentDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery; + + public async Task> Handle( + SubmitAgentDiscoveryCommand request, CancellationToken cancellationToken) + => await _discovery.SubmitAgentDiscoveriesAsync(request.AgentId, request.Devices, cancellationToken) + .ConfigureAwait(false); +} diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 0fe8416..27ab50f 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -28,6 +28,7 @@ public interface IApplicationDbContext DbSet Persons { get; } DbSet RevokedRefreshTokens { get; } DbSet Sites { get; } + DbSet SiteCredentials { get; } DbSet UserGroups { get; } DbSet UserSites { get; } Task SaveChangesAsync(CancellationToken cancellationToken); diff --git a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs new file mode 100644 index 0000000..ede7d4a --- /dev/null +++ b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs @@ -0,0 +1,98 @@ +namespace Heimdall.Application.DTOs; + +// ──────────────────────────────────────────────────────────────────── +// Site credentials (pool of login/password pairs for camera discovery) +// ──────────────────────────────────────────────────────────────────── + +/// Credential pair declared for a site. Password is write-only: never returned by the API. +public record SiteCredentialResponse( + Guid Id, + Guid SiteId, + string Label, + string Username, + DateTime CreatedAt, + DateTime? LastUsedAt); + +/// Add a credential pair to a site. +public record AddSiteCredentialRequest( + string Label, + string Username, + string Password); + +/// +/// A credential pair shipped inside the agent config envelope. The password is +/// only ever present inside the encrypted envelope — never in plain settings. +/// +public record AgentCameraCredential( + string Label, + string Username, + string Password); + +// ──────────────────────────────────────────────────────────────────── +// Agent-submitted discovery results +// ──────────────────────────────────────────────────────────────────── + +/// +/// 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. +/// +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); + +/// Response to an agent's discovery submission. +public record AgentDiscoverySubmitResponse( + int Received, + int New, + int Updated); + +// ──────────────────────────────────────────────────────────────────── +// Pending discovery results (UI) +// ──────────────────────────────────────────────────────────────────── + +/// A persisted discovery result exposed to the UI for confirmation. +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); + +/// Request to reject (ignore) a pending discovery result. +public record RejectDiscoveryRequest(Guid ResultId); + +/// Result of a scan-now request broadcast to site agents. +public record ScanNowResponse(int AgentsNotified); diff --git a/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs b/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs new file mode 100644 index 0000000..d0b727d --- /dev/null +++ b/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs @@ -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; + +public class RejectDiscoveryHandler : IRequestHandler +{ + private readonly ICameraDiscoveryService _discovery; + + public RejectDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery; + + public async Task Handle(RejectDiscoveryCommand request, CancellationToken cancellationToken) + => await _discovery.RejectDiscoveryAsync(request.ResultId, cancellationToken).ConfigureAwait(false); +} diff --git a/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs b/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs new file mode 100644 index 0000000..5bc8577 --- /dev/null +++ b/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs @@ -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>; + +/// +/// 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. +/// +public class RequestSiteScanHandler : IRequestHandler> +{ + private readonly IApplicationDbContext _context; + private readonly IConfigBroadcastService _broadcast; + + public RequestSiteScanHandler(IApplicationDbContext context, IConfigBroadcastService broadcast) + { + _context = context; + _broadcast = broadcast; + } + + public async Task> Handle( + RequestSiteScanCommand request, CancellationToken cancellationToken) + { + var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false); + if (!siteExists) + return ServiceResult.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.Success(new ScanNowResponse(notified)); + } +} diff --git a/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs b/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs new file mode 100644 index 0000000..fbe4b87 --- /dev/null +++ b/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs @@ -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>>; + +public class ListPendingDiscoveriesHandler : IRequestHandler>> +{ + private readonly ICameraDiscoveryService _discovery; + + public ListPendingDiscoveriesHandler(ICameraDiscoveryService discovery) => _discovery = discovery; + + public async Task>> Handle( + ListPendingDiscoveriesQuery request, CancellationToken cancellationToken) + => await _discovery.ListPendingDiscoveriesAsync(request.SiteId, cancellationToken).ConfigureAwait(false); +} diff --git a/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs b/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs new file mode 100644 index 0000000..c0a3fa2 --- /dev/null +++ b/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs @@ -0,0 +1,72 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Security; + +/// +/// 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 (), +/// 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. +/// +public static class AgentCredentialEnvelope +{ + private const string Prefix = "v1:"; + private const int NonceSize = 12; + private const int TagSize = 16; + + /// + /// 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). + /// + public static byte[] DeriveKeyFromApiKeyHash(string apiKeyHash) + => Convert.FromHexString(apiKeyHash); + + /// Derive the AES key from the plaintext API key (agent side). + public static byte[] DeriveKeyFromApiKey(string apiKey) + => SHA256.HashData(Encoding.UTF8.GetBytes(apiKey)); + + public static string Encrypt(IReadOnlyList 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 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(payload) ?? []; + } +} diff --git a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs index a681d0b..c47f41d 100644 --- a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs +++ b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs @@ -79,4 +79,26 @@ public interface ICameraDiscoveryService /// Task> CheckDuplicateAsync( CheckDuplicateRequest request, CancellationToken ct); + + /// + /// 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. + /// + Task> SubmitAgentDiscoveriesAsync( + Guid agentId, IReadOnlyList devices, CancellationToken ct); + + /// + /// List pending (unprocessed) discovery results for a site, newest first. + /// + Task>> ListPendingDiscoveriesAsync( + Guid siteId, CancellationToken ct); + + /// + /// Mark a discovery result as rejected (ignored) so it no longer appears + /// in the pending list. Does not delete the row. + /// + Task RejectDiscoveryAsync(Guid resultId, CancellationToken ct); } diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index 1bc684f..ee3ddf4 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -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>> { 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>> 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>.Success(config); } } diff --git a/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs b/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs new file mode 100644 index 0000000..c4c35a0 --- /dev/null +++ b/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs @@ -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>; + +public class AddSiteCredentialHandler : IRequestHandler> +{ + private readonly IApplicationDbContext _context; + private readonly ICredentialProtector _protector; + + public AddSiteCredentialHandler(IApplicationDbContext context, ICredentialProtector protector) + { + _context = context; + _protector = protector; + } + + public async Task> Handle( + AddSiteCredentialCommand request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.Label)) + return ServiceResult.Failure("Label is required"); + if (string.IsNullOrWhiteSpace(request.Username)) + return ServiceResult.Failure("Username is required"); + if (string.IsNullOrWhiteSpace(request.Password)) + return ServiceResult.Failure("Password is required"); + + var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false); + if (!siteExists) + return ServiceResult.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.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.Success(new SiteCredentialResponse( + credential.Id, credential.SiteId, credential.Label, credential.Username, + credential.CreatedAt, credential.LastUsedAt)); + } +} diff --git a/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs b/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs new file mode 100644 index 0000000..e6d1475 --- /dev/null +++ b/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs @@ -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; + +public class DeleteSiteCredentialHandler : IRequestHandler +{ + private readonly IApplicationDbContext _context; + + public DeleteSiteCredentialHandler(IApplicationDbContext context) => _context = context; + + public async Task 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(); + } +} diff --git a/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs b/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs new file mode 100644 index 0000000..c7b8464 --- /dev/null +++ b/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs @@ -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>>; + +public class ListSiteCredentialsHandler : IRequestHandler>> +{ + private readonly IApplicationDbContext _context; + + public ListSiteCredentialsHandler(IApplicationDbContext context) => _context = context; + + public async Task>> Handle( + ListSiteCredentialsQuery request, CancellationToken cancellationToken) + { + var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false); + if (!siteExists) + return ServiceResult>.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>.Success(response); + } +} diff --git a/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs index ea6fb24..582e1b5 100644 --- a/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs +++ b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs @@ -116,5 +116,11 @@ public class CameraDiscoveryResult : Entity Vendor = vendor; } + public void SetHostname(string? hostname) + { + if (!string.IsNullOrEmpty(hostname)) + Hostname = hostname; + } + public void MarkProcessed() => IsProcessed = true; } diff --git a/src/Heimdall.Domain/Entities/Site.cs b/src/Heimdall.Domain/Entities/Site.cs index 97147de..8fa8f8c 100644 --- a/src/Heimdall.Domain/Entities/Site.cs +++ b/src/Heimdall.Domain/Entities/Site.cs @@ -30,6 +30,10 @@ public class Site : Entity, IAuditableEntity, ISoftDeletable private readonly List _cameras = []; public IReadOnlyCollection Cameras => _cameras.AsReadOnly(); + /// Credential pairs declared for this site (used by camera discovery). + private readonly List _credentials = []; + public IReadOnlyCollection Credentials => _credentials.AsReadOnly(); + private Site() { } // EF Core public Site(string name, string? address = null, string? timezone = null) diff --git a/src/Heimdall.Domain/Entities/SiteCredential.cs b/src/Heimdall.Domain/Entities/SiteCredential.cs new file mode 100644 index 0000000..74e431e --- /dev/null +++ b/src/Heimdall.Domain/Entities/SiteCredential.cs @@ -0,0 +1,49 @@ +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// 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 +/// (applied in the +/// application/service layer before storage) — never stored in plain text. +/// +public class SiteCredential : Entity +{ + public Guid SiteId { get; private set; } + public Site Site { get; private set; } = null!; + + /// Human-readable label, e.g. "admin principal" or "comptes NVR". + public string Label { get; private set; } = string.Empty; + + public string Username { get; private set; } = string.Empty; + + /// Encrypted via ICredentialProtector at the service layer. + public string Password { get; private set; } = string.Empty; + + public DateTime CreatedAt { get; private set; } = DateTime.UtcNow; + + /// Last time a discovery successfully used this credential pair. + 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; +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 5892eba..7ec75e4 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -21,6 +21,7 @@ public class AppDbContext : IdentityDbContext, IApplicat // Domain entities public DbSet Sites => Set(); + public DbSet SiteCredentials => Set(); public DbSet Agents => Set(); public DbSet Cameras => Set(); public DbSet CameraCredentials => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs new file mode 100644 index 0000000..b6e1a3f --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs @@ -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 +{ + public void Configure(EntityTypeBuilder 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); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs new file mode 100644 index 0000000..870178b --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs @@ -0,0 +1,1831 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260811120321_AddSiteCredentials")] + partial class AddSiteCredentials + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("OccurredAt"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("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("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + 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") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.cs b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.cs new file mode 100644 index 0000000..a642b10 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddSiteCredentials : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "site_credentials", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + Label = table.Column(type: "character varying(100)", unicode: false, maxLength: 100, nullable: false), + Username = table.Column(type: "character varying(200)", unicode: false, maxLength: 200, nullable: false), + Password = table.Column(type: "character varying(2000)", unicode: false, maxLength: 2000, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + LastUsedAt = table.Column(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"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "site_credentials"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 2cd2845..a9f51e8 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1302,6 +1302,48 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("sites", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("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("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 } diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs index 92661a2..652b6d6 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs @@ -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> SubmitAgentDiscoveriesAsync( + Guid agentId, IReadOnlyList 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.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.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 { "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 ────────────────────────── + + /// + /// 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 + /// from the ONVIF manufacturer when available. + /// + 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; + } + + /// + /// Map an ONVIF manufacturer name to a camera-database vendor key + /// (b:xxx used in ). Returns null when the + /// manufacturer is unknown — the generic templates still apply. + /// + 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>> 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>.Success(response); + } + + public async Task 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( diff --git a/src/Heimdall.Infrastructure/Services/Discovery/IOnvifProbeService.cs b/src/Heimdall.Infrastructure/Services/Discovery/IOnvifProbeService.cs index 22572e5..8580430 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/IOnvifProbeService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/IOnvifProbeService.cs @@ -19,4 +19,22 @@ public interface IOnvifProbeService /// Returns null if no ONVIF device is detected. /// Task ProbeAsync(string ipAddress, int port = 3702, CancellationToken ct = default); + + /// + /// 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. + /// + Task ProbeWithCredentialsAsync( + string ipAddress, string? username, string? password, int port = 3702, CancellationToken ct = default); + + /// + /// 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. + /// + Task ProbeDeviceServiceAsync( + string deviceServiceUrl, string? username, string? password, CancellationToken ct = default); } diff --git a/src/Heimdall.Infrastructure/Services/Discovery/OnvifProbeService.cs b/src/Heimdall.Infrastructure/Services/Discovery/OnvifProbeService.cs index e7823d3..51c6773 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/OnvifProbeService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/OnvifProbeService.cs @@ -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 _logger; @@ -36,10 +40,20 @@ public sealed class OnvifProbeService : IOnvifProbeService } public async Task ProbeAsync(string ipAddress, int port = 3702, CancellationToken ct = default) + => await ProbeWithCredentialsAsync(ipAddress, null, null, port, ct).ConfigureAwait(false); + + /// + /// 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. + /// + public async Task 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 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 GetDeviceInformationAsync(string deviceServiceUrl, CancellationToken ct) + private async Task GetDeviceInformationAsync( + string deviceServiceUrl, string? username, string? password, CancellationToken ct) { try { var client = _httpClientFactory.CreateClient("Discovery"); client.Timeout = HttpTimeout; - var soapBody = $@" - - - - -"; + // 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 = $@" + + + + {username} + {Convert.ToBase64String(digest)} + {Convert.ToBase64String(nonce)} + {created} + + + "; + } + else + { + securityHeader = $@" + + + + {username} + {password} + + + "; + } + } + + return $@" +{securityHeader} + + + +"; + } + private sealed record OnvifDeviceDetail( string? Manufacturer, string? Model, diff --git a/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor b/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor new file mode 100644 index 0000000..88a79b8 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor @@ -0,0 +1,319 @@ +@page "/sites/{SiteId:guid}/discoveries" +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar +@inject NavigationManager Nav + + + + Caméras détectées + + + 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. + + +
+
+ + @if (_scanning) { } + Scanner maintenant + + + + +
+ + ← Retour au site + +
+ +@if (_scanning) +{ + + Scan demandé aux agents du site. Les résultats arrivent dans quelques instants… + +} + +@if (_loading) +{ + +} +else if (_discoveries.Count == 0) +{ + + + Aucune caméra détectée + + 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. + + +} +else +{ + + + Adresse IP + Marque / Modèle + Type + Ports + Détecté le + Actions + + + + @context.IpAddress + @if (!string.IsNullOrEmpty(context.MacAddress)) + { + @context.MacAddress + } + + + @if (!string.IsNullOrEmpty(context.Vendor) || !string.IsNullOrEmpty(context.OnvifHardware)) + { + @(context.Vendor ?? "Inconnu") + @if (!string.IsNullOrEmpty(context.OnvifHardware)) + { + @context.OnvifHardware + } + } + else if (!string.IsNullOrEmpty(context.HttpServerHeader)) + { + @context.HttpServerHeader + } + else + { + Inconnue + } + + + + + + @if (context.OpenPorts.Length == 0) { - } + else + { +
+ @foreach (var port in context.OpenPorts) + { + @port + } +
+ } +
+ @context.ProbedAt.ToLocalTime().ToString("g") + + + + + + + + +
+
+} + +@* ─── Dialog de confirmation ─────────────────────────────────────── *@ + + + + Ajouter la caméra @_confirm?.IpAddress + + + @if (_confirm is not null) + { + + + @if (_confirm.StreamUrls.Length > 0) + { + + @foreach (var url in _confirm.StreamUrls) + { + @url + } + + } + else + { + + Aucune URL de flux n'a pu être construite pour cette caméra. + + } + + + @(_confirm.Vendor ?? "Marque inconnue") + @if (!string.IsNullOrEmpty(_confirm.OnvifHardware)) { · @_confirm.OnvifHardware } + @if (!string.IsNullOrEmpty(_confirm.MacAddress)) { · @_confirm.MacAddress } + + + @if (!string.IsNullOrEmpty(_confirmError)) + { + @_confirmError + } + } + + + Annuler + + @if (_confirming) { } + Ajouter la caméra + + + + +@code { + [Parameter] public Guid SiteId { get; set; } + + private List _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 + }; +} diff --git a/src/Heimdall.Web/Components/Pages/SiteDetail.razor b/src/Heimdall.Web/Components/Pages/SiteDetail.razor index 2fa6db8..8812e4e 100644 --- a/src/Heimdall.Web/Components/Pages/SiteDetail.razor +++ b/src/Heimdall.Web/Components/Pages/SiteDetail.razor @@ -81,6 +81,62 @@ else } + @* Identifiants caméras (découverte automatique) *@ + +
+ + + Identifiants caméras + + + Ajouter + +
+ + 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. + + + @if (_credentialsLoading) + { + + } + else if (_credentials.Count == 0) + { + + Aucun identifiant déclaré. La détection fonctionnera, mais les caméras + protégées ne seront pas identifiées automatiquement. + + } + else + { + + + Libellé + Utilisateur + Dernière utilisation + + + + @context.Label + @context.Username + + @(context.LastUsedAt?.ToString("g") ?? "jamais") + + + + + + + + + } +
+ @* Navigation rapide *@ Gestion @@ -100,6 +156,14 @@ else Voir les agents + + + + Détection + Caméras détectées + + } +@* ─── Ajout d'identifiant caméra ─────────────────────────────────── *@ + + + Ajouter un identifiant caméra + + + + + @if (!string.IsNullOrEmpty(_credentialError)) + { + @_credentialError + } + + + Annuler + + @if (_savingCredential) { } + Ajouter + + + + @code { [Parameter] public Guid Id { get; set; } @@ -118,6 +209,16 @@ else private DateTime _tokenExpiresAt; private string _dockerComposeSnippet = ""; + // ── Identifiants caméras ────────────────────────────────────── + private List _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() diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index 3e002d0..c7b2ce3 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -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 }); } + /// Submit network scan results from agent (API Key auth). + /// + /// 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. + /// + [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 SubmitDiscovery( + Guid id, [FromBody] IReadOnlyList 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 }); + } + /// Get agent details (JWT auth). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] [HttpGet("{id:guid}")] diff --git a/src/Heimdall.Web/Controllers/DiscoveryController.cs b/src/Heimdall.Web/Controllers/DiscoveryController.cs index 3931334..9ad7f13 100644 --- a/src/Heimdall.Web/Controllers/DiscoveryController.cs +++ b/src/Heimdall.Web/Controllers/DiscoveryController.cs @@ -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 }); } + + /// List pending discovery results for a site (agent-submitted). + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("sites/{siteId:guid}")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task 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 }); + } + + /// Reject (ignore) a pending discovery result. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost("{resultId:guid}/reject")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task 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 }); + } + + /// Ask the site's online agents to run an immediate network scan. + [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 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 }); + } } diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index bb8c5df..065354f 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -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 /// /// 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). /// - [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] + [Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")] [HttpGet("agent/{agentId:guid}")] [ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task 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) diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index d644a7b..05c59f9 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -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; + } /// Create a new site (Admin only). [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 }); } + + /// List camera credential pairs declared for this site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/credentials")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task 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 }); + } + + /// Add a camera credential pair to this site (used by agent discovery). + [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 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 }); + } + + /// Delete a camera credential pair from this site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] + [HttpDelete("{id:guid}/credentials/{credentialId:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task 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 }); + } } diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 1bfd557..c9f860e 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -314,6 +314,75 @@ public class HeimdallApiClient return await response.Content.ReadFromJsonAsync(Json); } + // ─── Site camera credentials ─────────────────────────────────── + + public async Task> GetSiteCredentialsAsync(Guid siteId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/sites/{siteId}/credentials", Json) ?? []; + } + + public async Task 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(Json); + } + + public async Task 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> GetPendingDiscoveriesAsync(Guid siteId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/discovery/sites/{siteId}", Json) ?? []; + } + + public async Task 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(Json); + } + + public async Task RejectDiscoveryAsync(Guid resultId) + { + var client = CreateClient(); + var response = await client.PostAsync($"api/discovery/{resultId}/reject", null); + return response.IsSuccessStatusCode; + } + + public async Task 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(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, diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 8973af2..9c2b4d7 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -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>(); var httpFactory = Substitute.For(); - 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() { diff --git a/tests/Heimdall.Agent.Tests/NetworkCameraScannerTests.cs b/tests/Heimdall.Agent.Tests/NetworkCameraScannerTests.cs new file mode 100644 index 0000000..c4aea34 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/NetworkCameraScannerTests.cs @@ -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>()); + scanner.ShouldNotBeNull(); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Discovery/AgentDiscoveryHandlersTests.cs b/tests/Heimdall.Application.Tests/Handlers/Discovery/AgentDiscoveryHandlersTests.cs new file mode 100644 index 0000000..7ebcfbf --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Discovery/AgentDiscoveryHandlersTests.cs @@ -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(); + var devices = new List + { + 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(), Arg.Any>(), Arg.Any()) + .Returns(ServiceResult.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(), Arg.Any>(), Arg.Any()); + } + + // ─── List pending ───────────────────────────────────────────── + + [Fact] + public async Task List_pending_should_delegate_to_discovery_service() + { + var service = Substitute.For(); + var pending = new List + { + 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(), Arg.Any()) + .Returns(ServiceResult>.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(); + service.RejectDiscoveryAsync(Arg.Any(), Arg.Any()) + .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(), Arg.Any()); + } + + // ─── 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(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor([agent1, agent2])); + + var broadcast = Substitute.For(); + 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()); + await broadcast.Received(1).NotifyAgentSettingChanged(agent2.Id, "discovery.scan.requested", "1", Arg.Any()); + } + + [Fact] + public async Task Scan_now_unknown_site_should_not_found() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([])); + context.Agents.Returns(MockDbSetHelper.CreateFor([])); + var broadcast = Substitute.For(); + var handler = new RequestSiteScanHandler(context, broadcast); + + var result = await handler.Handle(new RequestSiteScanCommand(Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs index 71778cf..0e09a7a 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -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(); + 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? appSettings = null, + List? agentSettings = null, + List? agents = null, + List? credentials = null) + { + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor(appSettings ?? [])); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor(agentSettings ?? [])); + context.Agents.Returns(MockDbSetHelper.CreateFor(agents ?? [])); + context.SiteCredentials.Returns(MockDbSetHelper.CreateFor(credentials ?? [])); + + Protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + Protector.Decrypt(Arg.Any()).Returns(c => (c.Arg() ?? "").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 { new("global.key", "global-value", "General"), @@ -19,15 +46,13 @@ public class GetEffectiveAgentConfigHandlerTests }; var agentSettings = new List { - 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(); - context.AppSettings.Returns(MockDbSetHelper.CreateFor(appSettings)); - context.AgentSettings.Returns(MockDbSetHelper.CreateFor(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 + { + 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"); + } } diff --git a/tests/Heimdall.Application.Tests/Handlers/SiteCredentials/SiteCredentialHandlersTests.cs b/tests/Heimdall.Application.Tests/Handlers/SiteCredentials/SiteCredentialHandlersTests.cs new file mode 100644 index 0000000..07d2009 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/SiteCredentials/SiteCredentialHandlersTests.cs @@ -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(); + + public SiteCredentialHandlersTests() + { + _protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + } + + private IApplicationDbContext CreateContext(params SiteCredential[] credentials) + { + var context = Substitute.For(); + 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()); + } + + [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()); + } + + [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); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs new file mode 100644 index 0000000..226a617 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs @@ -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 _dbFactory; + private readonly IOnvifProbeService _onvif = Substitute.For(); + private readonly ICredentialProtector _protector = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); + + public AgentDiscoveryServiceTests() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + _dbFactory = CreateFactory(_connection); + _protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + _protector.Decrypt(Arg.Any()).Returns(c => (c.Arg() ?? "").Replace("enc_", "")); + } + + public void Dispose() + { + _connection?.Close(); + _connection?.Dispose(); + GC.SuppressFinalize(this); + } + + private static TestDbContextFactory CreateFactory(SqliteConnection connection) + { + var opts = new DbContextOptionsBuilder() + .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(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + new StreamTesterService(Substitute.For(), Substitute.For>()), + _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(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _onvif.DidNotReceiveWithAnyArgs().ProbeDeviceServiceAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [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 opts) + : IDbContextFactory + { + private static readonly AuditInterceptor Audit = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit); + public Task CreateDbContextAsync(CancellationToken ct = default) + => Task.FromResult(new AppDbContext(opts, Audit)); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/OnvifProbeServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/OnvifProbeServiceTests.cs index fcefe04..a817711 100644 --- a/tests/Heimdall.Infrastructure.Tests/OnvifProbeServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/OnvifProbeServiceTests.cs @@ -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 = """ + + + + + Hikvision + DS-2CD2T47 + + + + """; + 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(""); + capturedBody.ShouldContain("admin"); + 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 = """ + + + + + Axis + M3085 + + + + """; + 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"); + } + + /// HttpMessageHandler stub for capturing request bodies. + private sealed class StubHttpMessageHandler(Func responder) + : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken ct) + => Task.FromResult(responder(request)); + } } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/DiscoveriesPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/DiscoveriesPageTests.cs new file mode 100644 index 0000000..1a34f46 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Components/Pages/DiscoveriesPageTests.cs @@ -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 discoveries) + { + Handler.OnGet("api/discovery/sites/", discoveries); + Handler.OnGet("api/agents/by-site/", new PagedData([Agent()], 1, 1, 50)); + } + + [Fact] + public void DiscoveriesPage_AfficheListeDesDecouvertes() + { + RouteDiscoveries([Discovery()]); + LoginAs(); + + var cut = RenderPage(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(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(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(); + 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(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(); + 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(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(); + snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "") + .ShouldContain(m => m.Contains("ignorée", StringComparison.OrdinalIgnoreCase)); + }); + } +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs index d9177b9..ab698d7 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs @@ -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()); + Handler.OnGet("api/sites/", new SiteItem( + SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10))); + LoginAs(); + + var cut = RenderPage(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 + { + 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(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("admin"); + cut.Markup.ShouldContain("nvr"); + }); + } + + [Fact] + public void SiteDetail_AjouterIdentifiant_PostEtAffiche() + { + Handler.OnGet($"api/sites/{SiteId}/credentials", new List()); + 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(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(); + 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 { 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(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(); + snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "") + .ShouldContain(m => m.Contains("supprimé", StringComparison.OrdinalIgnoreCase)); + }); + } }