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

@@ -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);
}
}