From b97d3bec110c3df5cce0f1b5004da2c2afea3b05 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 27 Aug 2026 20:28:41 +0200 Subject: [PATCH] =?UTF-8?q?feat(security):=20enforcement=20=E2=80=94=20fil?= =?UTF-8?q?trage=20cam=C3=A9ra=20dans=20les=20endpoints=20sensibles=20(#17?= =?UTF-8?q?5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CreateCamera/CreateCameraCommand.cs | 1 + .../DeleteCamera/DeleteCameraCommand.cs | 1 + .../ToggleCameraStatusCommand.cs | 1 + .../UpdateCamera/UpdateCameraCommand.cs | 1 + .../Common/IApplicationDbContext.cs | 1 + .../Queries/GetEvent/GetEventHandler.cs | 26 ++++-- .../Events/Queries/GetEvent/GetEventQuery.cs | 2 +- .../Queries/GetEvents/GetEventsHandler.cs | 18 +++- .../Queries/GetEvents/GetEventsQuery.cs | 3 +- .../GetRecentByCameraHandler.cs | 19 +++- .../GetRecentByCameraQuery.cs | 2 +- .../Services/ICameraAccessService.cs | 23 +++++ .../Commands/DeleteSite/DeleteSiteHandler.cs | 1 + .../Commands/UpdateSite/UpdateSiteCommand.cs | 1 + src/Heimdall.Domain/Entities/UserCamera.cs | 23 +++++ .../Data/AppDbContext.cs | 2 + .../Configurations/UserCameraConfiguration.cs | 28 ++++++ .../DependencyInjection.cs | 3 + .../Services/CameraAccessService.cs | 88 +++++++++++++++++++ .../Controllers/EventsController.cs | 19 ++-- src/Heimdall.Web/Hubs/MonitoringHub.cs | 39 +++++++- .../Handlers/Events/GetEventHandlerTests.cs | 9 +- .../Handlers/Events/GetEventsHandlerTests.cs | 16 +++- .../Events/GetRecentByCameraHandlerTests.cs | 11 ++- 24 files changed, 313 insertions(+), 25 deletions(-) create mode 100644 src/Heimdall.Application/Services/ICameraAccessService.cs create mode 100644 src/Heimdall.Domain/Entities/UserCamera.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/UserCameraConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Services/CameraAccessService.cs diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs index ebfe737..e71fa0a 100644 --- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs @@ -5,6 +5,7 @@ using Heimdall.Domain.Entities; using MediatR; namespace Heimdall.Application.Cameras.Commands.CreateCamera; + public record CreateCameraCommand( Guid SiteId, string Name, diff --git a/src/Heimdall.Application/Cameras/Commands/DeleteCamera/DeleteCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/DeleteCamera/DeleteCameraCommand.cs index 8608dab..1afe7aa 100644 --- a/src/Heimdall.Application/Cameras/Commands/DeleteCamera/DeleteCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/DeleteCamera/DeleteCameraCommand.cs @@ -3,6 +3,7 @@ using Heimdall.Domain.Entities; using MediatR; namespace Heimdall.Application.Cameras.Commands.DeleteCamera; + public record DeleteCameraCommand(Guid Id) : IRequest; public class DeleteCameraCommandHandler : IRequestHandler { diff --git a/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs b/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs index ffe2019..6ec21e2 100644 --- a/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs @@ -4,6 +4,7 @@ using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using MediatR; namespace Heimdall.Application.Cameras.Commands.ToggleCameraStatus; + public record ToggleCameraStatusCommand(Guid Id) : IRequest>; public class ToggleCameraStatusCommandHandler : IRequestHandler> { diff --git a/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs index 8d6ff07..15c1769 100644 --- a/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs @@ -5,6 +5,7 @@ using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using MediatR; namespace Heimdall.Application.Cameras.Commands.UpdateCamera; + public record UpdateCameraCommand( Guid Id, string Name, diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index da1a99c..113020e 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -35,6 +35,7 @@ public interface IApplicationDbContext DbSet StoragePolicies { get; } DbSet UserGroups { get; } DbSet UserRecoveryCodes { get; } + DbSet UserCameras { get; } DbSet UserSites { get; } DbSet Vehicles { get; } Task SaveChangesAsync(CancellationToken cancellationToken); diff --git a/src/Heimdall.Application/Events/Queries/GetEvent/GetEventHandler.cs b/src/Heimdall.Application/Events/Queries/GetEvent/GetEventHandler.cs index 8e1151f..dd0cedc 100644 --- a/src/Heimdall.Application/Events/Queries/GetEvent/GetEventHandler.cs +++ b/src/Heimdall.Application/Events/Queries/GetEvent/GetEventHandler.cs @@ -1,18 +1,23 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Queries.GetEvent; - #pragma warning disable CA1711 public class GetEventHandler : IRequestHandler> #pragma warning restore CA1711 { private readonly IApplicationDbContext _context; + private readonly ICameraAccessService _cameraAccess; - public GetEventHandler(IApplicationDbContext context) => _context = context; + public GetEventHandler(IApplicationDbContext context, ICameraAccessService cameraAccess) + { + _context = context; + _cameraAccess = cameraAccess; + } public async Task> Handle(GetEventQuery request, CancellationToken ct) { @@ -21,9 +26,20 @@ public class GetEventHandler : IRequestHandler e.Camera) .FirstOrDefaultAsync(e => e.Id == request.Id, ct); - return ev is null - ? ServiceResult.NotFound("Event not found") - : ServiceResult.Success(MapResponse(ev)); + if (ev is null) + return ServiceResult.NotFound("Event not found"); + + // Verify user has access to this event's camera + if (request.UserId.HasValue) + { + var hasAccess = await _cameraAccess + .HasCameraAccessAsync(request.UserId.Value, ev.CameraId, ct) + .ConfigureAwait(false); + if (!hasAccess) + return ServiceResult.NotFound("Event not found"); + } + + return ServiceResult.Success(MapResponse(ev)); } private static CameraEventResponse MapResponse(CameraEvent e) => new( diff --git a/src/Heimdall.Application/Events/Queries/GetEvent/GetEventQuery.cs b/src/Heimdall.Application/Events/Queries/GetEvent/GetEventQuery.cs index e17a6d6..84ca58f 100644 --- a/src/Heimdall.Application/Events/Queries/GetEvent/GetEventQuery.cs +++ b/src/Heimdall.Application/Events/Queries/GetEvent/GetEventQuery.cs @@ -4,4 +4,4 @@ using MediatR; namespace Heimdall.Application.Events.Queries.GetEvent; -public record GetEventQuery(Guid Id) : IRequest>; +public record GetEventQuery(Guid Id, Guid? UserId = null) : IRequest>; diff --git a/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsHandler.cs b/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsHandler.cs index 1ab631c..476f85f 100644 --- a/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsHandler.cs +++ b/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsHandler.cs @@ -1,18 +1,23 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Queries.GetEvents; - #pragma warning disable CA1711 public class GetEventsHandler : IRequestHandler>> #pragma warning restore CA1711 { private readonly IApplicationDbContext _context; + private readonly ICameraAccessService _cameraAccess; - public GetEventsHandler(IApplicationDbContext context) => _context = context; + public GetEventsHandler(IApplicationDbContext context, ICameraAccessService cameraAccess) + { + _context = context; + _cameraAccess = cameraAccess; + } public async Task>> Handle(GetEventsQuery request, CancellationToken ct) { @@ -21,6 +26,15 @@ public class GetEventsHandler : IRequestHandler e.Camera); + // Camera access filtering + if (request.UserId.HasValue) + { + var accessibleCameraIds = await _cameraAccess + .GetUserAccessibleCameraIdsAsync(request.UserId.Value, ct) + .ConfigureAwait(false); + query = query.Where(e => accessibleCameraIds.Contains(e.CameraId)); + } + if (request.CameraId.HasValue) query = query.Where(e => e.CameraId == request.CameraId.Value); diff --git a/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsQuery.cs b/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsQuery.cs index 25f0fbb..f0bc2fe 100644 --- a/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsQuery.cs +++ b/src/Heimdall.Application/Events/Queries/GetEvents/GetEventsQuery.cs @@ -14,4 +14,5 @@ public record GetEventsQuery( double? MinConfidence, int Page = 1, int PageSize = 50, - string? Search = null) : IRequest>>; + string? Search = null, + Guid? UserId = null) : IRequest>>; diff --git a/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraHandler.cs b/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraHandler.cs index ab4eaa9..e4cf4de 100644 --- a/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraHandler.cs +++ b/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraHandler.cs @@ -1,21 +1,36 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Queries.GetRecentByCamera; - #pragma warning disable CA1711 public class GetRecentByCameraHandler : IRequestHandler>> #pragma warning restore CA1711 { private readonly IApplicationDbContext _context; + private readonly ICameraAccessService _cameraAccess; - public GetRecentByCameraHandler(IApplicationDbContext context) => _context = context; + public GetRecentByCameraHandler(IApplicationDbContext context, ICameraAccessService cameraAccess) + { + _context = context; + _cameraAccess = cameraAccess; + } public async Task>> Handle(GetRecentByCameraQuery request, CancellationToken ct) { + // Verify user has access to this camera + if (request.UserId.HasValue) + { + var hasAccess = await _cameraAccess + .HasCameraAccessAsync(request.UserId.Value, request.CameraId, ct) + .ConfigureAwait(false); + if (!hasAccess) + return ServiceResult>.NotFound("Camera not found"); + } + var items = await _context.CameraEvents .AsNoTracking() .Include(e => e.Camera) diff --git a/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraQuery.cs b/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraQuery.cs index 0a51a48..d991f42 100644 --- a/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraQuery.cs +++ b/src/Heimdall.Application/Events/Queries/GetRecentByCamera/GetRecentByCameraQuery.cs @@ -4,4 +4,4 @@ using MediatR; namespace Heimdall.Application.Events.Queries.GetRecentByCamera; -public record GetRecentByCameraQuery(Guid CameraId, int Count = 20) : IRequest>>; +public record GetRecentByCameraQuery(Guid CameraId, int Count = 20, Guid? UserId = null) : IRequest>>; diff --git a/src/Heimdall.Application/Services/ICameraAccessService.cs b/src/Heimdall.Application/Services/ICameraAccessService.cs new file mode 100644 index 0000000..c67ee6b --- /dev/null +++ b/src/Heimdall.Application/Services/ICameraAccessService.cs @@ -0,0 +1,23 @@ +namespace Heimdall.Application.Services; + +/// +/// Enforces camera-level access control. +/// Users with direct UserCamera entries get camera-level access. +/// Users without UserCamera entries fall back to site-level (UserSite). +/// Admin role bypasses all checks (always returns true / all cameras). +/// +public interface ICameraAccessService +{ + /// + /// Returns true if the user has access to the specified camera. + /// Admins always have access. Non-admins need either a UserCamera entry + /// or a UserSite entry for the camera's site. + /// + Task HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default); + + /// + /// Returns all camera IDs the user can access (via UserCamera or UserSite fallback). + /// Admins get all camera IDs. + /// + Task> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs b/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs index 77f6a23..72626da 100644 --- a/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs +++ b/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs @@ -3,6 +3,7 @@ using Heimdall.Domain.Entities; using MediatR; namespace Heimdall.Application.Sites.Commands.DeleteSite; + public class DeleteSiteHandler : IRequestHandler { private readonly IApplicationDbContext _context; diff --git a/src/Heimdall.Application/Sites/Commands/UpdateSite/UpdateSiteCommand.cs b/src/Heimdall.Application/Sites/Commands/UpdateSite/UpdateSiteCommand.cs index d288173..425a7cc 100644 --- a/src/Heimdall.Application/Sites/Commands/UpdateSite/UpdateSiteCommand.cs +++ b/src/Heimdall.Application/Sites/Commands/UpdateSite/UpdateSiteCommand.cs @@ -3,4 +3,5 @@ using Heimdall.Application.DTOs; using MediatR; namespace Heimdall.Application.Sites.Commands.UpdateSite; + public record UpdateSiteCommand(Guid Id, string Name, string? Address, string? Timezone, string? NtfyTopic = null, bool? AutoUpdateEnabled = null) : IRequest>; diff --git a/src/Heimdall.Domain/Entities/UserCamera.cs b/src/Heimdall.Domain/Entities/UserCamera.cs new file mode 100644 index 0000000..5ed6bd3 --- /dev/null +++ b/src/Heimdall.Domain/Entities/UserCamera.cs @@ -0,0 +1,23 @@ +namespace Heimdall.Domain.Entities; + +/// +/// Many-to-many relationship between users and cameras. +/// Determines which cameras a non-admin user can access at camera granularity. +/// Falls back to site-level (UserSite) when no direct camera entry exists. +/// +public class UserCamera +{ + public Guid UserId { get; private set; } + public Guid CameraId { get; private set; } + + public AppUser User { get; private set; } = null!; + public Camera Camera { get; private set; } = null!; + + private UserCamera() { } // EF Core + + public UserCamera(Guid userId, Guid cameraId) + { + UserId = userId; + CameraId = cameraId; + } +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index a9a16fe..ec04610 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -27,6 +27,7 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet Cameras => Set(); public DbSet CameraCredentials => Set(); public DbSet CameraDetectionProfiles => Set(); + public DbSet UserCameras => Set(); public DbSet UserSites => Set(); public DbSet ApiKeys => Set(); public DbSet AuditLogs => Set(); @@ -93,6 +94,7 @@ public class AppDbContext : IdentityDbContext, IApplicat builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); builder.Entity().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted); + builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); // Matching query filters for dependent entities sharing required // navigations to soft-deletable entities. These prevent EF Core diff --git a/src/Heimdall.Infrastructure/Data/Configurations/UserCameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/UserCameraConfiguration.cs new file mode 100644 index 0000000..11aae41 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/UserCameraConfiguration.cs @@ -0,0 +1,28 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class UserCameraConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("user_cameras"); + + builder.HasKey(uc => new { uc.UserId, uc.CameraId }); + + builder.HasOne(uc => uc.User) + .WithMany() + .HasForeignKey(uc => uc.UserId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasOne(uc => uc.Camera) + .WithMany() + .HasForeignKey(uc => uc.CameraId) + .OnDelete(DeleteBehavior.Restrict); + + // Index for "find all cameras for a user" queries + builder.HasIndex(uc => uc.UserId); + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 65d55ac..71ef4be 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -162,6 +162,9 @@ public static class DependencyInjection // Camera assignment service (used by CQRS handlers) services.AddScoped(); + // Camera access control (used by CQRS handlers and MonitoringHub) + services.AddScoped(); + // Analysis job scheduler (capability + affinity + load routing) services.AddScoped(); diff --git a/src/Heimdall.Infrastructure/Services/CameraAccessService.cs b/src/Heimdall.Infrastructure/Services/CameraAccessService.cs new file mode 100644 index 0000000..097f42b --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/CameraAccessService.cs @@ -0,0 +1,88 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +/// +/// Enforces camera-level access control. +/// Admins bypass all checks. Non-admins fall back from UserCamera → UserSite. +/// +public class CameraAccessService : ICameraAccessService +{ + private readonly IApplicationDbContext _context; + private readonly UserManager _userManager; + + public CameraAccessService( + IApplicationDbContext context, + UserManager userManager) + { + _context = context; + _userManager = userManager; + } + + /// + public async Task HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default) + { + // Admin bypass + var user = await _userManager.FindByIdAsync(userId.ToString()).ConfigureAwait(false); + if (user is not null && await _userManager.IsInRoleAsync(user, AppRoles.Admin).ConfigureAwait(false)) + return true; + + // Check direct UserCamera entry + var hasDirectAccess = await _context.UserCameras + .AnyAsync(uc => uc.UserId == userId && uc.CameraId == cameraId, ct) + .ConfigureAwait(false); + if (hasDirectAccess) + return true; + + // Fallback: check site-level access via UserSite + var camera = await _context.Cameras + .AsNoTracking() + .FirstOrDefaultAsync(c => c.Id == cameraId, ct) + .ConfigureAwait(false); + if (camera is null) + return false; + + return await _context.UserSites + .AnyAsync(us => us.UserId == userId && us.SiteId == camera.SiteId, ct) + .ConfigureAwait(false); + } + + /// + public async Task> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default) + { + // Admin: return all camera IDs + var user = await _userManager.FindByIdAsync(userId.ToString()).ConfigureAwait(false); + if (user is not null && await _userManager.IsInRoleAsync(user, AppRoles.Admin).ConfigureAwait(false)) + { + return await _context.Cameras + .AsNoTracking() + .Select(c => c.Id) + .ToListAsync(ct) + .ConfigureAwait(false); + } + + // Collect camera IDs from direct UserCamera entries + 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 directCameraIds.Union(siteCameraIds).Distinct().ToList(); + } +} diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs index 06a3628..caff904 100644 --- a/src/Heimdall.Web/Controllers/EventsController.cs +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using Heimdall.Application.DTOs; using Heimdall.Application.Events.Commands.CreateEvent; using Heimdall.Application.Events.Commands.AttachSnapshot; @@ -48,7 +49,8 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _mediator.Send(new GetEventQuery(id), ct); + var userId = GetUserId(); + var result = await _mediator.Send(new GetEventQuery(id, userId), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -74,7 +76,8 @@ public class EventsController : ControllerBase if (type is not null && Enum.TryParse(type, true, out var t)) parsedType = t; - var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q), ct); + var userId = GetUserId(); + var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q, userId), ct); return Ok(result.Data); } @@ -84,7 +87,8 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default) { - var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count), ct); + var userId = GetUserId(); + var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count, userId), ct); return Ok(result.Data); } @@ -113,6 +117,11 @@ public class EventsController : ControllerBase ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } + + private Guid? GetUserId() + { + var sub = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value + ?? User?.FindFirst("sub")?.Value; + return Guid.TryParse(sub, out var userId) ? userId : null; + } } - - diff --git a/src/Heimdall.Web/Hubs/MonitoringHub.cs b/src/Heimdall.Web/Hubs/MonitoringHub.cs index a3d42c2..c2748a2 100644 --- a/src/Heimdall.Web/Hubs/MonitoringHub.cs +++ b/src/Heimdall.Web/Hubs/MonitoringHub.cs @@ -1,6 +1,11 @@ +using System.Security.Claims; +using Heimdall.Application.Common; using Heimdall.Application.Metrics; using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.SignalR; namespace Heimdall.Api.Hubs; @@ -14,11 +19,22 @@ namespace Heimdall.Api.Hubs; public class MonitoringHub : Hub { private readonly ILogger _logger; + private readonly ICameraAccessService _cameraAccess; + private readonly UserManager _userManager; - public MonitoringHub(ILogger logger) => _logger = logger; + public MonitoringHub( + ILogger logger, + ICameraAccessService cameraAccess, + UserManager userManager) + { + _logger = logger; + _cameraAccess = cameraAccess; + _userManager = userManager; + } /// /// Clients call this to join monitoring for a specific site. + /// Verifies the user has access to at least one camera at the site. /// public async Task JoinSiteMonitoring(string siteId) { @@ -27,6 +43,20 @@ public class MonitoringHub : Hub 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); } @@ -70,6 +100,13 @@ public class MonitoringHub : Hub _logger.LogDebug("Client disconnected from monitoring hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } + + private Guid? GetUserId() + { + var sub = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value + ?? Context.User?.FindFirst("sub")?.Value; + return Guid.TryParse(sub, out var userId) ? userId : null; + } } /// diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs index 91ea1a5..1a36457 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using Heimdall.Application.Events.Queries.GetEvent; +using Heimdall.Application.Services; using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; @@ -19,7 +20,10 @@ public class GetEventHandlerTests var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); - var handler = new GetEventHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.HasCameraAccessAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + var handler = new GetEventHandler(context, cameraAccess); var result = await handler.Handle(new GetEventQuery(ev.Id), CancellationToken.None); @@ -34,7 +38,8 @@ public class GetEventHandlerTests { var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); - var handler = new GetEventHandler(context); + var cameraAccess = Substitute.For(); + var handler = new GetEventHandler(context, cameraAccess); var result = await handler.Handle(new GetEventQuery(Guid.NewGuid()), CancellationToken.None); diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs index 1ebcfc7..c26b8f2 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using Heimdall.Application.Events.Queries.GetEvents; +using Heimdall.Application.Services; using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; @@ -23,7 +24,10 @@ public class GetEventsHandlerTests var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); - var handler = new GetEventsHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any(), Arg.Any()) + .Returns([camera.Id]); + var handler = new GetEventsHandler(context, cameraAccess); var result = await handler.Handle(new GetEventsQuery(null, null, null, null, null, null, 1, 50), CancellationToken.None); @@ -49,7 +53,10 @@ public class GetEventsHandlerTests var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); - var handler = new GetEventsHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any(), Arg.Any()) + .Returns([camera1.Id, camera2.Id]); + var handler = new GetEventsHandler(context, cameraAccess); var result = await handler.Handle(new GetEventsQuery(camera1.Id, null, null, null, null, null, 1, 50), CancellationToken.None); @@ -75,7 +82,10 @@ public class GetEventsHandlerTests var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); - var handler = new GetEventsHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any(), Arg.Any()) + .Returns([camera.Id]); + var handler = new GetEventsHandler(context, cameraAccess); var result = await handler.Handle(new GetEventsQuery(null, null, null, null, null, null, 1, 50, "JEAN"), CancellationToken.None); diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs index cbc51db..ddf8a0f 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using Heimdall.Application.Events.Queries.GetRecentByCamera; +using Heimdall.Application.Services; using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; @@ -25,7 +26,10 @@ public class GetRecentByCameraHandlerTests var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); - var handler = new GetRecentByCameraHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.HasCameraAccessAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + var handler = new GetRecentByCameraHandler(context, cameraAccess); var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None); @@ -41,7 +45,10 @@ public class GetRecentByCameraHandlerTests var cameraId = Guid.NewGuid(); var context = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); - var handler = new GetRecentByCameraHandler(context); + var cameraAccess = Substitute.For(); + cameraAccess.HasCameraAccessAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + var handler = new GetRecentByCameraHandler(context, cameraAccess); var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None);