From 35ff5733410bcfa36034e22a88b17da3ccdafbfc Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 11 Nov 2026 21:10:40 +0100 Subject: [PATCH] fix(camera): keep activated cameras offline until agent confirmation --- skills/camera-toggle-acceptance/SKILL.md | 12 ++++- .../ToggleCameraStatusCommand.cs | 2 +- .../Components/Pages/CameraDetail.razor | 2 +- .../Components/Pages/CamerasPage.razor | 2 +- .../Controllers/AgentsController.cs | 14 +++++- .../Controllers/CamerasController.cs | 2 +- .../Cameras/ToggleCameraStatusCommandTests.cs | 6 +-- .../Controllers/CamerasControllerTests.cs | 47 ++++++++++++++++++- 8 files changed, 76 insertions(+), 11 deletions(-) diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md index 568d562..7f53e92 100644 --- a/skills/camera-toggle-acceptance/SKILL.md +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -9,14 +9,18 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn ## Implementation path -- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. +- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled. +- Agent status reports require the API key to resolve to the same Agent ID in the route. Authenticate and authorize that identity with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`. - `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest. - `GetEffectiveAgentConfigQuery` emits `camera..enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`. - `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera. +- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled. - Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state. ## Local verification +The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract. + Run the focused Agent lifecycle suites: ```bash @@ -51,3 +55,9 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel ## Sixth source-built run The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold. + +## Camera status contract acceptance + +For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled. + +A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence. diff --git a/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs b/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs index 2e855e5..ef9586d 100644 --- a/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/ToggleCameraStatus/ToggleCameraStatusCommand.cs @@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandlerQuery parameters for agent log retrieval. public record AgentLogsQuery( [FromQuery] int Page = 1, @@ -35,7 +38,11 @@ public class AgentsController : ControllerBase private readonly IMediator _mediator; - public AgentsController(IMediator mediator) => _mediator = mediator; + public AgentsController(IMediator mediator, ResourceAccess resourceAccess) + { + _mediator = mediator; + _resourceAccess = resourceAccess; + } /// Register an agent using a site registration token. [AllowAnonymous] @@ -149,6 +156,11 @@ public class AgentsController : ControllerBase public async Task ReportCameraStatus( Guid id, Guid cameraId, [FromBody] ReportCameraStatusRequest request, CancellationToken ct) { + var requester = await _resourceAccess.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await _resourceAccess.AgentAsync(requester, id, ct)) + return Forbid(); + if (!Enum.TryParse(request.Status, true, out var status)) return BadRequest(new { error = $"Invalid status: {request.Status}" }); diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index dce3268..28a0731 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -171,7 +171,7 @@ public class CamerasController : ControllerBase : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } - /// Toggle a camera between Online and Disabled. + /// Toggle a camera between enabled (initially Offline) and Disabled. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] [HttpPost("{id:guid}/toggle-status")] [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/ToggleCameraStatusCommandTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/ToggleCameraStatusCommandTests.cs index ed02ab5..d48a3e8 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Cameras/ToggleCameraStatusCommandTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/ToggleCameraStatusCommandTests.cs @@ -20,7 +20,7 @@ public class ToggleCameraStatusCommandTests } [Fact] - public async Task Toggle_disabled_camera_should_set_online() + public async Task Toggle_disabled_camera_should_set_offline_until_agent_confirms_connectivity() { var context = Substitute.For(); context.Cameras.Returns(MockDbSetHelper.CreateFor([_disabledCamera])); @@ -30,7 +30,7 @@ public class ToggleCameraStatusCommandTests result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); - result.Data.Status.ShouldBe(CameraStatus.Online); + result.Data.Status.ShouldBe(CameraStatus.Offline); } [Fact] @@ -76,6 +76,6 @@ public class ToggleCameraStatusCommandTests context.AuditLogs.Received(1).Add(Arg.Is(log => log != null && log.UserId == actorId && log.Action == "Camera.StatusChanged" && log.OldValue!.Contains("\"status\":\"Disabled\"") - && log.NewValue!.Contains("\"status\":\"Online\""))); + && log.NewValue!.Contains("\"status\":\"Offline\""))); } } diff --git a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs index 8354960..00b8999 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs @@ -67,11 +67,54 @@ public class CamerasControllerTests : PostgresTestBase var cameraId = cameraContent.GetProperty("id").GetGuid(); cameraContent.GetProperty("status").GetString().ShouldBe("Disabled"); - // Toggle → Online + // Activation is enabled but has no connectivity evidence yet. var toggleResponse = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null); toggleResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var toggled = await toggleResponse.Content.ReadFromJsonAsync(); - toggled.GetProperty("status").GetString().ShouldBe("Online"); + toggled.GetProperty("status").GetString().ShouldBe("Offline"); + + var cameraResponse = await client.GetAsync($"api/cameras/{cameraId}"); + var camera = await cameraResponse.Content.ReadFromJsonAsync(); + camera.GetProperty("status").GetString().ShouldBe("Offline"); + + var tokenResponse = await client.PostAsync($"api/sites/{siteId}/tokens", null); + var siteToken = (await tokenResponse.Content.ReadFromJsonAsync()) + .GetProperty("token").GetString()!; + var registerResponse = await client.PostAsJsonAsync("api/agents/register", new + { + token = siteToken, + hostname = "camera-connectivity-agent", + version = "1.0.0-test" + }); + var registration = await registerResponse.Content.ReadFromJsonAsync(); + var agentId = registration.GetProperty("agentId").GetGuid(); + var apiKey = registration.GetProperty("apiKey").GetString()!; + var agentClient = Factory.CreateClient(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey); + + var heartbeatResponse = await agentClient.PostAsJsonAsync( + $"api/agents/{agentId}/heartbeat", new { publicIp = "127.0.0.1" }); + heartbeatResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var assignmentResponse = await client.PostAsJsonAsync("api/assignments", new + { + cameraId, + agentId, + reason = "integration test" + }); + assignmentResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var reportResponse = await agentClient.PutAsJsonAsync( + $"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" }); + reportResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var wrongAgentReport = await agentClient.PutAsJsonAsync( + $"api/agents/{Guid.NewGuid()}/cameras/{cameraId}/status", new { status = "Offline" }); + wrongAgentReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); + + cameraResponse = await client.GetAsync($"api/cameras/{cameraId}"); + camera = await cameraResponse.Content.ReadFromJsonAsync(); + camera.GetProperty("status").GetString().ShouldBe("Online"); // Toggle back → Disabled var toggleBack = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);