test(security): expand camera access matrix #65
No files matched your search
@@ -0,0 +1,82 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Controllers;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Scenarios;
|
||||
|
||||
[Collection("Postgres")]
|
||||
public sealed class CameraAuthorizationScenarios : PostgresTestBase
|
||||
{
|
||||
public CameraAuthorizationScenarios(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
[Fact]
|
||||
public async Task Direct_camera_grant_is_scoped_and_soft_delete_revokes_api_access()
|
||||
{
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
var viewer = await Factory.CreateViewerClientAsync();
|
||||
var viewerId = UserIdFromAccessToken(viewer);
|
||||
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = $"Access matrix {Guid.NewGuid():N}",
|
||||
timezone = "UTC"
|
||||
});
|
||||
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var siteId = (await siteResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
||||
|
||||
var allowedCameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
||||
{
|
||||
siteId,
|
||||
name = "Granted camera",
|
||||
rtspUrl = "rtsp://127.0.0.1:554/stream"
|
||||
});
|
||||
allowedCameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var allowedCameraId = (await allowedCameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
||||
|
||||
var deniedCameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
||||
{
|
||||
siteId,
|
||||
name = "Unassigned camera",
|
||||
rtspUrl = "rtsp://127.0.0.2:554/stream"
|
||||
});
|
||||
deniedCameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var deniedCameraId = (await deniedCameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
||||
|
||||
var grantResponse = await admin.PostAsJsonAsync("api/user-camera-access", new
|
||||
{
|
||||
userId = viewerId,
|
||||
siteId,
|
||||
cameraId = allowedCameraId
|
||||
});
|
||||
grantResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
// The authorized route reaches the query and returns its normal empty result;
|
||||
// a same-site camera without a grant is stopped by the resource boundary.
|
||||
(await viewer.GetAsync($"api/assignments/camera/{allowedCameraId}")).StatusCode
|
||||
.ShouldBe(HttpStatusCode.NotFound);
|
||||
(await viewer.GetAsync($"api/assignments/camera/{deniedCameraId}")).StatusCode
|
||||
.ShouldBe(HttpStatusCode.Forbidden);
|
||||
|
||||
var groupResponse = await admin.PostAsJsonAsync("api/groups", new { name = $"Private group {Guid.NewGuid():N}" });
|
||||
groupResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var groupId = (await groupResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
||||
(await viewer.GetAsync($"api/groups/{groupId}/cameras")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
(await viewer.PostAsJsonAsync($"api/groups/{groupId}/cameras", new { groupId, cameraId = deniedCameraId }))
|
||||
.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
|
||||
(await admin.DeleteAsync($"api/cameras/{allowedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
||||
(await viewer.GetAsync($"api/assignments/camera/{allowedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
}
|
||||
|
||||
private static Guid UserIdFromAccessToken(HttpClient client)
|
||||
{
|
||||
var token = client.DefaultRequestHeaders.Authorization?.Parameter
|
||||
?? throw new InvalidOperationException("The test client has no access token");
|
||||
var payload = token.Split('.')[1].Replace('-', '+').Replace('_', '/');
|
||||
payload = payload.PadRight((payload.Length + 3) / 4 * 4, '=');
|
||||
using var document = JsonDocument.Parse(Convert.FromBase64String(payload));
|
||||
return document.RootElement.GetProperty("sub").GetGuid();
|
||||
}
|
||||
}
|
||||
@@ -66,4 +66,24 @@ public sealed class EventsHubTests
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents("invalid"));
|
||||
await groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Soft_deleted_camera_is_not_joined_even_with_a_live_direct_grant()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "direct");
|
||||
var groups = Substitute.For<IGroupManager>();
|
||||
var context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection");
|
||||
context.User.Returns(AccessFixture.Principal(user.Id));
|
||||
context.Items.Returns(new Dictionary<object, object?>());
|
||||
using var hub = new EventsHub(NullLogger<EventsHub>.Instance, f.Access, f.Cameras, new LiveSubscriptions())
|
||||
{ Context = context, Groups = groups };
|
||||
|
||||
f.A1.SoftDelete();
|
||||
await f.Db.SaveChangesAsync();
|
||||
|
||||
await Should.ThrowAsync<HubException>(() => hub.JoinSiteEvents(f.A.Id.ToString()));
|
||||
await groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,48 @@ public sealed class ResourceAccessFilterTests
|
||||
(await Run(f, "Cameras", "GetById", new(), new() { ["id"] = f.A1.Id })).ShouldBeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assignment_routes_check_camera_scope_and_require_full_site_scope_for_agents()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var partial = f.User(AppRoles.Supervisor, "group");
|
||||
var partialPrincipal = AccessFixture.Principal(partial.Id);
|
||||
|
||||
(await Run(f, "Assignments", "GetCameraAssignment", partialPrincipal,
|
||||
new() { ["cameraId"] = f.A1.Id })).ShouldBeNull();
|
||||
(await Run(f, "Assignments", "GetCameraHistory", partialPrincipal,
|
||||
new() { ["cameraId"] = f.A2.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Assignments", "GetAgentAssignments", partialPrincipal,
|
||||
new() { ["agentId"] = f.AgentA.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Assignments", "AssignSiteCameras", partialPrincipal,
|
||||
new() { ["siteId"] = f.A.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Assignments", "AssignCamera", partialPrincipal,
|
||||
new() { ["request"] = new { CameraId = f.A1.Id, AgentId = f.AgentA.Id } })).ShouldBeOfType<ForbidResult>();
|
||||
|
||||
var siteUser = f.User(AppRoles.Supervisor, "site");
|
||||
var sitePrincipal = AccessFixture.Principal(siteUser.Id);
|
||||
(await Run(f, "Assignments", "GetAgentAssignments", sitePrincipal,
|
||||
new() { ["agentId"] = f.AgentA.Id })).ShouldBeNull();
|
||||
(await Run(f, "Assignments", "AssignSiteCameras", sitePrincipal,
|
||||
new() { ["siteId"] = f.A.Id })).ShouldBeNull();
|
||||
(await Run(f, "Assignments", "AssignSiteCameras", sitePrincipal,
|
||||
new() { ["siteId"] = f.B.Id })).ShouldBeOfType<ForbidResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Soft_deleted_cameras_are_rejected_by_resource_filter()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "direct");
|
||||
f.A1.SoftDelete();
|
||||
await f.Db.SaveChangesAsync();
|
||||
|
||||
(await Run(f, "Cameras", "GetById", AccessFixture.Principal(user.Id),
|
||||
new() { ["id"] = f.A1.Id })).ShouldBeOfType<ForbidResult>();
|
||||
(await Run(f, "Assignments", "GetCameraAssignment", AccessFixture.Principal(user.Id),
|
||||
new() { ["cameraId"] = f.A1.Id })).ShouldBeOfType<ForbidResult>();
|
||||
}
|
||||
|
||||
private static async Task<IActionResult?> Run(AccessFixture f, string controller, string action,
|
||||
System.Security.Claims.ClaimsPrincipal principal, Dictionary<string, object?> arguments)
|
||||
{
|
||||
|
||||
@@ -54,6 +54,27 @@ public sealed class ResourceAccessTests
|
||||
(await f.Cameras.HasCameraAccessAsync(user.Id, f.B1.Id)).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Soft_deleted_camera_and_its_events_are_inaccessible_even_with_a_grant()
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(AppRoles.Viewer, "direct");
|
||||
var ev = new CameraEvent(f.A1.Id, EventType.MotionDetected, .9);
|
||||
f.Db.CameraEvents.Add(ev);
|
||||
await f.Db.SaveChangesAsync();
|
||||
var requester = (await f.Access.ResolveAsync(AccessFixture.Principal(user.Id)))!;
|
||||
|
||||
(await f.Access.CameraAsync(requester, f.A1.Id)).ShouldBeTrue();
|
||||
(await f.Access.EventAsync(requester, ev.Id)).ShouldBeTrue();
|
||||
|
||||
f.A1.SoftDelete();
|
||||
await f.Db.SaveChangesAsync();
|
||||
|
||||
(await f.Access.CameraAsync(requester, f.A1.Id)).ShouldBeFalse();
|
||||
(await f.Access.EventAsync(requester, ev.Id)).ShouldBeFalse();
|
||||
(await f.Cameras.GetUserAccessibleCameraIdsAsync(user.Id)).ShouldNotContain(f.A1.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Agent_is_bound_to_one_key_and_only_assigned_cameras()
|
||||
{
|
||||
|
||||
@@ -28,7 +28,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
|
||||
- [ ] **AGENT-09** Mesurer seuils de capture et santé d'enregistrement sous panne caméra/modèle/disque ; rendre alertes et métriques exploitables.
|
||||
- [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif.
|
||||
- [ ] **Toggle caméra #59/#199** Protéger les double-clics ; prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l'état survit au redémarrage.
|
||||
- [ ] **Accès caméra #141** Compléter la matrice Admin/sans droit/site/caméra/groupe/soft-delete sur API et SignalR, y compris mutations et suppression en cascade ; mesurer le seuil de couverture demandé (>80 %). Vérifier que l'UI couvre le remplacement atomique des accès (#133/#134).
|
||||
- [ ] **Accès caméra #141** La PR en cours ajoute des scénarios d’intégration API pour grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que des tests du filtre d’affectations et des hubs après suppression logique. Restent la mesure du seuil de couverture demandé (>80 %) et la validation UI du remplacement atomique des accès (#133/#134).
|
||||
- [ ] **QA-01** Ajouter scénarios transversaux API → Agent → stockage → événement → UI → notification, dont périmètres de site et droits caméra ; mesurer couverture utile sans compter les tests ignorés comme succès.
|
||||
- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée.
|
||||
|
||||
|
||||
Reference in new issue
Block a user