fix(security): enforce resource isolation across API and hubs
This commit is contained in:
1 parent
21f0530b6c
commit
1cd4e2b4b5
39 files changed
+1081
-497
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# Lot 2 — Hubs autorisés et absence de secrets dans les diffusions
|
||||
|
||||
Suite de la PR politique API et groupes. Périmètre SEC-04/SEC-05 et raccordement SEC-03/FEAT-04, sans changement fonctionnel au pipeline ni au lot connexion/session.
|
||||
|
||||
## Diffusions
|
||||
|
||||
EventsHub autorise le site demandé puis inscrit uniquement les caméras effectivement accessibles. Le broadcaster adresse les abonnés de la caméra de l’événement, jamais tous les abonnés du site. Les GUID sont normalisés. MonitoringHub exige un droit sur le site entier ; un accès caméra partiel ne donne pas l’inventaire et les statuts des autres ressources du site. JoinAdminBroadcast exige le rôle Admin en base. ConfigHub exige la relation persistée clé → agent/site et interdit un autre agent, même dans le même site.
|
||||
|
||||
Un registre de connexions est utilisé par les trois broadcasters. Chaque envoi résout à nouveau l’identité et le droit depuis la base : retrait de groupe/site, suppression d’agent et révocation/expiration de clé sont pris en compte sans attendre une reconnexion. Les groupes SignalR ne sont pas considérés comme une preuve durable d’autorisation. Le registre est nettoyé à la déconnexion ; un redémarrage implique la reconnexion et le réabonnement habituels.
|
||||
|
||||
## Configuration et journaux
|
||||
|
||||
Seules les clés AppSetting existantes et AgentScoped sont diffusées ; les overrides de clés serveur sont refusés à l’écriture et exclus du rechargement complet, y compris les anciens overrides persistés. La commande interne de découverte conserve son contrat producteur `discovery.scan.requested = 1`, mais est transportée par un événement séparé `DiscoveryScanRequested` sans clé ni valeur ; `SettingChanged` n’accepte que des clés AgentScoped. Les credentials caméra chiffrés et la configuration des seules caméras affectées continuent à être produits côté serveur par le chargement complet existant.
|
||||
|
||||
Les contrôleurs transmettent désormais explicitement le champ AgentScoped des demandes de création/modification. Les logs de configuration ne contiennent plus de valeurs, même pour une clé inconnue ou une valeur invalide. Les journaux d’audit caméra ne sérialisent plus les URL RTSP ; les logs de capture, découverte et test de flux n’impriment plus les URL susceptibles d’inclure userinfo ou tokens. Les erreurs réseau/configuration sont consignées par type, sans message d’exception externe. Le filtre d’exception HTTP conserve le type et l’identifiant de trace, sans message susceptible de contenir une valeur sensible.
|
||||
|
||||
## Preuves et limites
|
||||
|
||||
Tests : abonnements caméra directs/groupes/sites, refus site B, monitoring partiel refusé, broadcast Admin, refus d’usurpation ConfigHub, révocation après abonnement, exclusion SMTP/S3 du push et du rechargement et rejet d’override serveur. Validation locale exécutée le 20 octobre 2026 avec .NET SDK 10.0.112 (`dotnet test <projet> --no-restore --verbosity minimal`) : Web 385/385, Agent 356/356, Application 504/504 et Infrastructure 223/223 ; aucun test ignoré. `git diff --check` passe. Un test de régression vérifie également le nettoyage des anciennes inscriptions lors d’un réabonnement après retrait des droits. Ces résultats ne couvrent pas les suites navigateur ou une infrastructure externe réelle.
|
||||
|
||||
Le registre est local à l’instance, conformément au déploiement SignalR actuel sans backplane. Un déploiement distribué devra transporter les abonnements ou diffuser sur chaque instance avec la même réautorisation ; aucune promesse de fan-out multi-instance n’est faite. La réautorisation ajoute des lectures par destinataire et doit être mesurée avant une montée en charge. Les changements de droits entre la vérification et l’envoi restent soumis à la course normale d’une requête en cours. Les anciens journaux déjà persistés ne sont pas purgés par ces changements. La sécurité des objets snapshot eux-mêmes relève du lot 4. La validation par caméra réelle et les essais SMTP/S3 réels ne sont pas remplacés par les tests locaux.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Lot 2 — Politique API et droits groupes
|
||||
|
||||
Périmètre : SEC-03, SEC-06 et FEAT-04 du rapport du 20 octobre 2026. Les hubs et SEC-05 font l’objet de la PR suivante. Aucun fichier AGENTS.md trouvé dans les ancêtres ni dans ce worktree. Aucun changement au lot connexion/session, au pipeline ou à la CI ; aucun merge ni déploiement.
|
||||
|
||||
## Contrat d’accès
|
||||
|
||||
- Le demandeur est explicitement humain ou agent. Les sujets absents, vides, contradictoires, utilisateurs inconnus et clés sans relation unique avec un agent actif sont refusés.
|
||||
- Une clé doit être active, non expirée et liée par son hash complet à exactement un agent du même site. Un simple identifiant de clé/site ne permet plus d’agir au nom d’un autre agent. Les clés génériques créées manuellement sans agent enregistré restent inutilisables comme identité agent ; la procédure d’enregistrement existante crée les deux enregistrements compatibles, sans migration.
|
||||
- Admin conserve toutes les ressources existantes ; Supervisor et Viewer conservent leurs permissions d’action existantes. L’autorisation d’une action et son périmètre sont deux conditions cumulatives.
|
||||
- Les droits caméra sont l’union de UserCameraAccess (caméra ou site entier), UserCamera, UserSite et UserGroup → GroupCameraAccess. Un grant spécifique dont SiteId ne correspond pas au site de la caméra ne donne aucun droit. Un groupe supprimé ne donne aucun droit. Aucune règle de refus prioritaire n’est introduite.
|
||||
- La même expression IQueryable sert au contrôle de détail, aux listes et aux filtres avant pagination. Les événements héritent du droit de leur caméra. Les listes de sites peuvent identifier un site contenant une caméra autorisée ; cela ne donne pas de droit sur ses autres caméras, ses agents, son inventaire ou ses credentials.
|
||||
- Les informations et opérations portant sur le site entier ou ses agents exigent un droit explicite sur tout le site (UserSite ou UserCameraAccess sans CameraId), ou Admin. Les agrégats globaux Stats sont réservés à Admin. Les listes globales d’agents sont filtrées avant pagination selon ces mêmes droits complets.
|
||||
- Un agent peut écrire uniquement pour lui-même et pour les caméras qui lui sont actuellement affectées dans son site, y compris l’ingestion d’événements, le statut et l’attachement d’un snapshot. Les autorisations d’un agent sont relues depuis la base pour chaque requête.
|
||||
- Un filtre MVC commun vérifie les ressources avant l’appel métier : Cameras, Sites, Agents, Events, Assignments, Settings, Discovery et mise à jour ciblée d’agent. Les sessions opaques de test de flux sans propriétaire persistant sont réservées à Admin. Les routes anonymes d’enregistrement restent contrôlées par leur token d’enregistrement.
|
||||
|
||||
## Personnes et véhicules
|
||||
|
||||
Les registres Person/KnownFace et Vehicle/LicensePlate sont **globaux à l’installation**, car ils ne portent pas de SiteId. Leurs routes continuent à exiger Person.Read/Write et Vehicle.Read/Write : Viewer lit, Supervisor et Admin lisent/écrivent. Une permission sur ce registre global n’ouvre aucun événement ou caméra supplémentaire ; l’historique événementiel reste filtré par caméra. Une isolation locale de ces registres demanderait un contrat métier et une migration distincts ; aucun rattachement implicite par nom ou par dernier événement n’est utilisé.
|
||||
|
||||
## Preuves et limites
|
||||
|
||||
Les tests de ce thème couvrent la matrice Admin/Supervisor/Viewer × sites A/B × direct/groupe/site/aucun, l’union des grants, le retrait d’un membre, les détails et mutations caméra, les routes agent et l’ingestion hors affectation. Les tests de rôle portent sur le périmètre ; les permissions d’action restent celles déclarées sur les contrôleurs. Un test du véritable AuthenticationHandler vérifie hash, sujet agent/site, clé non liée, expirée et agent supprimé.
|
||||
|
||||
Validation locale exécutée le 20 octobre 2026 avec .NET SDK 10.0.112 (`dotnet test <projet> --no-restore --verbosity minimal`) : Application 504/504, Infrastructure 223/223, Web 385/385 et Agent 356/356 ; aucun test ignoré. `git diff --check` passe. Les tests SQLite prouvent aussi la traduction relationnelle des expressions ; ils ne constituent pas une campagne PostgreSQL, navigateur ou matériel. Le filtre est la frontière HTTP ; les handlers internes restent utilisables par les jobs serveur de confiance. Toute nouvelle route portant une ressource doit être ajoutée explicitement à cette frontière et à sa matrice de tests.
|
||||
@@ -122,7 +122,7 @@ public sealed class CameraStreamService : IDisposable
|
||||
var session = new StreamSession(cameraId, rtspUrl, process);
|
||||
_sessions[cameraId] = session;
|
||||
|
||||
_logger.LogInformation("Stream started for camera {CameraId}: {Url}", cameraId, rtspUrl);
|
||||
_logger.LogInformation("Stream started for camera {CameraId}", cameraId);
|
||||
|
||||
// Background read loop
|
||||
_ = Task.Run(() => ReadFramesLoop(cameraId, session, ct), ct);
|
||||
@@ -131,7 +131,7 @@ public sealed class CameraStreamService : IDisposable
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start stream for camera {CameraId}", cameraId);
|
||||
_logger.LogError("Failed to start stream for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
|
||||
_throttle.Release();
|
||||
return false;
|
||||
}
|
||||
@@ -189,7 +189,7 @@ public sealed class CameraStreamService : IDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Frame read loop ended for camera {CameraId}", cameraId);
|
||||
_logger.LogWarning("Frame read loop ended for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -248,7 +248,7 @@ public sealed class CameraStreamService : IDisposable
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Cleanup error for camera {CameraId}", cameraId);
|
||||
_logger.LogWarning("Cleanup error for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -79,10 +79,12 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
.WithAutomaticReconnect(new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)))
|
||||
.Build();
|
||||
|
||||
_connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger());
|
||||
|
||||
// Listen for setting changes
|
||||
_connection.On<string, string>("SettingChanged", (key, value) =>
|
||||
{
|
||||
_logger.LogInformation("Config update received: {Key} = {Value}", key, value);
|
||||
_logger.LogInformation("Config update received: {Key}", key);
|
||||
ApplySetting(key, value);
|
||||
});
|
||||
|
||||
@@ -109,7 +111,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to rejoin agent group after reconnect");
|
||||
_logger.LogWarning("Failed to rejoin agent group after reconnect (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -119,7 +121,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
try
|
||||
{
|
||||
await _connection.StartAsync(stoppingToken);
|
||||
_logger.LogInformation("Connected to config hub at {HubUrl}", hubUrl);
|
||||
_logger.LogInformation("Connected to config hub");
|
||||
|
||||
// Join our personal config channel
|
||||
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
|
||||
@@ -136,7 +138,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Config hub connection failed, retrying in 15s...");
|
||||
_logger.LogWarning("Config hub connection failed, retrying in 15s... (error type {ErrorType})", ex.GetType().Name);
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -173,7 +175,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Ignored invalid heartbeat interval: {Value}", value);
|
||||
_logger.LogWarning("Ignored invalid heartbeat interval");
|
||||
}
|
||||
break;
|
||||
case "log.level":
|
||||
@@ -184,7 +186,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Ignored invalid log level: {Value}", value);
|
||||
_logger.LogWarning("Ignored invalid log level");
|
||||
}
|
||||
break;
|
||||
case "discovery.scan.requested":
|
||||
@@ -203,19 +205,19 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Ignored invalid autoUpdateEnabled value: {Value}", value);
|
||||
_logger.LogWarning("Ignored invalid autoUpdateEnabled value");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (RestartRequiredPrefixes.Any(p => key.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Setting {Key} = {Value} requires an agent restart to take effect (not applied live)",
|
||||
key, value);
|
||||
"Setting {Key} requires an agent restart to take effect (not applied live)",
|
||||
key);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
|
||||
_logger.LogDebug("Unknown setting {Key} (stored for future use)", key);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -243,7 +245,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to decrypt camera credential pool (kept previous pool)");
|
||||
_logger.LogWarning("Failed to decrypt camera credential pool (kept previous pool) (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +289,7 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to fetch full configuration");
|
||||
_logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogTrace(ex, "Probe error for {Ip}", ip);
|
||||
_logger.LogTrace("Probe error for {Ip} (error type {ErrorType})", ip, ex.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -271,7 +271,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "HomeKit mDNS discovery failed");
|
||||
_logger.LogWarning("HomeKit mDNS discovery failed (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
|
||||
return devices;
|
||||
@@ -348,7 +348,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "DVRIP discovery failed");
|
||||
_logger.LogWarning("DVRIP discovery failed (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
|
||||
return devices;
|
||||
@@ -515,7 +515,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "ONVIF WS-Discovery multicast failed");
|
||||
_logger.LogWarning("ONVIF WS-Discovery multicast failed (error type {ErrorType})", ex.GetType().Name);
|
||||
}
|
||||
|
||||
return devices;
|
||||
@@ -618,7 +618,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP probe failed for {Ip}:{Port}", ip, port);
|
||||
_logger.LogTrace("HTTP probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -685,7 +685,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogTrace(ex, "ONVIF probe failed for {Ip}:{Port}", ip, port);
|
||||
_logger.LogTrace("ONVIF probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -714,7 +714,7 @@ public NetworkCameraScanner(
|
||||
if (digest is not null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"ONVIF auth succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
|
||||
"ONVIF auth succeeded with credential '{Label}'", credential.Label);
|
||||
return digest with { CredentialLabel = credential.Label };
|
||||
}
|
||||
|
||||
@@ -723,7 +723,7 @@ public NetworkCameraScanner(
|
||||
if (text is not null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"ONVIF auth (PasswordText) succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
|
||||
"ONVIF auth (PasswordText) succeeded with credential '{Label}'", credential.Label);
|
||||
return text with { CredentialLabel = credential.Label };
|
||||
}
|
||||
}
|
||||
@@ -752,7 +752,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "GetDeviceInformation failed for {Url}", deviceServiceUrl);
|
||||
_logger.LogTrace("GetDeviceInformation failed for [camera endpoint]");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -832,7 +832,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "GetStreamUri failed for {Url}", deviceServiceUrl);
|
||||
_logger.LogTrace("GetStreamUri failed for [camera endpoint]");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1041,9 +1041,9 @@ public NetworkCameraScanner(
|
||||
{
|
||||
// cancelled
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception)
|
||||
{
|
||||
_logger.LogTrace(ex, "Stream test failed for {Url}", url);
|
||||
_logger.LogTrace("Stream test failed for [camera endpoint]");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -1105,7 +1105,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "RTSP probe failed for {Url}", url);
|
||||
_logger.LogTrace("RTSP probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1131,7 +1131,7 @@ public NetworkCameraScanner(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP stream probe failed for {Url}", url);
|
||||
_logger.LogTrace("HTTP stream probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1203,16 +1203,16 @@ public NetworkCameraScanner(
|
||||
{
|
||||
if (ret is 100 or 515)
|
||||
{
|
||||
_logger.LogDebug("DVRIP login OK for {Url}", url);
|
||||
_logger.LogDebug("DVRIP login OK for [camera endpoint]");
|
||||
return true;
|
||||
}
|
||||
_logger.LogDebug("DVRIP login rejected (Ret={Ret}) for {Url}", ret, url);
|
||||
_logger.LogDebug("DVRIP login rejected (Ret={Ret}) for [camera endpoint]", ret);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "DVRIP probe failed for {Url}", url);
|
||||
_logger.LogTrace("DVRIP probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1319,12 +1319,12 @@ public NetworkCameraScanner(
|
||||
var c1Read = await ReadExactWithTimeoutAsync(stream, c1, DvripTimeout, ct).ConfigureAwait(false);
|
||||
|
||||
var alive = c0[0] == 0x03 && c1Read;
|
||||
_logger.LogDebug("RTMP probe {Result} for {Url}", alive ? "OK" : "failed", url);
|
||||
_logger.LogDebug("RTMP probe {Result} for [camera endpoint]", alive ? "OK" : "failed");
|
||||
return alive;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "RTMP probe failed for {Url}", url);
|
||||
_logger.LogTrace("RTMP probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1379,12 +1379,12 @@ public NetworkCameraScanner(
|
||||
// Skip the binary preamble in the response, look for the HTTP status.
|
||||
var httpIndex = response.IndexOf("HTTP/1.", StringComparison.Ordinal);
|
||||
var alive = httpIndex >= 0 && response.AsSpan(httpIndex).StartsWith("HTTP/1.1 200", StringComparison.OrdinalIgnoreCase);
|
||||
_logger.LogDebug("Bubble probe {Result} for {Url}", alive ? "OK" : "failed", url);
|
||||
_logger.LogDebug("Bubble probe {Result} for [camera endpoint]", alive ? "OK" : "failed");
|
||||
return alive;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "Bubble probe failed for {Url}", url);
|
||||
_logger.LogTrace("Bubble probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1429,12 +1429,12 @@ public NetworkCameraScanner(
|
||||
var response = Encoding.ASCII.GetString(buffer, 0, n);
|
||||
// 200, 401 (pairing required) and 470 (auth required) all prove a live HAP service.
|
||||
var alive = response.StartsWith("HTTP/1.1", StringComparison.OrdinalIgnoreCase);
|
||||
_logger.LogDebug("HomeKit probe {Result} for {Url} ({Response})", alive ? "OK" : "failed", url, response.Split('\r')[0]);
|
||||
_logger.LogDebug("HomeKit probe {Result} for [camera endpoint] ({Response})", alive ? "OK" : "failed", response.Split('\r')[0]);
|
||||
return alive;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HomeKit probe failed for {Url}", url);
|
||||
_logger.LogTrace("HomeKit probe failed for [camera endpoint]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1515,9 +1515,9 @@ public NetworkCameraScanner(
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception)
|
||||
{
|
||||
_logger?.LogTrace(ex, "Screenshot capture failed for {Url}", url);
|
||||
_logger?.LogTrace("Screenshot capture failed for [camera endpoint]");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Heimdall.Application.Agents.Queries.GetAllAgents;
|
||||
|
||||
public record GetAllAgentsQuery(
|
||||
int Page = 1,
|
||||
int PageSize = 20) : IRequest<ServiceResult<PagedResult<AgentResponse>>>;
|
||||
int PageSize = 20, IReadOnlyCollection<Guid>? SiteIds = null) : IRequest<ServiceResult<PagedResult<AgentResponse>>>;
|
||||
|
||||
public class GetAllAgentsHandler : IRequestHandler<GetAllAgentsQuery, ServiceResult<PagedResult<AgentResponse>>>
|
||||
{
|
||||
@@ -17,7 +17,8 @@ public class GetAllAgentsHandler : IRequestHandler<GetAllAgentsQuery, ServiceRes
|
||||
|
||||
public async Task<ServiceResult<PagedResult<AgentResponse>>> Handle(GetAllAgentsQuery request, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Agents.Include(a => a.Site).OrderBy(a => a.Name);
|
||||
var query = _db.Agents.Include(a => a.Site)
|
||||
.Where(a => request.SiteIds == null || request.SiteIds.Contains(a.SiteId)).OrderBy(a => a.Name);
|
||||
|
||||
var total = await query.CountAsync(ct).ConfigureAwait(false);
|
||||
var items = await query
|
||||
|
||||
@@ -32,7 +32,7 @@ public class CreateCameraCommandHandler : IRequestHandler<CreateCameraCommand, S
|
||||
|
||||
_db.Cameras.Add(camera);
|
||||
_db.AuditLogs.Add(new AuditLog(null, "Camera.Created", "Camera", camera.Id.ToString(),
|
||||
newValue: JsonSerializer.Serialize(new { camera.Name, camera.RtspUrl, SiteId = camera.SiteId })));
|
||||
newValue: JsonSerializer.Serialize(new { camera.Name, SiteId = camera.SiteId })));
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
|
||||
@@ -29,15 +29,15 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
|
||||
if (camera is null)
|
||||
return ServiceResult<CameraResponse>.NotFound("Camera not found");
|
||||
|
||||
var oldName = camera.Name; var oldRtspUrl = camera.RtspUrl; var oldManufacturer = camera.Manufacturer; var oldModel = camera.Model;
|
||||
var oldName = camera.Name; var oldManufacturer = camera.Manufacturer; var oldModel = camera.Model;
|
||||
|
||||
camera.Update(request.Name, request.Manufacturer, request.Model, request.RtspUrl);
|
||||
if (request.Status.HasValue)
|
||||
camera.SetStatus(request.Status.Value);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "Camera.Updated", "Camera", request.Id.ToString(),
|
||||
oldValue: JsonSerializer.Serialize(new { Name = oldName, RtspUrl = oldRtspUrl, Manufacturer = oldManufacturer, Model = oldModel }),
|
||||
newValue: JsonSerializer.Serialize(new { camera.Name, camera.RtspUrl, camera.Manufacturer, camera.Model })));
|
||||
oldValue: JsonSerializer.Serialize(new { Name = oldName, Manufacturer = oldManufacturer, Model = oldModel }),
|
||||
newValue: JsonSerializer.Serialize(new { camera.Name, camera.Manufacturer, camera.Model })));
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
|
||||
@@ -19,6 +19,9 @@ public class SetAgentSettingCommandHandler : IRequestHandler<SetAgentSettingComm
|
||||
{
|
||||
var key = request.Key.Trim().ToLowerInvariant();
|
||||
|
||||
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct))
|
||||
return ServiceResult<AgentSettingDto>.Failure("Setting is not agent-scoped", 400);
|
||||
|
||||
var existing = await _db.AgentSettings
|
||||
.FirstOrDefaultAsync(s => s.AgentId == request.AgentId && s.Key == key, ct);
|
||||
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class GetEffectiveAgentConfigQueryHandler
|
||||
config[s.Key] = s.Value;
|
||||
|
||||
var agentSettings = await _db.AgentSettings
|
||||
.Where(s => s.AgentId == request.AgentId)
|
||||
.Where(s => s.AgentId == request.AgentId && _db.AppSettings.Any(a => a.Key == s.Key && a.AgentScoped))
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var s in agentSettings)
|
||||
|
||||
@@ -63,6 +63,14 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
if (!CryptographicOperations.FixedTimeEquals(incomingHash, storedHash))
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
|
||||
// A site key alone is not an agent identity. Resolve the registered binding
|
||||
// by the full verified hash, and reject ambiguous or stale bindings.
|
||||
var agents = await db.Agents.AsNoTracking()
|
||||
.Where(a => a.ApiKeyHash == apiKeyEntity.KeyHash && a.SiteId == apiKeyEntity.SiteId)
|
||||
.Select(a => a.Id).Take(2).ToListAsync(Context.RequestAborted);
|
||||
if (agents.Count != 1 || !apiKeyEntity.SiteId.HasValue)
|
||||
return AuthenticateResult.Fail("API key is not bound to one active agent");
|
||||
|
||||
apiKeyEntity.MarkUsed();
|
||||
// Persist LastUsedAt update
|
||||
await db.SaveChangesAsync();
|
||||
@@ -71,6 +79,7 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
||||
new Claim("auth_method", "api_key"),
|
||||
new Claim("agent_id", agents[0].ToString()),
|
||||
new Claim("api_key_prefix", prefix),
|
||||
};
|
||||
|
||||
|
||||
@@ -2,282 +2,46 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Enforces camera-level access control.
|
||||
/// Admins bypass all checks. Non-admins fall back from UserCameraAccess → UserCamera → UserSite.
|
||||
/// </summary>
|
||||
public class CameraAccessService : ICameraAccessService
|
||||
/// <summary>Union of explicit camera grants, legacy grants, sites and live group membership.</summary>
|
||||
public class CameraAccessService(IApplicationDbContext context) : ICameraAccessService
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
|
||||
public CameraAccessService(
|
||||
IApplicationDbContext context,
|
||||
UserManager<AppUser> userManager)
|
||||
{
|
||||
_context = context;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default)
|
||||
{
|
||||
// Admin bypass
|
||||
if (await IsAdminAsync(userId).ConfigureAwait(false))
|
||||
return true;
|
||||
=> await ApplyCameraFilter(context.Cameras, userId).AnyAsync(c => c.Id == cameraId, ct);
|
||||
|
||||
// Check UserCameraAccess: site-wide (CameraId = null) or specific camera
|
||||
var camera = await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(c => c.Id == cameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (camera is null)
|
||||
return false;
|
||||
public Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
=> ApplyCameraFilter(context.Cameras, userId).Select(c => c.Id).ToListAsync(ct);
|
||||
|
||||
var hasCameraAccess = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.AnyAsync(eca =>
|
||||
eca.UserId == userId &&
|
||||
eca.SiteId == camera.SiteId &&
|
||||
(eca.CameraId == null || eca.CameraId == cameraId),
|
||||
ct)
|
||||
.ConfigureAwait(false);
|
||||
if (hasCameraAccess)
|
||||
return true;
|
||||
public Task<List<Guid>> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default)
|
||||
=> ApplyCameraFilter(context.Cameras, userId).Where(c => c.SiteId == siteId).Select(c => c.Id).ToListAsync(ct);
|
||||
|
||||
// Check direct UserCamera entry (legacy)
|
||||
var hasDirectAccess = await _context.UserCameras
|
||||
.AsNoTracking()
|
||||
.AnyAsync(uc => uc.UserId == userId && uc.CameraId == cameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (hasDirectAccess)
|
||||
return true;
|
||||
|
||||
// Fallback: check site-level access via UserSite
|
||||
return await _context.UserSites
|
||||
.AsNoTracking()
|
||||
.AnyAsync(us => us.UserId == userId && us.SiteId == camera.SiteId, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
// Admin: return all camera IDs
|
||||
if (await IsAdminAsync(userId).ConfigureAwait(false))
|
||||
{
|
||||
return await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.Select(c => c.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Collect camera IDs from UserCameraAccess entries
|
||||
var accessCameraIds = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.Where(eca => eca.UserId == userId && eca.CameraId != null)
|
||||
.Select(eca => eca.CameraId!.Value)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Collect camera IDs from UserCameraAccess site-wide entries (CameraId = null)
|
||||
var siteWideCameraIds = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.Where(eca => eca.UserId == userId && eca.CameraId == null)
|
||||
.SelectMany(eca => _context.Cameras
|
||||
.Where(c => c.SiteId == eca.SiteId)
|
||||
.Select(c => c.Id))
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Collect camera IDs from direct UserCamera entries (legacy)
|
||||
var directCameraIds = await _context.UserCameras
|
||||
.AsNoTracking()
|
||||
.Where(uc => uc.UserId == userId)
|
||||
.Select(uc => uc.CameraId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Collect camera IDs from site-level UserSite fallback
|
||||
var siteCameraIds = await _context.UserSites
|
||||
.AsNoTracking()
|
||||
.Where(us => us.UserId == userId)
|
||||
.SelectMany(us => _context.Cameras
|
||||
.Where(c => c.SiteId == us.SiteId)
|
||||
.Select(c => c.Id))
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return accessCameraIds
|
||||
.Union(siteWideCameraIds)
|
||||
.Union(directCameraIds)
|
||||
.Union(siteCameraIds)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<Guid>> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default)
|
||||
{
|
||||
if (await IsAdminAsync(userId).ConfigureAwait(false))
|
||||
{
|
||||
return await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.Where(c => c.SiteId == siteId)
|
||||
.Select(c => c.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// UserCameraAccess: site-wide (CameraId = null) → all cameras at site
|
||||
var hasSiteWideAccess = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.AnyAsync(eca =>
|
||||
eca.UserId == userId &&
|
||||
eca.SiteId == siteId &&
|
||||
eca.CameraId == null,
|
||||
ct)
|
||||
.ConfigureAwait(false);
|
||||
if (hasSiteWideAccess)
|
||||
{
|
||||
return await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.Where(c => c.SiteId == siteId)
|
||||
.Select(c => c.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// UserCameraAccess: specific cameras at this site
|
||||
var specificCameraIds = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.Where(eca =>
|
||||
eca.UserId == userId &&
|
||||
eca.SiteId == siteId &&
|
||||
eca.CameraId != null)
|
||||
.Select(eca => eca.CameraId!.Value)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Direct UserCamera entries for cameras at this site (legacy)
|
||||
var directCameraIds = await _context.UserCameras
|
||||
.AsNoTracking()
|
||||
.Where(uc => uc.UserId == userId && uc.Camera.SiteId == siteId)
|
||||
.Select(uc => uc.CameraId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// UserSite fallback: if user has site access, they see all cameras there
|
||||
var hasSiteAccess = await _context.UserSites
|
||||
.AsNoTracking()
|
||||
.AnyAsync(us => us.UserId == userId && us.SiteId == siteId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (hasSiteAccess)
|
||||
{
|
||||
return await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.Where(c => c.SiteId == siteId)
|
||||
.Select(c => c.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return specificCameraIds.Union(directCameraIds).Distinct().ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<Guid>> GetAccessibleSiteIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
if (await IsAdminAsync(userId).ConfigureAwait(false))
|
||||
{
|
||||
return await _context.Sites
|
||||
.AsNoTracking()
|
||||
.Select(s => s.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Sites from UserCameraAccess entries
|
||||
var accessSiteIds = await _context.UserCameraAccesses
|
||||
.AsNoTracking()
|
||||
.Where(eca => eca.UserId == userId)
|
||||
.Select(eca => eca.SiteId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Sites from direct UserSite entries
|
||||
var siteIds = await _context.UserSites
|
||||
.AsNoTracking()
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Sites from UserCamera entries (cameras at a site the user has camera-level access to)
|
||||
var cameraSiteIds = await _context.UserCameras
|
||||
.AsNoTracking()
|
||||
.Where(uc => uc.UserId == userId)
|
||||
.Select(uc => uc.Camera.SiteId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return accessSiteIds.Union(siteIds).Union(cameraSiteIds).Distinct().ToList();
|
||||
if (IsAdmin(userId)) return await context.Sites.Select(s => s.Id).ToListAsync(ct);
|
||||
var cameraSites = ApplyCameraFilter(context.Cameras, userId).Select(c => c.SiteId);
|
||||
return await context.Sites.Where(s => cameraSites.Contains(s.Id) ||
|
||||
context.UserSites.Any(us => us.UserId == userId && us.SiteId == s.Id) ||
|
||||
context.UserCameraAccesses.Any(a => a.UserId == userId && a.SiteId == s.Id && a.CameraId == null))
|
||||
.Select(s => s.Id).ToListAsync(ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IQueryable<Camera> ApplyCameraFilter(IQueryable<Camera> query, Guid userId)
|
||||
{
|
||||
// Check admin status synchronously via Identity UserRoles table.
|
||||
// Admin users bypass the filter — return the query unchanged.
|
||||
var isAdmin = _context.UserRoles
|
||||
.AsNoTracking()
|
||||
.Any(ur => ur.UserId == userId &&
|
||||
_context.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
|
||||
|
||||
if (isAdmin)
|
||||
return query;
|
||||
|
||||
// Cameras from UserCameraAccess with specific CameraId
|
||||
var accessCameraIds = _context.UserCameraAccesses
|
||||
.Where(eca => eca.UserId == userId && eca.CameraId != null)
|
||||
.Select(eca => eca.CameraId!.Value);
|
||||
|
||||
// Cameras from UserCameraAccess site-wide entries (CameraId = null)
|
||||
var siteWideCameraIds = _context.UserCameraAccesses
|
||||
.Where(eca => eca.UserId == userId && eca.CameraId == null)
|
||||
.SelectMany(eca => _context.Cameras
|
||||
.Where(c => c.SiteId == eca.SiteId)
|
||||
.Select(c => c.Id));
|
||||
|
||||
// Cameras from direct UserCamera entries (legacy)
|
||||
var directCameraIds = _context.UserCameras
|
||||
.Where(uc => uc.UserId == userId)
|
||||
.Select(uc => uc.CameraId);
|
||||
|
||||
// Cameras from UserSite fallback
|
||||
var siteCameraIds = _context.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.SelectMany(us => _context.Cameras
|
||||
.Where(c => c.SiteId == us.SiteId)
|
||||
.Select(c => c.Id));
|
||||
|
||||
var allAccessibleIds = accessCameraIds
|
||||
.Union(siteWideCameraIds)
|
||||
.Union(directCameraIds)
|
||||
.Union(siteCameraIds);
|
||||
|
||||
return query.Where(c => allAccessibleIds.Contains(c.Id));
|
||||
if (userId == Guid.Empty) return query.Where(c => false);
|
||||
if (IsAdmin(userId)) return query;
|
||||
return query.Where(c =>
|
||||
context.UserCameraAccesses.Any(a => a.UserId == userId && a.SiteId == c.SiteId &&
|
||||
(a.CameraId == null || a.CameraId == c.Id)) ||
|
||||
context.UserCameras.Any(a => a.UserId == userId && a.CameraId == c.Id) ||
|
||||
context.UserSites.Any(a => a.UserId == userId && a.SiteId == c.SiteId) ||
|
||||
context.GroupCameraAccesses.Any(a => a.CameraId == c.Id &&
|
||||
context.Groups.Any(g => g.Id == a.GroupId && !g.IsDeleted) &&
|
||||
context.UserGroups.Any(m => m.UserId == userId && m.GroupId == a.GroupId)));
|
||||
}
|
||||
|
||||
private async Task<bool> IsAdminAsync(Guid userId)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString()).ConfigureAwait(false);
|
||||
return user is not null && await _userManager.IsInRoleAsync(user, AppRoles.Admin).ConfigureAwait(false);
|
||||
}
|
||||
private bool IsAdmin(Guid userId) => userId != Guid.Empty && context.UserRoles.Any(ur =>
|
||||
ur.UserId == userId && context.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
|
||||
}
|
||||
@@ -44,7 +44,7 @@ public sealed class HttpProbeService : IHttpProbeService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "HTTP probe error for {Ip}", ipAddress);
|
||||
_logger.LogWarning("HTTP probe error for {Ip} (error type {ErrorType})", ipAddress, ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ public sealed class HttpProbeService : IHttpProbeService
|
||||
// Consider 200-499 as "alive" (the device responds)
|
||||
if (statusCode >= 200 && statusCode <= 499)
|
||||
{
|
||||
_logger.LogDebug("HTTP probe hit at {Url} — {StatusCode} / {Server}", url, statusCode, serverHeader);
|
||||
_logger.LogDebug("HTTP probe hit at [camera endpoint] — {StatusCode} / {Server}", statusCode, serverHeader);
|
||||
return new HttpProbeData(port, statusCode, serverHeader);
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ public sealed class HttpProbeService : IHttpProbeService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP probe exception for {Ip}:{Port}", ipAddress, port);
|
||||
_logger.LogTrace("HTTP probe exception for {Ip}:{Port} (error type {ErrorType})", ipAddress, port, ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "ONVIF probe error for {Ip}:{Port}", ipAddress, port);
|
||||
_logger.LogWarning("ONVIF probe error for {Ip}:{Port} (error type {ErrorType})", ipAddress, port, ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -101,13 +101,12 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
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);
|
||||
_logger.LogDebug("ONVIF device service [camera endpoint] returned no device information");
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"ONVIF device service {Url} — {Name} ({Hardware})",
|
||||
deviceServiceUrl, deviceInfo.Manufacturer ?? "unknown", deviceInfo.Model ?? "unknown");
|
||||
"ONVIF device service — {Name} ({Hardware})", deviceInfo.Manufacturer ?? "unknown", deviceInfo.Model ?? "unknown");
|
||||
|
||||
return new OnvifDeviceInfo(
|
||||
DeviceServiceUrl: deviceServiceUrl,
|
||||
@@ -211,7 +210,7 @@ public sealed class OnvifProbeService : IOnvifProbeService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "Failed to get ONVIF device information from {Url}", deviceServiceUrl);
|
||||
_logger.LogTrace("Failed to get ONVIF device information from [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ public sealed partial class StreamTesterService
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
if (t.IsFaulted)
|
||||
_logger.LogError(t.Exception, "Stream test session {SessionId} crashed", sessionId);
|
||||
_logger.LogError("Stream test session {SessionId} crashed", sessionId);
|
||||
}, TaskContinuationOptions.OnlyOnFaulted);
|
||||
|
||||
return MapSession(sessionId, session);
|
||||
@@ -110,7 +110,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Stream test failed for {Url}", urlCopy);
|
||||
_logger.LogWarning("Stream test failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
session.AddResult(new Application.DTOs.StreamTestResult(
|
||||
urlCopy, [], 0, 0, 0, null, false));
|
||||
}
|
||||
@@ -130,7 +130,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Stream test session {SessionId} failed", sessionId);
|
||||
_logger.LogError("Stream test session {SessionId} failed (error type {ErrorType})", sessionId, ex.GetType().Name);
|
||||
session.MarkDone();
|
||||
}
|
||||
finally
|
||||
@@ -196,7 +196,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "Screenshot capture failed for {Url}", url);
|
||||
_logger.LogTrace("Screenshot capture failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -266,7 +266,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "ffmpeg screenshot failed for {Url}", url);
|
||||
_logger.LogTrace("ffmpeg screenshot failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -343,7 +343,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP screenshot failed for {Url}", url);
|
||||
_logger.LogTrace("HTTP screenshot failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -392,7 +392,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "RTSP test failed for {Url}", url);
|
||||
_logger.LogTrace("RTSP test failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false);
|
||||
}
|
||||
}
|
||||
@@ -425,7 +425,7 @@ public sealed partial class StreamTesterService
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogTrace(ex, "HTTP stream test failed for {Url}", url);
|
||||
_logger.LogTrace("HTTP stream test failed for [camera endpoint] (error type {ErrorType})", ex.GetType().Name);
|
||||
return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +226,7 @@ public class AgentsController : ControllerBase
|
||||
public async Task<IActionResult> ListAll(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _mediator.Send(new GetAllAgentsQuery(page, pageSize), ct);
|
||||
var result = await _mediator.Send(new GetAllAgentsQuery(page, pageSize, await GetAllowedSites(ct)), ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
@@ -245,4 +245,11 @@ public class AgentsController : ControllerBase
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
private async Task<List<Guid>> GetAllowedSites(CancellationToken ct)
|
||||
{
|
||||
var access = HttpContext.RequestServices.GetRequiredService<Heimdall.Api.Security.ResourceAccess>();
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
return requester is null ? [] : await access.FullSiteIdsAsync(requester, ct);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -89,13 +89,13 @@ public class SettingsController : ControllerBase
|
||||
public async Task<IActionResult> Create(
|
||||
[FromBody] CreateAppSettingRequest request, CancellationToken ct)
|
||||
{
|
||||
var command = new CreateAppSettingCommand(request.Key, request.Value, request.Category, request.Description, request.ValueType, request.AllowedValues);
|
||||
var command = new CreateAppSettingCommand(request.Key, request.Value, request.Category, request.Description, request.ValueType, request.AllowedValues, request.AgentScoped);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
|
||||
_logger.LogInformation("Created global setting {Key}", result.Data!.Key);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -108,13 +108,13 @@ public class SettingsController : ControllerBase
|
||||
public async Task<IActionResult> Update(
|
||||
string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
|
||||
{
|
||||
var command = new UpdateAppSettingCommand(key, request.Value, request.Description, request.Category, request.ValueType, request.AllowedValues);
|
||||
var command = new UpdateAppSettingCommand(key, request.Value, request.Description, request.Category, request.ValueType, request.AllowedValues, request.AgentScoped);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
|
||||
_logger.LogInformation("Updated global setting {Key}", result.Data!.Key);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -203,8 +203,7 @@ public class SettingsController : ControllerBase
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}",
|
||||
agentId, result.Data.Key, RedactValue(null, result.Data.Value, result.Data.Key));
|
||||
_logger.LogInformation("Set agent override Agent={AgentId}, {Key}", agentId, result.Data!.Key);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ public class ExceptionFilter : IExceptionFilter
|
||||
|
||||
public void OnException(ExceptionContext context)
|
||||
{
|
||||
_logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message);
|
||||
_logger.LogError("Unhandled exception type {ExceptionType}, trace {TraceId}",
|
||||
context.Exception.GetType().Name, context.HttpContext.TraceIdentifier);
|
||||
|
||||
var (statusCode, code, message) = context.Exception switch
|
||||
{
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Heimdall.Application.Metrics;
|
||||
@@ -13,10 +16,14 @@ namespace Heimdall.Api.Hubs;
|
||||
public class ConfigHub : Hub
|
||||
{
|
||||
private readonly ILogger<ConfigHub> _logger;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
private readonly ResourceAccess _access;
|
||||
|
||||
public ConfigHub(ILogger<ConfigHub> logger)
|
||||
public ConfigHub(ILogger<ConfigHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
|
||||
{
|
||||
_logger = logger;
|
||||
_access = access;
|
||||
_subscriptions = subscriptions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -25,18 +32,20 @@ public class ConfigHub : Hub
|
||||
/// </summary>
|
||||
public async Task JoinAgentGroup(string agentId)
|
||||
{
|
||||
if (!Guid.TryParse(agentId, out var _))
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Invalid agentId format");
|
||||
return;
|
||||
}
|
||||
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
|
||||
_logger.LogInformation("Agent {AgentId} joined config group", agentId);
|
||||
if (!Guid.TryParse(agentId, out var agent)) throw new HubException("Access denied");
|
||||
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
||||
!await _access.AgentAsync(requester, agent, Context.ConnectionAborted))
|
||||
throw new HubException("Access denied");
|
||||
_subscriptions.Join("config", Context.ConnectionId, $"agent_{agent}", Context.User!);
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agent}");
|
||||
}
|
||||
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent) throw new HubException("Access denied");
|
||||
_subscriptions.Join("config", Context.ConnectionId, "all", Context.User!);
|
||||
HeimdallMetrics.SignalRConnectionAdded();
|
||||
_logger.LogInformation("Agent connected to config hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnConnectedAsync();
|
||||
@@ -44,6 +53,7 @@ public class ConfigHub : Hub
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
_subscriptions.Disconnect("config", Context.ConnectionId);
|
||||
HeimdallMetrics.SignalRConnectionRemoved();
|
||||
_logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
@@ -59,9 +69,15 @@ public class ConfigBroadcastService : IConfigBroadcastService
|
||||
{
|
||||
private readonly IHubContext<ConfigHub> _hubContext;
|
||||
private readonly ILogger<ConfigBroadcastService> _logger;
|
||||
private readonly ResourceAccess _access;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger)
|
||||
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger, IApplicationDbContext db, ResourceAccess access, LiveSubscriptions subscriptions)
|
||||
{
|
||||
_db = db;
|
||||
_access = access;
|
||||
_subscriptions = subscriptions;
|
||||
_hubContext = hubContext;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -69,21 +85,32 @@ public class ConfigBroadcastService : IConfigBroadcastService
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting global setting change: {Key} = {Value}", key, value);
|
||||
await _hubContext.Clients.All.SendAsync("SettingChanged", key, value, ct);
|
||||
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
|
||||
_logger.LogDebug("Broadcasting global setting change: {Key}", key);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("config", "all", _access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("SettingChanged", key, value, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key} = {Value}", agentId, key, value);
|
||||
await _hubContext.Clients.Group($"agent_{agentId}").SendAsync("SettingChanged", key, value, ct);
|
||||
// Keep the existing internal producer contract, but send commands as a
|
||||
// separate, valueless event. SettingChanged always requires AgentScoped.
|
||||
if (key == "discovery.scan.requested" && value == "1")
|
||||
{
|
||||
var recipients = await _subscriptions.AuthorizedAsync("config", $"agent_{agentId}", _access,
|
||||
r => _access.AgentAsync(r, agentId, ct), ct);
|
||||
await _hubContext.Clients.Clients(recipients).SendAsync("DiscoveryScanRequested", ct);
|
||||
return;
|
||||
}
|
||||
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
|
||||
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key}", agentId, key);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("config", $"agent_{agentId}", _access, r => _access.AgentAsync(r, agentId, ct), ct)).SendAsync("SettingChanged", key, value, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogInformation("Broadcasting full config reload to all agents");
|
||||
await _hubContext.Clients.All.SendAsync("ConfigReload", ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("config", "all", _access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("ConfigReload", ct);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Metrics;
|
||||
using Heimdall.Application.Services;
|
||||
@@ -15,21 +16,30 @@ namespace Heimdall.Api.Hubs;
|
||||
public class EventsHub : Hub
|
||||
{
|
||||
private readonly ILogger<EventsHub> _logger;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
private readonly ResourceAccess _access;
|
||||
private readonly ICameraAccessService _cameras;
|
||||
|
||||
public EventsHub(ILogger<EventsHub> logger) => _logger = logger;
|
||||
public EventsHub(ILogger<EventsHub> logger, ResourceAccess access, ICameraAccessService cameras, LiveSubscriptions subscriptions)
|
||||
{ _logger = logger; _access = access; _cameras = cameras; _subscriptions = subscriptions; }
|
||||
|
||||
/// <summary>
|
||||
/// Clients call this to join a group-filtered event feed (e.g., per site).
|
||||
/// </summary>
|
||||
public async Task JoinSiteEvents(string siteId)
|
||||
{
|
||||
if (!Guid.TryParse(siteId, out _))
|
||||
if (!Guid.TryParse(siteId, out var site)) throw new HubException("Access denied");
|
||||
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
||||
if (requester is null || requester.Kind != RequesterKind.Human) throw new HubException("Access denied");
|
||||
var ids = await _cameras.GetAccessibleCameraIdsAsync(requester.Id, site, Context.ConnectionAborted);
|
||||
await LeaveSiteEvents(site.ToString());
|
||||
if (ids.Count == 0) throw new HubException("Access denied");
|
||||
Context.Items[$"events_{site}"] = ids;
|
||||
foreach (var id in ids)
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
|
||||
return;
|
||||
_subscriptions.Join("events", Context.ConnectionId, $"camera_{id}", Context.User!);
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"camera_{id}");
|
||||
}
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
|
||||
_logger.LogDebug("Client {ConnectionId} joined site events group {SiteId}", Context.ConnectionId, siteId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -37,8 +47,13 @@ public class EventsHub : Hub
|
||||
/// </summary>
|
||||
public async Task LeaveSiteEvents(string siteId)
|
||||
{
|
||||
if (!Guid.TryParse(siteId, out _)) return;
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
|
||||
if (!Guid.TryParse(siteId, out var site)) return;
|
||||
if (!Context.Items.Remove($"events_{site}", out var joined) || joined is not List<Guid> ids) return;
|
||||
foreach (var id in ids)
|
||||
{
|
||||
_subscriptions.Leave("events", Context.ConnectionId, $"camera_{id}");
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"camera_{id}");
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task OnConnectedAsync()
|
||||
@@ -50,6 +65,7 @@ public class EventsHub : Hub
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
_subscriptions.Disconnect("events", Context.ConnectionId);
|
||||
HeimdallMetrics.SignalRConnectionRemoved();
|
||||
_logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
@@ -64,9 +80,13 @@ public class EventBroadcastService : IEventBroadcastService
|
||||
{
|
||||
private readonly IHubContext<EventsHub> _hubContext;
|
||||
private readonly ILogger<EventBroadcastService> _logger;
|
||||
private readonly ResourceAccess _access;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
|
||||
public EventBroadcastService(IHubContext<EventsHub> hubContext, ILogger<EventBroadcastService> logger)
|
||||
public EventBroadcastService(IHubContext<EventsHub> hubContext, ILogger<EventBroadcastService> logger, ResourceAccess access, LiveSubscriptions subscriptions)
|
||||
{
|
||||
_access = access;
|
||||
_subscriptions = subscriptions;
|
||||
_hubContext = hubContext;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -74,6 +94,6 @@ public class EventBroadcastService : IEventBroadcastService
|
||||
public async Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting new event: {EventId} type={Type} camera={CameraId}", ev.Id, ev.Type, ev.CameraId);
|
||||
await _hubContext.Clients.Group($"site_{ev.SiteId}").SendAsync("EventCreated", ev, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("events", $"camera_{ev.CameraId}", _access, r => _access.CameraAsync(r, ev.CameraId, ct), ct)).SendAsync("EventCreated", ev, ct);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Heimdall.Api.Security;
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Metrics;
|
||||
@@ -19,18 +20,11 @@ namespace Heimdall.Api.Hubs;
|
||||
public class MonitoringHub : Hub
|
||||
{
|
||||
private readonly ILogger<MonitoringHub> _logger;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
private readonly UserManager<Heimdall.Domain.Entities.AppUser> _userManager;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
private readonly ResourceAccess _access;
|
||||
|
||||
public MonitoringHub(
|
||||
ILogger<MonitoringHub> logger,
|
||||
ICameraAccessService cameraAccess,
|
||||
UserManager<Heimdall.Domain.Entities.AppUser> userManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_cameraAccess = cameraAccess;
|
||||
_userManager = userManager;
|
||||
}
|
||||
public MonitoringHub(ILogger<MonitoringHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
|
||||
{ _logger = logger; _access = access; _subscriptions = subscriptions; }
|
||||
|
||||
/// <summary>
|
||||
/// Clients call this to join monitoring for a specific site.
|
||||
@@ -38,27 +32,13 @@ public class MonitoringHub : Hub
|
||||
/// </summary>
|
||||
public async Task JoinSiteMonitoring(string siteId)
|
||||
{
|
||||
if (!Guid.TryParse(siteId, out _))
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = GetUserId();
|
||||
if (userId.HasValue)
|
||||
{
|
||||
var accessibleCameraIds = await _cameraAccess
|
||||
.GetUserAccessibleCameraIdsAsync(userId.Value)
|
||||
.ConfigureAwait(false);
|
||||
if (accessibleCameraIds.Count == 0)
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Access denied");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
|
||||
_logger.LogDebug("Client {ConnectionId} joined monitoring group {SiteId}", Context.ConnectionId, siteId);
|
||||
if (!Guid.TryParse(siteId, out var site)) throw new HubException("Access denied");
|
||||
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
||||
if (requester is null || requester.Kind != RequesterKind.Human ||
|
||||
!await _access.SiteAsync(requester, site, Context.ConnectionAborted))
|
||||
throw new HubException("Access denied");
|
||||
_subscriptions.Join("monitoring", Context.ConnectionId, $"site_{site}", Context.User!);
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{site}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,8 +46,9 @@ public class MonitoringHub : Hub
|
||||
/// </summary>
|
||||
public async Task LeaveSiteMonitoring(string siteId)
|
||||
{
|
||||
if (!Guid.TryParse(siteId, out _)) return;
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
|
||||
if (!Guid.TryParse(siteId, out var site)) return;
|
||||
_subscriptions.Leave("monitoring", Context.ConnectionId, $"site_{site}");
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{site}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -75,6 +56,10 @@ public class MonitoringHub : Hub
|
||||
/// </summary>
|
||||
public async Task JoinAdminBroadcast()
|
||||
{
|
||||
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
||||
if (requester is null || !await _access.IsAdminAsync(requester, Context.ConnectionAborted))
|
||||
throw new HubException("Access denied");
|
||||
_subscriptions.Join("monitoring", Context.ConnectionId, "admin-broadcast", Context.User!);
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast");
|
||||
_logger.LogDebug("Client {ConnectionId} joined admin broadcast monitoring group", Context.ConnectionId);
|
||||
}
|
||||
@@ -84,6 +69,7 @@ public class MonitoringHub : Hub
|
||||
/// </summary>
|
||||
public async Task LeaveAdminBroadcast()
|
||||
{
|
||||
_subscriptions.Leave("monitoring", Context.ConnectionId, "admin-broadcast");
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "admin-broadcast");
|
||||
}
|
||||
|
||||
@@ -96,6 +82,7 @@ public class MonitoringHub : Hub
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
_subscriptions.Disconnect("monitoring", Context.ConnectionId);
|
||||
HeimdallMetrics.SignalRConnectionRemoved();
|
||||
_logger.LogDebug("Client disconnected from monitoring hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
@@ -117,9 +104,13 @@ public class MonitoringBroadcastService : IMonitoringBroadcastService
|
||||
{
|
||||
private readonly IHubContext<MonitoringHub> _hubContext;
|
||||
private readonly ILogger<MonitoringBroadcastService> _logger;
|
||||
private readonly ResourceAccess _access;
|
||||
private readonly LiveSubscriptions _subscriptions;
|
||||
|
||||
public MonitoringBroadcastService(IHubContext<MonitoringHub> hubContext, ILogger<MonitoringBroadcastService> logger)
|
||||
public MonitoringBroadcastService(IHubContext<MonitoringHub> hubContext, ILogger<MonitoringBroadcastService> logger, ResourceAccess access, LiveSubscriptions subscriptions)
|
||||
{
|
||||
_access = access;
|
||||
_subscriptions = subscriptions;
|
||||
_hubContext = hubContext;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -127,29 +118,29 @@ public class MonitoringBroadcastService : IMonitoringBroadcastService
|
||||
public async Task NotifyAgentStatusChanged(Guid siteId, Guid agentId, string status, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting agent status: Agent={AgentId} Status={Status}", agentId, status);
|
||||
await _hubContext.Clients.Group($"site_{siteId}").SendAsync("AgentStatusChanged", new { agentId, status }, ct);
|
||||
await _hubContext.Clients.Group("admin-broadcast").SendAsync("AgentStatusChanged", new { siteId, agentId, status }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", $"site_{siteId}", _access, r => _access.SiteAsync(r, siteId, ct), ct)).SendAsync("AgentStatusChanged", new { agentId, status }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", "admin-broadcast", _access, r => _access.IsAdminAsync(r, ct), ct)).SendAsync("AgentStatusChanged", new { siteId, agentId, status }, ct);
|
||||
}
|
||||
|
||||
public async Task NotifyCameraStatusChanged(Guid siteId, Guid cameraId, string status, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting camera status: Camera={CameraId} Status={Status}", cameraId, status);
|
||||
await _hubContext.Clients.Group($"site_{siteId}").SendAsync("CameraStatusChanged", new { cameraId, status }, ct);
|
||||
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraStatusChanged", new { siteId, cameraId, status }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", $"site_{siteId}", _access, r => _access.SiteAsync(r, siteId, ct), ct)).SendAsync("CameraStatusChanged", new { cameraId, status }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", "admin-broadcast", _access, r => _access.IsAdminAsync(r, ct), ct)).SendAsync("CameraStatusChanged", new { siteId, cameraId, status }, ct);
|
||||
}
|
||||
|
||||
public async Task NotifyStorageUsageUpdated(int usedPercent, long availableBytes, CancellationToken ct = default)
|
||||
{
|
||||
await _hubContext.Clients.Group("admin-broadcast").SendAsync("StorageUsageUpdated", new { usedPercent, availableBytes }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", "admin-broadcast", _access, r => _access.IsAdminAsync(r, ct), ct)).SendAsync("StorageUsageUpdated", new { usedPercent, availableBytes }, ct);
|
||||
}
|
||||
|
||||
public async Task NotifyGpuUsageUpdated(int usedPercent, float temperature, CancellationToken ct = default)
|
||||
{
|
||||
await _hubContext.Clients.Group("admin-broadcast").SendAsync("GpuUsageUpdated", new { usedPercent, temperature }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", "admin-broadcast", _access, r => _access.IsAdminAsync(r, ct), ct)).SendAsync("GpuUsageUpdated", new { usedPercent, temperature }, ct);
|
||||
}
|
||||
|
||||
public async Task NotifyJobStatusChanged(string jobName, string status, string? duration = null, CancellationToken ct = default)
|
||||
{
|
||||
await _hubContext.Clients.Group("admin-broadcast").SendAsync("JobStatusChanged", new { jobName, status, duration }, ct);
|
||||
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("monitoring", "admin-broadcast", _access, r => _access.IsAdminAsync(r, ct), ct)).SendAsync("JobStatusChanged", new { jobName, status, duration }, ct);
|
||||
}
|
||||
}
|
||||
@@ -487,8 +487,13 @@ public partial class Program
|
||||
|
||||
private static void ConfigureControllers(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddScoped<Heimdall.Api.Security.ResourceAccess>();
|
||||
builder.Services.AddSingleton<Heimdall.Api.Security.LiveSubscriptions>();
|
||||
builder.Services.AddControllers(options =>
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
|
||||
{
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>();
|
||||
options.Filters.Add<Heimdall.Api.Security.ResourceAccessFilter>();
|
||||
})
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Heimdall.Api.Security;
|
||||
|
||||
/// <summary>Connection subscriptions only. Authorization is re-evaluated from the database on every send.</summary>
|
||||
public sealed class LiveSubscriptions
|
||||
{
|
||||
private readonly ConcurrentDictionary<(string Hub, string Connection, string Channel), ClaimsPrincipal> _entries = new();
|
||||
public void Join(string hub, string connection, string channel, ClaimsPrincipal principal)
|
||||
=> _entries[(hub, connection, channel)] = principal;
|
||||
public void Leave(string hub, string connection, string channel)
|
||||
=> _entries.TryRemove((hub, connection, channel), out _);
|
||||
public void Disconnect(string hub, string connection)
|
||||
{
|
||||
foreach (var key in _entries.Keys.Where(k => k.Hub == hub && k.Connection == connection))
|
||||
_entries.TryRemove(key, out _);
|
||||
}
|
||||
public async Task<IReadOnlyList<string>> AuthorizedAsync(string hub, string channel, ResourceAccess access,
|
||||
Func<Requester, Task<bool>> authorize, CancellationToken ct = default)
|
||||
{
|
||||
var result = new List<string>();
|
||||
foreach (var (key, principal) in _entries.Where(e => e.Key.Hub == hub && e.Key.Channel == channel))
|
||||
{
|
||||
var requester = await access.ResolveAsync(principal, ct);
|
||||
if (requester is not null && await authorize(requester)) result.Add(key.Connection);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Api.Security;
|
||||
|
||||
public enum RequesterKind { Human, Agent }
|
||||
public sealed record Requester(RequesterKind Kind, Guid Id, Guid? SiteId = null);
|
||||
|
||||
/// <summary>Resolves identities from persisted state; never treats an API key ID as a user ID.</summary>
|
||||
public sealed class ResourceAccess(IApplicationDbContext db, ICameraAccessService cameras)
|
||||
{
|
||||
public async Task<Requester?> ResolveAsync(ClaimsPrincipal? principal, CancellationToken ct = default)
|
||||
{
|
||||
if (principal?.Identity?.IsAuthenticated != true) return null;
|
||||
var subjects = principal.FindAll(ClaimTypes.NameIdentifier).Concat(principal.FindAll("sub"))
|
||||
.Select(c => c.Value).Distinct(StringComparer.Ordinal).ToArray();
|
||||
if (subjects.Length != 1) return null;
|
||||
var subject = subjects[0];
|
||||
if (!Guid.TryParse(subject, out var id) || id == Guid.Empty) return null;
|
||||
if (principal.HasClaim("auth_method", "api_key"))
|
||||
{
|
||||
var key = await db.ApiKeys.AsNoTracking().SingleOrDefaultAsync(k => k.Id == id && k.Enabled, ct);
|
||||
if (key is null || key.ExpiresAt <= DateTime.UtcNow || key.SiteId is null) return null;
|
||||
var bound = await db.Agents.AsNoTracking().Where(a => a.ApiKeyHash == key.KeyHash && a.SiteId == key.SiteId)
|
||||
.Select(a => a.Id).Take(2).ToListAsync(ct);
|
||||
if (bound.Count != 1) return null;
|
||||
var claimedAgent = principal.FindFirstValue("agent_id");
|
||||
var claimedSite = principal.FindFirstValue("site_id");
|
||||
if ((claimedAgent is not null && claimedAgent != bound[0].ToString()) ||
|
||||
(claimedSite is not null && claimedSite != key.SiteId.Value.ToString())) return null;
|
||||
return new(RequesterKind.Agent, bound[0], key.SiteId);
|
||||
}
|
||||
if (!await db.Users.AnyAsync(u => u.Id == id, ct)) return null;
|
||||
return new(RequesterKind.Human, id);
|
||||
}
|
||||
|
||||
public Task<bool> IsAdminAsync(Requester r, CancellationToken ct = default) => r.Kind == RequesterKind.Human
|
||||
? db.UserRoles.AnyAsync(ur => ur.UserId == r.Id && db.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin), ct)
|
||||
: Task.FromResult(false);
|
||||
|
||||
// Full-site rights are required for site metadata, inventories, agents and site-wide changes.
|
||||
// A camera grant never confers access to the other cameras or credentials of its site.
|
||||
public async Task<bool> SiteAsync(Requester r, Guid siteId, CancellationToken ct = default)
|
||||
{
|
||||
if (!await db.Sites.AnyAsync(s => s.Id == siteId, ct)) return false;
|
||||
if (r.Kind == RequesterKind.Agent) return r.SiteId == siteId;
|
||||
return await IsAdminAsync(r, ct) || await db.UserSites.AnyAsync(s => s.UserId == r.Id && s.SiteId == siteId, ct) ||
|
||||
await db.UserCameraAccesses.AnyAsync(a => a.UserId == r.Id && a.SiteId == siteId && a.CameraId == null, ct);
|
||||
}
|
||||
|
||||
public Task<bool> CameraAsync(Requester r, Guid cameraId, CancellationToken ct = default) => r.Kind == RequesterKind.Agent
|
||||
? db.Cameras.AnyAsync(c => c.Id == cameraId && c.SiteId == r.SiteId && c.AgentId == r.Id, ct)
|
||||
: cameras.HasCameraAccessAsync(r.Id, cameraId, ct);
|
||||
|
||||
public async Task<bool> AgentAsync(Requester r, Guid agentId, CancellationToken ct = default)
|
||||
{
|
||||
if (r.Kind == RequesterKind.Agent) return r.Id == agentId;
|
||||
var site = await db.Agents.Where(a => a.Id == agentId).Select(a => (Guid?)a.SiteId).SingleOrDefaultAsync(ct);
|
||||
return site.HasValue && await SiteAsync(r, site.Value, ct);
|
||||
}
|
||||
|
||||
public async Task<bool> EventAsync(Requester r, Guid eventId, CancellationToken ct = default)
|
||||
{
|
||||
var camera = await db.CameraEvents.Where(e => e.Id == eventId).Select(e => (Guid?)e.CameraId).FirstOrDefaultAsync(ct);
|
||||
return camera.HasValue && await CameraAsync(r, camera.Value, ct);
|
||||
}
|
||||
|
||||
public async Task<List<Guid>> FullSiteIdsAsync(Requester r, CancellationToken ct = default)
|
||||
{
|
||||
if (r.Kind == RequesterKind.Agent) return r.SiteId.HasValue ? [r.SiteId.Value] : [];
|
||||
if (await IsAdminAsync(r, ct)) return await db.Sites.Select(s => s.Id).ToListAsync(ct);
|
||||
return await db.Sites.Where(s => db.UserSites.Any(u => u.UserId == r.Id && u.SiteId == s.Id) ||
|
||||
db.UserCameraAccesses.Any(a => a.UserId == r.Id && a.SiteId == s.Id && a.CameraId == null))
|
||||
.Select(s => s.Id).ToListAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Api.Security;
|
||||
|
||||
/// <summary>Resource boundary in addition to action permission policies. Runs after model binding.</summary>
|
||||
public sealed class ResourceAccessFilter(ResourceAccess access, IApplicationDbContext db) : IAsyncActionFilter
|
||||
{
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var action = (ControllerActionDescriptor)context.ActionDescriptor;
|
||||
if (context.HttpContext.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null ||
|
||||
action.ControllerName is "Auth" or "Health") { await next(); return; }
|
||||
var ct = context.HttpContext.RequestAborted;
|
||||
var r = await access.ResolveAsync(context.HttpContext.User, ct);
|
||||
if (r is null) { context.Result = new UnauthorizedResult(); return; }
|
||||
Guid? Id(string name)
|
||||
{
|
||||
foreach (var (key, value) in context.ActionArguments)
|
||||
{
|
||||
if (key.Equals(name, StringComparison.OrdinalIgnoreCase) && value is Guid id) return id;
|
||||
var property = value?.GetType().GetProperty(name, System.Reflection.BindingFlags.Public |
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase);
|
||||
if (property?.GetValue(value) is Guid nested) return nested;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async Task<bool> Camera(Guid? id) => id.HasValue && await access.CameraAsync(r, id.Value, ct);
|
||||
async Task<bool> Site(Guid? id) => id.HasValue && await access.SiteAsync(r, id.Value, ct);
|
||||
async Task<bool> Agent(Guid? id) => id.HasValue && await access.AgentAsync(r, id.Value, ct);
|
||||
async Task<bool> Event(Guid? id) => id.HasValue && await access.EventAsync(r, id.Value, ct);
|
||||
var allowed = true;
|
||||
switch (action.ControllerName)
|
||||
{
|
||||
case "Cameras":
|
||||
allowed = action.ActionName switch
|
||||
{
|
||||
"Create" => await Site(Id("SiteId")),
|
||||
"ListBySite" => true, // camera query is filtered before pagination
|
||||
_ => await Camera(Id("id"))
|
||||
};
|
||||
break;
|
||||
case "Sites":
|
||||
// A partial grant can discover its site's name via the filtered list only.
|
||||
if (Id("id") is Guid site) allowed = await Site(site);
|
||||
break;
|
||||
case "Agents":
|
||||
if (Id("id") is Guid agent) allowed = await Agent(agent);
|
||||
if (allowed && Id("cameraId") is Guid camera) allowed = await Camera(camera);
|
||||
if (allowed && Id("siteId") is Guid agentSite) allowed = await Site(agentSite);
|
||||
break;
|
||||
case "Events":
|
||||
if (Id("id") is Guid ev) allowed = await Event(ev);
|
||||
if (allowed && Id("cameraId") is Guid eventCamera) allowed = await Camera(eventCamera);
|
||||
break;
|
||||
case "Assignments":
|
||||
if (Id("cameraId") is Guid assignedCamera) allowed = await Camera(assignedCamera);
|
||||
if (allowed && Id("agentId") is Guid assignedAgent) allowed = await Agent(assignedAgent);
|
||||
if (allowed && Id("siteId") is Guid assignedSite) allowed = await Site(assignedSite);
|
||||
break;
|
||||
case "Updates":
|
||||
if (Id("id") is Guid updatedAgent) allowed = await Agent(updatedAgent);
|
||||
break;
|
||||
case "Settings":
|
||||
if (Id("agentId") is Guid configAgent) allowed = await Agent(configAgent);
|
||||
break;
|
||||
case "Discovery":
|
||||
if (Id("siteId") is Guid discoverySite) allowed = await Site(discoverySite);
|
||||
else if (Id("resultId") is Guid result)
|
||||
{
|
||||
var siteId = await db.CameraDiscoveryResults.Where(d => d.Id == result).Select(d => (Guid?)d.SiteId).FirstOrDefaultAsync(ct);
|
||||
allowed = await Site(siteId);
|
||||
}
|
||||
else if (action.ActionName is not ("SearchDatabase" or "BuildStreamUrls"))
|
||||
allowed = await access.IsAdminAsync(r, ct); // opaque probe sessions have no persisted owner
|
||||
if (allowed && Id("discoveryResultId") is Guid discoveryResult)
|
||||
{
|
||||
var resultSite = await db.CameraDiscoveryResults.Where(d => d.Id == discoveryResult)
|
||||
.Select(d => (Guid?)d.SiteId).FirstOrDefaultAsync(ct);
|
||||
allowed = resultSite.HasValue && resultSite == Id("siteId") && await Site(resultSite);
|
||||
}
|
||||
if (allowed && Id("agentId") is Guid discoveryAgent) allowed = await Agent(discoveryAgent);
|
||||
break;
|
||||
case "Stats":
|
||||
allowed = await access.IsAdminAsync(r, ct); // aggregates cover the whole installation
|
||||
break;
|
||||
}
|
||||
if (!allowed) { context.Result = new ForbidResult(); return; }
|
||||
await next();
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ public class ConfigReceiverServiceTests
|
||||
AgentCredentialStore? store = null,
|
||||
RuntimeLogLevel? runtimeLogLevel = null,
|
||||
IHttpClientFactory? httpFactory = null,
|
||||
CameraConfigStore? cameraStore = null)
|
||||
CameraConfigStore? cameraStore = null,
|
||||
ILogger<ConfigReceiverService>? logger = null)
|
||||
{
|
||||
state ??= new AgentState { AgentId = Guid.Empty };
|
||||
var options = Options.Create(new AgentOptions
|
||||
@@ -24,7 +25,7 @@ public class ConfigReceiverServiceTests
|
||||
CentralUrl = "http://localhost:5000",
|
||||
SiteToken = "test"
|
||||
});
|
||||
var logger = Substitute.For<ILogger<ConfigReceiverService>>();
|
||||
logger ??= Substitute.For<ILogger<ConfigReceiverService>>();
|
||||
httpFactory ??= Substitute.For<IHttpClientFactory>();
|
||||
var scanTrigger = new DiscoveryScanTrigger();
|
||||
runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime;
|
||||
@@ -50,6 +51,19 @@ public class ConfigReceiverServiceTests
|
||||
return (new RuntimeLogLevel(factory, options), factory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensitive_setting_values_are_never_logged_even_when_invalid_or_unknown()
|
||||
{
|
||||
var messages = new List<string>();
|
||||
using var factory = LoggerFactory.Create(b => b.SetMinimumLevel(LogLevel.Trace).AddProvider(new ListLoggerProvider(messages)));
|
||||
using var service = CreateService(logger: factory.CreateLogger<ConfigReceiverService>());
|
||||
var apply = typeof(ConfigReceiverService).GetMethod("ApplySetting", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
foreach (var key in new[] { "heartbeat.interval.seconds", "log.level", "autoUpdateEnabled", "unknown.setting", "model.api_key", "discovery.credentials" })
|
||||
apply.Invoke(service, [key, "SENSITIVE_VALUE_SENTINEL"]);
|
||||
messages.ShouldNotBeEmpty();
|
||||
string.Join("\n", messages).ShouldNotContain("SENSITIVE_VALUE_SENTINEL");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithDependencies_DoesNotThrow()
|
||||
{
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ public class GetEffectiveAgentConfigHandlerTests
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data["global.key"].ShouldBe("global-value");
|
||||
result.Data["shared.key"].ShouldBe("agent-override");
|
||||
result.Data["agent.only"].ShouldBe("agent-value");
|
||||
result.Data.ShouldNotContainKey("agent.only");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -13,6 +13,7 @@ public class SetAgentSettingHandlerTests
|
||||
{
|
||||
var agentId = Guid.NewGuid();
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>([new AppSetting("agent.key", "default")]));
|
||||
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>());
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new SetAgentSettingCommandHandler(context);
|
||||
@@ -32,6 +33,7 @@ public class SetAgentSettingHandlerTests
|
||||
var agentId = Guid.NewGuid();
|
||||
var existing = new AgentSetting(agentId, "agent.key", "old-value");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>([new AppSetting("agent.key", "default")]));
|
||||
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>([existing]));
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new SetAgentSettingCommandHandler(context);
|
||||
|
||||
@@ -25,13 +25,19 @@ public class CameraAccessServiceTests
|
||||
_context = Substitute.For<IApplicationDbContext>();
|
||||
var store = Substitute.For<IUserStore<AppUser>>();
|
||||
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
_sut = new CameraAccessService(_context, _userManager);
|
||||
_sut = new CameraAccessService(_context);
|
||||
SetupNonAdminRole();
|
||||
SetupCameras([]);
|
||||
SetupSites([]);
|
||||
_context.Groups.Returns(MockDbSetHelper.CreateFor(new List<Group>()));
|
||||
_context.UserGroups.Returns(MockDbSetHelper.CreateFor(new List<UserGroup>()));
|
||||
_context.GroupCameraAccesses.Returns(MockDbSetHelper.CreateFor(new List<GroupCameraAccess>()));
|
||||
}
|
||||
|
||||
// ── HasCameraAccessAsync ────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task HasCameraAccessAsync_AdminBypass_ReturnsTrue()
|
||||
public async Task HasCameraAccessAsync_Admin_UnknownCamera_ReturnsFalse()
|
||||
{
|
||||
// Arrange
|
||||
SetupAdminUser(_adminId);
|
||||
@@ -40,7 +46,7 @@ public class CameraAccessServiceTests
|
||||
var result = await _sut.HasCameraAccessAsync(_adminId, Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
result.ShouldBeTrue();
|
||||
result.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -450,6 +456,7 @@ public class CameraAccessServiceTests
|
||||
|
||||
private void SetupAdminUser(Guid userId)
|
||||
{
|
||||
SetupAdminRole();
|
||||
_userManager.FindByIdAsync(userId.ToString())
|
||||
.Returns(new AppUser { Id = userId });
|
||||
_userManager.IsInRoleAsync(Arg.Any<AppUser>(), AppRoles.Admin)
|
||||
@@ -458,6 +465,7 @@ public class CameraAccessServiceTests
|
||||
|
||||
private void SetupNonAdminUser(Guid userId)
|
||||
{
|
||||
SetupNonAdminRole();
|
||||
_userManager.FindByIdAsync(userId.ToString())
|
||||
.Returns(new AppUser { Id = userId });
|
||||
_userManager.IsInRoleAsync(Arg.Any<AppUser>(), AppRoles.Admin)
|
||||
|
||||
@@ -72,7 +72,7 @@ public class ExceptionFilterTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnException_LogsErrorMessage()
|
||||
public void OnException_LogsTypeAndTraceWithoutSensitiveException()
|
||||
{
|
||||
var logger = Substitute.For<ILogger<ExceptionFilter>>();
|
||||
var httpContext = new DefaultHttpContext();
|
||||
@@ -85,11 +85,13 @@ public class ExceptionFilterTests
|
||||
var filter = new ExceptionFilter(logger);
|
||||
filter.OnException(context);
|
||||
|
||||
logger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
context.Exception,
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
var call = Assert.Single(logger.ReceivedCalls(), c => c.GetMethodInfo().Name == "Log");
|
||||
var arguments = call.GetArguments();
|
||||
Assert.Equal(LogLevel.Error, arguments[0]);
|
||||
Assert.Null(arguments[3]);
|
||||
var message = arguments[2]!.ToString()!;
|
||||
Assert.Contains(nameof(InvalidOperationException), message);
|
||||
Assert.Contains(httpContext.TraceIdentifier, message);
|
||||
Assert.DoesNotContain(context.Exception.Message, message);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.8" />
|
||||
<PackageReference Include="AngleSharp" Version="1.7.0" />
|
||||
<PackageReference Include="bunit" Version="2.9.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
|
||||
@@ -1,101 +1,69 @@
|
||||
using Heimdall.Api.Hubs;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Web.Tests.Security;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Hubs;
|
||||
|
||||
public sealed class EventsHubTests : IDisposable
|
||||
public sealed class EventsHubTests
|
||||
{
|
||||
private readonly ISingleClientProxy _caller;
|
||||
private readonly IGroupManager _groups;
|
||||
private readonly ILogger<EventsHub> _logger;
|
||||
private readonly EventsHub _hub;
|
||||
|
||||
public EventsHubTests()
|
||||
[Fact]
|
||||
public async Task Rejoining_after_grant_removal_clears_previous_subscriptions()
|
||||
{
|
||||
_caller = Substitute.For<ISingleClientProxy>();
|
||||
var clients = Substitute.For<IHubCallerClients>();
|
||||
clients.Caller.Returns(_caller);
|
||||
_groups = Substitute.For<IGroupManager>();
|
||||
_logger = Substitute.For<ILogger<EventsHub>>();
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "site");
|
||||
var groups = Substitute.For<IGroupManager>();
|
||||
var context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection");
|
||||
context.User.Returns(AccessFixture.Principal(user.Id));
|
||||
context.Items.Returns(new Dictionary<object, object?>());
|
||||
var subscriptions = new LiveSubscriptions();
|
||||
using var hub = new EventsHub(NullLogger<EventsHub>.Instance, f.Access, f.Cameras, subscriptions) { Context = context, Groups = groups };
|
||||
await hub.JoinSiteEvents(f.A.Id.ToString());
|
||||
f.Db.UserSites.RemoveRange(f.Db.UserSites.Where(s => s.UserId == user.Id));
|
||||
await f.Db.SaveChangesAsync();
|
||||
|
||||
_hub = new EventsHub(_logger)
|
||||
{
|
||||
Groups = _groups,
|
||||
Clients = clients,
|
||||
Context = Substitute.For<HubCallerContext>()
|
||||
};
|
||||
_hub.Context.ConnectionId.Returns("test-connection");
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents(f.A.Id.ToString()));
|
||||
|
||||
await groups.Received().RemoveFromGroupAsync("connection", $"camera_{f.A1.Id}");
|
||||
await groups.Received().RemoveFromGroupAsync("connection", $"camera_{f.A2.Id}");
|
||||
var remaining = await subscriptions.AuthorizedAsync("events", $"camera_{f.A1.Id}", f.Access, _ => Task.FromResult(true));
|
||||
remaining.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
[Theory]
|
||||
[InlineData("direct")]
|
||||
[InlineData("group")]
|
||||
[InlineData("site")]
|
||||
public async Task Subscription_joins_only_authorized_camera_groups(string grant)
|
||||
{
|
||||
_hub.Dispose();
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, grant);
|
||||
var groups = Substitute.For<IGroupManager>();
|
||||
var context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection");
|
||||
context.User.Returns(AccessFixture.Principal(user.Id));
|
||||
using var hub = new EventsHub(NullLogger<EventsHub>.Instance, f.Access, f.Cameras, new LiveSubscriptions()) { Context = context, Groups = groups };
|
||||
await hub.JoinSiteEvents(f.A.Id.ToString("B"));
|
||||
await groups.Received().AddToGroupAsync("connection", $"camera_{f.A1.Id}");
|
||||
await groups.DidNotReceive().AddToGroupAsync("connection", $"camera_{f.B1.Id}");
|
||||
await groups.DidNotReceive().AddToGroupAsync("connection", $"site_{f.A.Id}");
|
||||
if (grant != "site") await groups.DidNotReceive().AddToGroupAsync("connection", $"camera_{f.A2.Id}");
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents(f.B.Id.ToString()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task JoinSiteEvents_WithValidGuid_AddsToGroup()
|
||||
public async Task Missing_identity_and_invalid_ids_fail_closed()
|
||||
{
|
||||
var siteId = Guid.NewGuid().ToString();
|
||||
|
||||
await _hub.JoinSiteEvents(siteId);
|
||||
|
||||
await _groups.Received(1).AddToGroupAsync("test-connection", $"site_{siteId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task JoinSiteEvents_WithInvalidGuid_SendsError_DoesNotAddToGroup()
|
||||
{
|
||||
await _hub.JoinSiteEvents("not-a-guid");
|
||||
|
||||
await _groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task JoinSiteEvents_WithEmptyString_DoesNotAddToGroup()
|
||||
{
|
||||
await _hub.JoinSiteEvents("");
|
||||
|
||||
await _groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LeaveSiteEvents_WithValidGuid_RemovesFromGroup()
|
||||
{
|
||||
var siteId = Guid.NewGuid().ToString();
|
||||
|
||||
await _hub.LeaveSiteEvents(siteId);
|
||||
|
||||
await _groups.Received(1).RemoveFromGroupAsync("test-connection", $"site_{siteId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LeaveSiteEvents_WithInvalidGuid_DoesNothing()
|
||||
{
|
||||
await _hub.LeaveSiteEvents("bad-id");
|
||||
|
||||
await _groups.DidNotReceiveWithAnyArgs().RemoveFromGroupAsync(default!, default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_DoesNotThrow()
|
||||
{
|
||||
var exception = await Record.ExceptionAsync(() => _hub.OnConnectedAsync());
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnDisconnectedAsync_WithException_DoesNotThrow()
|
||||
{
|
||||
var exception = await Record.ExceptionAsync(() => _hub.OnDisconnectedAsync(new InvalidOperationException("test")));
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnDisconnectedAsync_WithoutException_DoesNotThrow()
|
||||
{
|
||||
var exception = await Record.ExceptionAsync(() => _hub.OnDisconnectedAsync(null));
|
||||
Assert.Null(exception);
|
||||
using var f = new AccessFixture();
|
||||
var groups = Substitute.For<IGroupManager>();
|
||||
using var hub = new EventsHub(NullLogger<EventsHub>.Instance, f.Access, f.Cameras, new LiveSubscriptions()) { Context = Substitute.For<HubCallerContext>(), Groups = groups };
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents(f.A.Id.ToString()));
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents("invalid"));
|
||||
await groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Heimdall.Api.Hubs;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
|
||||
using Heimdall.Application.Settings.Commands.SetAgentSetting;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Web.Tests.Security;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Hubs;
|
||||
|
||||
public sealed class IsolationHubTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(AppRoles.Admin, "none", true, true)]
|
||||
[InlineData(AppRoles.Supervisor, "site", true, false)]
|
||||
[InlineData(AppRoles.Viewer, "site", true, false)]
|
||||
[InlineData(AppRoles.Supervisor, "group", false, false)]
|
||||
[InlineData(AppRoles.Viewer, "direct", false, false)]
|
||||
[InlineData(AppRoles.Viewer, "none", false, false)]
|
||||
public async Task Monitoring_requires_full_site_and_admin_broadcast_requires_admin(string role, string grant, bool siteAllowed, bool adminAllowed)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(role, grant);
|
||||
var context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("c"); context.User.Returns(AccessFixture.Principal(user.Id));
|
||||
using var hub = new MonitoringHub(NullLogger<MonitoringHub>.Instance, f.Access, new LiveSubscriptions())
|
||||
{ Context = context, Groups = Substitute.For<IGroupManager>() };
|
||||
if (siteAllowed) await hub.JoinSiteMonitoring(f.A.Id.ToString());
|
||||
else await Should.ThrowAsync<HubException>(() => hub.JoinSiteMonitoring(f.A.Id.ToString()));
|
||||
if (role != AppRoles.Admin) await Should.ThrowAsync<HubException>(() => hub.JoinSiteMonitoring(f.B.Id.ToString()));
|
||||
if (adminAllowed) await hub.JoinAdminBroadcast();
|
||||
else await Should.ThrowAsync<HubException>(() => hub.JoinAdminBroadcast());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Config_channel_cannot_be_impersonated_even_inside_same_site()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("c"); context.User.Returns(AccessFixture.Principal(f.KeyA.Id, true));
|
||||
using var hub = new ConfigHub(NullLogger<ConfigHub>.Instance, f.Access, new LiveSubscriptions())
|
||||
{ Context = context, Groups = Substitute.For<IGroupManager>() };
|
||||
await hub.JoinAgentGroup(f.AgentA.Id.ToString("B"));
|
||||
await hub.Groups.Received().AddToGroupAsync("c", $"agent_{f.AgentA.Id}");
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinAgentGroup(f.PeerA.Id.ToString()));
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinAgentGroup(f.AgentB.Id.ToString()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Subscriptions_reauthorize_after_group_removal_and_key_revocation()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "group");
|
||||
var subscriptions = new LiveSubscriptions();
|
||||
subscriptions.Join("events", "human", "camera", AccessFixture.Principal(user.Id));
|
||||
(await subscriptions.AuthorizedAsync("events", "camera", f.Access, r => f.Access.CameraAsync(r, f.A1.Id))).ShouldBe(["human"]);
|
||||
f.Db.UserGroups.RemoveRange(f.Db.UserGroups); await f.Db.SaveChangesAsync();
|
||||
(await subscriptions.AuthorizedAsync("events", "camera", f.Access, r => f.Access.CameraAsync(r, f.A1.Id))).ShouldBeEmpty();
|
||||
subscriptions.Join("config", "agent", "all", AccessFixture.Principal(f.KeyA.Id, true));
|
||||
f.KeyA.Disable(); await f.Db.SaveChangesAsync();
|
||||
(await subscriptions.AuthorizedAsync("config", "all", f.Access, _ => Task.FromResult(true))).ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Server_settings_are_excluded_from_push_overrides_and_full_reload()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
f.Db.AppSettings.AddRange(new AppSetting("smtp.password", "SMTP_SECRET", "email", agentScoped: false),
|
||||
new AppSetting("s3.secret", "S3_SECRET", "storage", agentScoped: false),
|
||||
new AppSetting("agent.heartbeat", "30", "agent", agentScoped: true));
|
||||
// An old persisted override must not bypass the current scope.
|
||||
f.Db.AgentSettings.Add(new(f.AgentA.Id, "smtp.password", "OLD_SECRET"));
|
||||
await f.Db.SaveChangesAsync();
|
||||
var subscriptions = new LiveSubscriptions();
|
||||
subscriptions.Join("config", "c", "all", AccessFixture.Principal(f.KeyA.Id, true));
|
||||
var hubContext = Substitute.For<IHubContext<ConfigHub>>();
|
||||
var clients = Substitute.For<IHubClients>(); hubContext.Clients.Returns(clients);
|
||||
clients.Clients(Arg.Any<IReadOnlyList<string>>()).Returns(Substitute.For<IClientProxy>());
|
||||
var logger = new CaptureLogger<ConfigBroadcastService>();
|
||||
var broadcast = new ConfigBroadcastService(hubContext, logger, f.Db, f.Access, subscriptions);
|
||||
await broadcast.NotifyGlobalSettingChanged("smtp.password", "SMTP_SECRET");
|
||||
await broadcast.NotifyAgentSettingChanged(f.AgentA.Id, "s3.secret", "S3_SECRET");
|
||||
clients.DidNotReceiveWithAnyArgs().Clients(default!);
|
||||
var result = await new GetEffectiveAgentConfigQueryHandler(f.Db, Substitute.For<ICredentialProtector>())
|
||||
.Handle(new(f.AgentA.Id), default);
|
||||
result.Data!.ShouldNotContainKey("smtp.password"); result.Data!.ShouldNotContainKey("s3.secret");
|
||||
result.Data!["agent.heartbeat"].ShouldBe("30");
|
||||
(await new SetAgentSettingCommandHandler(f.Db).Handle(new(f.AgentA.Id, "smtp.password", "secret"), default)).IsSuccess.ShouldBeFalse();
|
||||
await broadcast.NotifyGlobalSettingChanged("agent.heartbeat", "45");
|
||||
clients.Received().Clients(Arg.Is<IReadOnlyList<string>>(ids => ids != null && ids.Count == 1 && ids[0] == "c"));
|
||||
var logs = string.Join("\n", logger.Messages);
|
||||
logs.ShouldNotContain("SMTP_SECRET"); logs.ShouldNotContain("S3_SECRET"); logs.ShouldNotContain("45");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Data.Interceptors;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Infrastructure.Services;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class AccessFixture : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection = new("DataSource=:memory:");
|
||||
public AppDbContext Db { get; }
|
||||
public CameraAccessService Cameras { get; }
|
||||
public ResourceAccess Access { get; }
|
||||
public Site A { get; } = new("A");
|
||||
public Site B { get; } = new("B");
|
||||
public Camera A1 { get; }
|
||||
public Camera A2 { get; }
|
||||
public Camera B1 { get; }
|
||||
public Agent AgentA { get; }
|
||||
public Agent PeerA { get; }
|
||||
public Agent AgentB { get; }
|
||||
public ApiKey KeyA { get; }
|
||||
public Group Group { get; } = new("Operators", null);
|
||||
|
||||
public AccessFixture()
|
||||
{
|
||||
_connection.Open();
|
||||
_connection.CreateFunction("NOW", () => DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
|
||||
Db = new(new DbContextOptionsBuilder<AppDbContext>().UseSqlite(_connection).Options, new AuditInterceptor());
|
||||
Db.Database.EnsureCreated();
|
||||
AgentA = new(A.Id, "a", "a", "1");
|
||||
PeerA = new(A.Id, "peer", "peer", "1");
|
||||
AgentB = new(B.Id, "b", "b", "1");
|
||||
var (_, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey();
|
||||
AgentA.Register(hash, prefix);
|
||||
KeyA = new(hash, prefix, A.Id);
|
||||
A1 = new(A.Id, "a1"); A1.AssignAgent(AgentA.Id);
|
||||
A2 = new(A.Id, "a2"); A2.AssignAgent(PeerA.Id);
|
||||
B1 = new(B.Id, "b1"); B1.AssignAgent(AgentB.Id);
|
||||
Db.AddRange(A, B, AgentA, PeerA, AgentB, KeyA, A1, A2, B1, Group);
|
||||
Db.SaveChanges();
|
||||
Cameras = new(Db);
|
||||
Access = new(Db, Cameras);
|
||||
}
|
||||
|
||||
public AppUser User(string role, string grant)
|
||||
{
|
||||
var user = new AppUser { Id = Guid.NewGuid(), UserName = Guid.NewGuid().ToString() };
|
||||
var entity = Db.Roles.FirstOrDefault(r => r.Name == role) ?? new AppRole { Id = Guid.NewGuid(), Name = role, NormalizedName = role.ToUpperInvariant() };
|
||||
if (Db.Entry(entity).State == EntityState.Detached) Db.Roles.Add(entity);
|
||||
Db.Users.Add(user);
|
||||
Db.UserRoles.Add(new IdentityUserRole<Guid> { UserId = user.Id, RoleId = entity.Id });
|
||||
switch (grant)
|
||||
{
|
||||
case "direct": Db.UserCameraAccesses.Add(new(user.Id, A.Id, A1.Id)); break;
|
||||
case "legacy": Db.UserCameras.Add(new(user.Id, A1.Id)); break;
|
||||
case "site": Db.UserSites.Add(new(user.Id, A.Id)); break;
|
||||
case "group":
|
||||
Db.UserGroups.Add(new(user.Id, Group.Id));
|
||||
if (!Db.GroupCameraAccesses.Any(g => g.GroupId == Group.Id && g.CameraId == A1.Id))
|
||||
Db.GroupCameraAccesses.Add(new(Group.Id, A1.Id));
|
||||
break;
|
||||
}
|
||||
Db.SaveChanges();
|
||||
return user;
|
||||
}
|
||||
|
||||
public static ClaimsPrincipal Principal(Guid id, bool agent = false) => new(new ClaimsIdentity(
|
||||
agent ? [new Claim(ClaimTypes.NameIdentifier, id.ToString()), new Claim("auth_method", "api_key")]
|
||||
: [new Claim(ClaimTypes.NameIdentifier, id.ToString())], "test"));
|
||||
|
||||
public void Dispose() { Db.Dispose(); _connection.Dispose(); }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class ApiKeyIdentityTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Real_handler_emits_server_resolved_agent_and_rejects_unbound_expired_deleted_keys()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var (plain, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey();
|
||||
var key = new ApiKey(hash, prefix, f.A.Id);
|
||||
f.Db.ApiKeys.Add(key); await f.Db.SaveChangesAsync();
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging(); services.AddSingleton(f.Db);
|
||||
services.AddAuthentication("ApiKey").AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", _ => { });
|
||||
using var provider = services.BuildServiceProvider();
|
||||
async Task<AuthenticateResult> Authenticate(string input)
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
var context = new DefaultHttpContext { RequestServices = scope.ServiceProvider };
|
||||
context.Request.Headers["X-API-Key"] = input;
|
||||
return await context.AuthenticateAsync("ApiKey");
|
||||
}
|
||||
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
|
||||
f.PeerA.Register(hash, prefix); await f.Db.SaveChangesAsync();
|
||||
var success = await Authenticate(plain);
|
||||
success.Succeeded.ShouldBeTrue();
|
||||
success.Principal!.FindFirst("agent_id")!.Value.ShouldBe(f.PeerA.Id.ToString());
|
||||
success.Principal.FindFirst("site_id")!.Value.ShouldBe(f.A.Id.ToString());
|
||||
(await Authenticate(plain[..^1] + (plain[^1] == '0' ? '1' : '0'))).Succeeded.ShouldBeFalse();
|
||||
key.SetExpiry(DateTime.UtcNow.AddMinutes(-1)); await f.Db.SaveChangesAsync();
|
||||
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
|
||||
key.SetExpiry(DateTime.UtcNow.AddMinutes(1)); f.PeerA.SoftDelete(); await f.Db.SaveChangesAsync();
|
||||
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Heimdall.Api.Controllers;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.Cameras.Queries.GetCamera;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class HttpIsolationTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(AppRoles.Admin, "none")]
|
||||
[InlineData(AppRoles.Supervisor, "group")]
|
||||
[InlineData(AppRoles.Viewer, "direct")]
|
||||
[InlineData(AppRoles.Viewer, "none")]
|
||||
public async Task Real_http_pipeline_combines_permissions_and_resource_scope(string role, string grant)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(role, grant);
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Testing" });
|
||||
builder.Logging.ClearProviders();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
builder.Services.AddSingleton<IApplicationDbContext>(f.Db);
|
||||
builder.Services.AddSingleton(f.Db);
|
||||
builder.Services.AddSingleton<ICameraAccessService>(f.Cameras);
|
||||
builder.Services.AddScoped<ResourceAccess>();
|
||||
builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining<GetCameraQuery>());
|
||||
builder.Services.AddControllers(o => o.Filters.Add<ResourceAccessFilter>()).AddApplicationPart(typeof(CamerasController).Assembly);
|
||||
builder.Services.AddAuthentication("JwtBearer")
|
||||
.AddScheme<AuthenticationSchemeOptions, TestHumanHandler>("JwtBearer", _ => { })
|
||||
.AddScheme<AuthenticationSchemeOptions, TestHumanHandler>("Cookies", _ => { })
|
||||
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", _ => { });
|
||||
builder.Services.AddAuthorization(o =>
|
||||
{
|
||||
foreach (var permission in AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct())
|
||||
o.AddPolicy(permission, p => p.RequireClaim("permission", permission));
|
||||
});
|
||||
builder.Services.AddRateLimiter(o => o.AddPolicy("Api", _ => System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("tests")));
|
||||
await using var app = builder.Build();
|
||||
app.UseRouting(); app.UseRateLimiter(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();
|
||||
await app.StartAsync();
|
||||
using var client = new HttpClient { BaseAddress = new(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single()) };
|
||||
client.DefaultRequestHeaders.Add("X-Test-User", user.Id.ToString());
|
||||
client.DefaultRequestHeaders.Add("X-Test-Role", role);
|
||||
var canReadA = role == AppRoles.Admin || grant != "none";
|
||||
(await client.GetAsync($"api/cameras/{f.A1.Id}")).StatusCode.ShouldBe(canReadA ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
(await client.GetAsync($"api/cameras/{f.B1.Id}")).StatusCode.ShouldBe(role == AppRoles.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
var mutation = await client.PostAsync($"api/cameras/{f.A1.Id}/toggle-status", null);
|
||||
mutation.StatusCode.ShouldBe(canReadA && role != AppRoles.Viewer ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
client.DefaultRequestHeaders.Remove("X-Test-User");
|
||||
(await client.GetAsync($"api/cameras/{f.A1.Id}")).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// Only the credential verification step is replaced. MVC, policies, resource filter,
|
||||
// database and query/command handlers are exercised through an actual HTTP listener.
|
||||
public sealed class TestHumanHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (Scheme.Name != "JwtBearer" || !Guid.TryParse(Request.Headers["X-Test-User"], out var id))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
var role = Request.Headers["X-Test-Role"].ToString();
|
||||
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, id.ToString()) };
|
||||
claims.AddRange(AppPermissions.RolePermissions[role].Select(p => new Claim("permission", p)));
|
||||
return Task.FromResult(AuthenticateResult.Success(new(new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)), Scheme.Name)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class ResourceAccessFilterTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Cameras", "GetById")]
|
||||
[InlineData("Cameras", "Update")]
|
||||
[InlineData("Cameras", "Delete")]
|
||||
[InlineData("Cameras", "ToggleStatus")]
|
||||
public async Task Every_camera_detail_or_mutation_is_checked_before_dispatch(string controller, string action)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Supervisor, "group");
|
||||
(await Run(f, controller, action, AccessFixture.Principal(user.Id), new() { ["id"] = f.A1.Id })).ShouldBeNull();
|
||||
(await Run(f, controller, action, AccessFixture.Principal(user.Id), new() { ["id"] = f.A2.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, controller, action, AccessFixture.Principal(user.Id), new() { ["id"] = f.B1.Id })).ShouldBeOfType<ForbidResult>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Heartbeat")]
|
||||
[InlineData("SubmitDiscovery")]
|
||||
[InlineData("SubmitLogs")]
|
||||
[InlineData("ReportCameraStatus")]
|
||||
public async Task Agent_routes_reject_cross_agent_mutations(string action)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var principal = AccessFixture.Principal(f.KeyA.Id, true);
|
||||
(await Run(f, "Agents", action, principal, new() { ["id"] = f.AgentA.Id, ["cameraId"] = f.A1.Id })).ShouldBeNull();
|
||||
(await Run(f, "Agents", action, principal, new() { ["id"] = f.PeerA.Id, ["cameraId"] = f.A2.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Agents", action, principal, new() { ["id"] = f.AgentB.Id, ["cameraId"] = f.B1.Id })).ShouldBeOfType<ForbidResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Agent_ingestion_checks_body_camera_and_snapshot_event()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var principal = AccessFixture.Principal(f.KeyA.Id, true);
|
||||
(await Run(f, "Events", "Create", principal, new() { ["request"] = new { CameraId = f.A2.Id } })).ShouldBeOfType<ForbidResult>();
|
||||
var ev = new Heimdall.Domain.Entities.CameraEvent(f.B1.Id, Heimdall.Domain.Enums.EventType.MotionDetected, .9);
|
||||
f.Db.CameraEvents.Add(ev); await f.Db.SaveChangesAsync();
|
||||
(await Run(f, "Events", "AttachSnapshot", principal, new() { ["id"] = ev.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Cameras", "GetById", new(), new() { ["id"] = f.A1.Id })).ShouldBeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
private static async Task<IActionResult?> Run(AccessFixture f, string controller, string action,
|
||||
System.Security.Claims.ClaimsPrincipal principal, Dictionary<string, object?> arguments)
|
||||
{
|
||||
var descriptor = new ControllerActionDescriptor { ControllerName = controller, ActionName = action };
|
||||
var context = new ActionContext(new DefaultHttpContext { User = principal }, new RouteData(), descriptor, new ModelStateDictionary());
|
||||
var executing = new ActionExecutingContext(context, [], arguments, new object());
|
||||
var called = false;
|
||||
await new ResourceAccessFilter(f.Access, f.Db).OnActionExecutionAsync(executing, () =>
|
||||
{
|
||||
called = true;
|
||||
return Task.FromResult(new ActionExecutedContext(context, [], new object()));
|
||||
});
|
||||
called.ShouldBe(executing.Result is null);
|
||||
return executing.Result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class ResourceAccessTests
|
||||
{
|
||||
public static TheoryData<string, string> Matrix => new()
|
||||
{
|
||||
{ AppRoles.Admin, "none" },
|
||||
{ AppRoles.Supervisor, "none" }, { AppRoles.Supervisor, "direct" }, { AppRoles.Supervisor, "group" }, { AppRoles.Supervisor, "site" },
|
||||
{ AppRoles.Viewer, "none" }, { AppRoles.Viewer, "direct" }, { AppRoles.Viewer, "group" }, { AppRoles.Viewer, "site" }, { AppRoles.Viewer, "legacy" }
|
||||
};
|
||||
|
||||
[Theory, MemberData(nameof(Matrix))]
|
||||
public async Task All_entry_points_agree_on_camera_scope(string role, string grant)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(role, grant);
|
||||
var r = (await f.Access.ResolveAsync(AccessFixture.Principal(user.Id)))!;
|
||||
var admin = role == AppRoles.Admin;
|
||||
var expected = admin ? new[] { f.A1.Id, f.A2.Id, f.B1.Id }
|
||||
: grant == "none" ? [] : grant == "site" ? [f.A1.Id, f.A2.Id] : new[] { f.A1.Id };
|
||||
(await f.Cameras.GetUserAccessibleCameraIdsAsync(user.Id)).Order().ShouldBe(expected.Order());
|
||||
(await f.Cameras.GetAccessibleCameraIdsAsync(user.Id, f.A.Id)).Order().ShouldBe(expected.Where(id => id != f.B1.Id).Order());
|
||||
f.Cameras.ApplyCameraFilter(f.Db.Cameras, user.Id).Select(c => c.Id).ToArray().Order().ShouldBe(expected.Order());
|
||||
foreach (var camera in new[] { f.A1, f.A2, f.B1 })
|
||||
{
|
||||
(await f.Access.CameraAsync(r, camera.Id)).ShouldBe(expected.Contains(camera.Id));
|
||||
var ev = new CameraEvent(camera.Id, EventType.MotionDetected, .9);
|
||||
f.Db.CameraEvents.Add(ev); await f.Db.SaveChangesAsync();
|
||||
(await f.Access.EventAsync(r, ev.Id)).ShouldBe(expected.Contains(camera.Id));
|
||||
}
|
||||
(await f.Access.SiteAsync(r, f.A.Id)).ShouldBe(admin || grant == "site");
|
||||
(await f.Access.SiteAsync(r, f.B.Id)).ShouldBe(admin);
|
||||
(await f.Access.AgentAsync(r, f.AgentA.Id)).ShouldBe(admin || grant == "site");
|
||||
(await f.Access.AgentAsync(r, f.AgentB.Id)).ShouldBe(admin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Group_membership_revocation_and_union_are_live()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "group");
|
||||
f.Db.UserCameras.Add(new(user.Id, f.B1.Id));
|
||||
await f.Db.SaveChangesAsync();
|
||||
(await f.Cameras.GetUserAccessibleCameraIdsAsync(user.Id)).Count.ShouldBe(2);
|
||||
f.Db.UserGroups.RemoveRange(f.Db.UserGroups);
|
||||
await f.Db.SaveChangesAsync();
|
||||
(await f.Cameras.HasCameraAccessAsync(user.Id, f.A1.Id)).ShouldBeFalse();
|
||||
(await f.Cameras.HasCameraAccessAsync(user.Id, f.B1.Id)).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Agent_is_bound_to_one_key_and_only_assigned_cameras()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var principal = AccessFixture.Principal(f.KeyA.Id, true);
|
||||
var r = (await f.Access.ResolveAsync(principal))!;
|
||||
r.Kind.ShouldBe(RequesterKind.Agent); r.Id.ShouldBe(f.AgentA.Id);
|
||||
(await f.Access.AgentAsync(r, f.AgentA.Id)).ShouldBeTrue();
|
||||
(await f.Access.AgentAsync(r, f.PeerA.Id)).ShouldBeFalse();
|
||||
(await f.Access.AgentAsync(r, f.AgentB.Id)).ShouldBeFalse();
|
||||
(await f.Access.CameraAsync(r, f.A1.Id)).ShouldBeTrue();
|
||||
(await f.Access.CameraAsync(r, f.A2.Id)).ShouldBeFalse();
|
||||
(await f.Access.CameraAsync(r, f.B1.Id)).ShouldBeFalse();
|
||||
(await f.Access.IsAdminAsync(r)).ShouldBeFalse();
|
||||
f.KeyA.Disable(); await f.Db.SaveChangesAsync();
|
||||
(await f.Access.ResolveAsync(principal)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Absent_unbound_or_ambiguous_identities_are_rejected()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
(await f.Access.ResolveAsync(null)).ShouldBeNull();
|
||||
(await f.Access.ResolveAsync(AccessFixture.Principal(Guid.NewGuid()))).ShouldBeNull();
|
||||
var key = new ApiKey("unbound", "unbound1", f.A.Id);
|
||||
f.Db.ApiKeys.Add(key); await f.Db.SaveChangesAsync();
|
||||
(await f.Access.ResolveAsync(AccessFixture.Principal(key.Id, true))).ShouldBeNull();
|
||||
f.PeerA.Register(f.KeyA.KeyHash, f.KeyA.KeyPrefix); await f.Db.SaveChangesAsync();
|
||||
(await f.Access.ResolveAsync(AccessFixture.Principal(f.KeyA.Id, true))).ShouldBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Heimdall.Application.Cameras.Commands.CreateCamera;
|
||||
using Heimdall.Application.Cameras.Commands.UpdateCamera;
|
||||
using Heimdall.Api.Filters;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class SensitiveAuditTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Camera_creation_and_update_audits_do_not_persist_stream_credentials()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
const string original = "rtsp://user:ORIGINAL_SECRET@camera/stream?token=PRIVATE_TOKEN";
|
||||
const string replacement = "rtsp://user:REPLACEMENT_SECRET@camera/stream";
|
||||
var created = await new CreateCameraCommandHandler(f.Db).Handle(new(f.A.Id, "camera", original, null, null), default);
|
||||
created.IsSuccess.ShouldBeTrue();
|
||||
var updated = await new UpdateCameraCommandHandler(f.Db).Handle(new(created.Data!.Id, "renamed", replacement, null), default);
|
||||
updated.IsSuccess.ShouldBeTrue();
|
||||
var audit = string.Join("\n", f.Db.AuditLogs.Select(a => (a.OldValue ?? "") + (a.NewValue ?? "")));
|
||||
audit.ShouldNotContain("SECRET"); audit.ShouldNotContain("PRIVATE_TOKEN"); audit.ShouldNotContain("rtsp://");
|
||||
audit.ShouldContain("renamed");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Http_exception_logs_keep_trace_without_sensitive_exception_content()
|
||||
{
|
||||
var logger = new CaptureLogger<ExceptionFilter>();
|
||||
var context = new ExceptionContext(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), [])
|
||||
{ Exception = new InvalidOperationException("smtp password=SERVER_SECRET") };
|
||||
new ExceptionFilter(logger).OnException(context);
|
||||
string.Join("\n", logger.Messages).ShouldNotContain("SERVER_SECRET");
|
||||
string.Join("\n", logger.Messages).ShouldContain(nameof(InvalidOperationException));
|
||||
context.ExceptionHandled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CaptureLogger<T> : ILogger<T>
|
||||
{
|
||||
public List<string> Messages { get; } = [];
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
=> Messages.Add(formatter(state, exception) + exception?.ToString());
|
||||
}
|
||||
Reference in new issue
Block a user