fix(camera): keep activated cameras offline until agent confirmation

This commit is contained in:
arnaud.dartois committed 2026-11-12 01:00:37 +01:00
1 parent 9fd9c75f94
commit 35ff573341
8 files changed
+76 -11

No files matched your search

+11 -1
View File
@@ -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.<id>.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.
@@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
var oldStatus = camera.Status;
var newStatus = camera.Status == CameraStatus.Disabled
? CameraStatus.Online
? CameraStatus.Offline
: CameraStatus.Disabled;
camera.SetStatus(newStatus);
@@ -633,7 +633,7 @@ else
if (result.Succeeded && result.Data is not null)
{
_camera.Status = result.Data.Status;
Snackbar.Add(result.Data.Status == "Online" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
Snackbar.Add(result.Data.Status != "Disabled" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
}
else _editError = result.ErrorMessage ?? Text["CameraDetail_StatusError"];
}
@@ -638,7 +638,7 @@
{
camera.Status = result.Data.Status;
Snackbar.Add(
result.Data.Status == "Online" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
result.Data.Status != "Disabled" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
Severity.Success);
}
else
@@ -10,6 +10,7 @@ using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory;
using Heimdall.Application.Cameras.Commands.ReportCameraStatus;
using Heimdall.Application.DTOs;
using Heimdall.Api.Security;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
@@ -24,6 +25,8 @@ namespace Heimdall.Api.Controllers;
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly ResourceAccess _resourceAccess;
/// <summary>Query parameters for agent log retrieval.</summary>
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;
}
/// <summary>Register an agent using a site registration token.</summary>
[AllowAnonymous]
@@ -149,6 +156,11 @@ public class AgentsController : ControllerBase
public async Task<IActionResult> 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<CameraStatus>(request.Status, true, out var status))
return BadRequest(new { error = $"Invalid status: {request.Status}" });
@@ -171,7 +171,7 @@ public class CamerasController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Toggle a camera between Online and Disabled.</summary>
/// <summary>Toggle a camera between enabled (initially Offline) and Disabled.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/toggle-status")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
@@ -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<IApplicationDbContext>();
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>([_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<AuditLog>(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\"")));
}
}
@@ -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<JsonElement>();
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<JsonElement>();
camera.GetProperty("status").GetString().ShouldBe("Offline");
var tokenResponse = await client.PostAsync($"api/sites/{siteId}/tokens", null);
var siteToken = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>())
.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<JsonElement>();
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<JsonElement>();
camera.GetProperty("status").GetString().ShouldBe("Online");
// Toggle back → Disabled
var toggleBack = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);