Merge pull request 'fix(security): isolate API resources and SignalR broadcasts' (#4) from audit-access-isolation into main

Validation combinée après exploitation #2 : 251 tests Infrastructure et 385 Web réussis, aucun échec ni ignoré. Auth/session #5 suit avec revalidation des connexions SignalR.
This commit was merged in pull request #4.
This commit is contained in:
arnaud.dartois committed 2026-10-20 07:23:27 +02:00
commit 8b87bbe760
39 files changed
+1081 -497

No files matched your search

@@ -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);
@@ -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);
}
+2 -1
View File
@@ -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
{
+42 -15
View File
@@ -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);
}
}
+30 -10
View File
@@ -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);
}
}
+33 -42
View File
@@ -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);
}
}
+6 -1
View File
@@ -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();
}
}