From 1ac10ee3a28491ee62e06dbd46a06a9ce20ca1de Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 6 Nov 2026 07:34:38 +0100 Subject: [PATCH] Complete remaining Heimdall PR acceptance --- docker/Dockerfile | 5 ++- docker/Dockerfile.agent | 5 ++- docker/Dockerfile.agent.gpu | 4 +- skills/agent-runtime-acceptance/SKILL.md | 6 +++ skills/agent-update-acceptance/SKILL.md | 8 ++++ skills/analysis-job-pipeline/SKILL.md | 3 ++ skills/central-auto-updates/SKILL.md | 3 ++ skills/site-ntfy-creation/SKILL.md | 14 ++++++ .../Services/AnalysisJobPollingService.cs | 13 ++++-- .../Services/LogUploadService.cs | 13 +++++- src/Heimdall.Application/DTOs/SiteDto.cs | 2 +- .../Controllers/AgentsController.cs | 2 +- .../Controllers/SitesController.cs | 2 +- src/Heimdall.Web/Heimdall.Web.csproj | 1 + src/Heimdall.Web/Program.cs | 8 +++- .../AnalysisJobPollingServiceTests.cs | 40 +++++++++++++++++ .../LogBufferServiceTests.cs | 17 +++++++ .../Controllers/AgentLogsControllerTests.cs | 45 +++++++++++++++++++ .../Controllers/SitesControllerTests.cs | 13 ++++-- todo.md | 6 +++ 20 files changed, 196 insertions(+), 14 deletions(-) create mode 100644 skills/site-ntfy-creation/SKILL.md create mode 100644 tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs diff --git a/docker/Dockerfile b/docker/Dockerfile index 1801e0e..272d0ee 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,7 +10,10 @@ RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng \ + && rm -rf /var/lib/apt/lists/* ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /out/ ./ EXPOSE 8080 diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index c04d3d0..dd6a502 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -12,7 +12,10 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-rest FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata \ + && rm -rf /var/lib/apt/lists/* RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall ENV ASPNETCORE_URLS=http://127.0.0.1:8080 COPY --from=build /out/ ./ diff --git a/docker/Dockerfile.agent.gpu b/docker/Dockerfile.agent.gpu index fac6582..40e86ac 100644 --- a/docker/Dockerfile.agent.gpu +++ b/docker/Dockerfile.agent.gpu @@ -18,7 +18,9 @@ ENV DOTNET_ROOT=/usr/share/dotnet \ LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \ ASPNETCORE_URLS=http://127.0.0.1:8080 \ Agent__InferenceExecutionProvider=CUDA -RUN apt-get update -qq && apt-get install -y --no-install-recommends \ +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ ca-certificates ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \ && rm -rf /var/lib/apt/lists/* \ && install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index de5df73..1d3d8e8 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -15,6 +15,12 @@ Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL - `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`. - Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. +## Central log upload contract + +- Agent log levels must use the exact `AgentLogLevel` names accepted by Central's parser: `Information` and `Warning` (not the common aliases `Info`/`Warn`), alongside `Trace`, `Debug`, `Error`, and `Critical`. +- Keep `ToCentralLevel_MapsMicrosoftNamesToAgentContract` asserting both the emitted name and that Central's enum parser accepts it at the corresponding severity. +- Agent logging is API-key authenticated. A source-built disposable Compose check can register a synthetic Agent, submit one entry at each severity to `/api/agents/{id}/logs`, and read them back through the authorized Central log query. Keep generated credentials and project resources isolated and clean up exact locally built tags per the Compose recipe. + ## Local checks ```bash diff --git a/skills/agent-update-acceptance/SKILL.md b/skills/agent-update-acceptance/SKILL.md index 13399f3..20d78c3 100644 --- a/skills/agent-update-acceptance/SKILL.md +++ b/skills/agent-update-acceptance/SKILL.md @@ -20,3 +20,11 @@ Use this skill when changing `install/install-agent.sh`, `install/install-agent. - For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval. - Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory. - Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration. + +## Central installer asset delivery + +- `Heimdall.Web.csproj` publishes the Linux/Windows Agent installers and their supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files. +- ASP.NET Core's default MIME table does not recognize `.py`. Add `.py` to a `FileExtensionContentTypeProvider` explicitly or `/install/agent-supervisor.py` returns 404 despite being present in `wwwroot`. +- For changes to these assets or static-file configuration, build Central from the current source in a disposable Compose project and GET `/install/install-agent.sh` and `/install/agent-supervisor.py`. Require HTTP 200 and byte-for-byte equality with their source files. Also require `/healthz` healthy. +- Follow `skills/compose-disposable-recipe/SKILL.md`: use generated credentials, isolated ports/project volumes/network, a unique Central image tag, and an EXIT trap installed before build. Verify all project containers, volumes, and networks are gone and remove/verify absence of the exact local image tag. Keep shared base images. +- A successful local acceptance proves the source-built Central serves the files; it does not prove a deployed Central image has been rebuilt or restarted. Confirm deployed endpoints separately before calling an incident resolved. diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md index 560dcb4..70a98a6 100644 --- a/skills/analysis-job-pipeline/SKILL.md +++ b/skills/analysis-job-pipeline/SKILL.md @@ -16,6 +16,7 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet - The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result. - Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection. - Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types. +- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies. ## Required validation @@ -32,6 +33,8 @@ The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-h ## Current local acceptance evidence +Result delivery has a focused Agent test: `SendResultAsync_DoesNotRetryPermanentClientRejection` returns after one HTTP 400. The supported result JSON uses web defaults (`classIndex`, not `ClassIndex`). The disposable source Compose acceptance below validates the Central job API and persisted result contract; keep transport retry behavior covered by the Agent HTTP-handler test. + On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference. Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated. diff --git a/skills/central-auto-updates/SKILL.md b/skills/central-auto-updates/SKILL.md index cd789e3..d8659d3 100644 --- a/skills/central-auto-updates/SKILL.md +++ b/skills/central-auto-updates/SKILL.md @@ -24,6 +24,7 @@ Use this skill when changing the Linux or Windows Central installer, its generat - Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files. - Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned. - The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system. +- For each published Ubuntu-based Central, CPU Agent, or CUDA Agent runtime image, update the base OS package index, upgrade installed OS packages noninteractively, install runtime packages, and clear apt lists in one layer. Verify the final image with the repository's pinned Trivy scanner at HIGH/CRITICAL severity; a passing application build does not clear OS package advisories. ## Re-running the installer @@ -37,4 +38,6 @@ Use this skill when changing the Linux or Windows Central installer, its generat Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data. +When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance. + If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup. diff --git a/skills/site-ntfy-creation/SKILL.md b/skills/site-ntfy-creation/SKILL.md new file mode 100644 index 0000000..994d91a --- /dev/null +++ b/skills/site-ntfy-creation/SKILL.md @@ -0,0 +1,14 @@ +--- +name: site-ntfy-creation +description: Maintain and accept the site-specific ntfy topic through Heimdall site creation. +--- + +# Site ntfy creation + +The site topic is an optional destination used by notification delivery. Creation crosses a JSON DTO, `SitesController`, `CreateSiteCommand`, `CreateSiteHandler`, and `Site`; every layer must carry `NtfyTopic`. Keep the optional DTO parameter last/defaulted to preserve existing clients. The Sites page already sends it in `CreateSiteAsync`. + +## Acceptance + +1. Extend the PostgreSQL API integration test to POST a unique site name and `ntfyTopic`, then GET that site and assert `SiteResponse.NtfyTopic` equals the submitted topic. This catches JSON binding, controller mapping, and relational persistence together. +2. Run the focused integration test against the repository PostgreSQL fixture. +3. Follow `skills/compose-disposable-recipe/SKILL.md` to run a source-built disposable Compose stack. Bootstrap an isolated admin, create a site with a topic through `POST /api/sites`, read it back, and verify the topic. Remove the exact project and locally built tags and verify no project containers, volumes, or networks remain. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs index 8ed54ab..9bd6d07 100644 --- a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -137,7 +137,7 @@ public sealed class AnalysisJobPollingService : BackgroundService .ToArray()); } - private async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId, + internal async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId, AnalysisResult result, CancellationToken ct) { var retryDelay = TimeSpan.FromSeconds(2); @@ -155,6 +155,13 @@ public sealed class AnalysisJobPollingService : BackgroundService jobId, result.AttemptId); return; } + if ((int)response.StatusCode is >= 400 and < 500) + { + _logger.LogError( + "Analysis result for job {JobId} was permanently rejected with HTTP {StatusCode}; stopping retries", + jobId, (int)response.StatusCode); + return; + } _logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying", jobId, (int)response.StatusCode); } @@ -226,8 +233,8 @@ public sealed class AnalysisJobPollingService : BackgroundService private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType, string? ParametersJson); - private sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, + internal sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, float Width, float Height, int? ClassIndex); - private sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error, + internal sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error, IReadOnlyList Detections); } diff --git a/src/Heimdall.Agent/Services/LogUploadService.cs b/src/Heimdall.Agent/Services/LogUploadService.cs index 14b5394..55a98a0 100644 --- a/src/Heimdall.Agent/Services/LogUploadService.cs +++ b/src/Heimdall.Agent/Services/LogUploadService.cs @@ -16,6 +16,17 @@ namespace Heimdall.Agent.Services; /// public class LogUploadService : BackgroundService { + internal static string ToCentralLevel(LogLevel level) => level switch + { + LogLevel.Trace => "Trace", + LogLevel.Debug => "Debug", + LogLevel.Information => "Information", + LogLevel.Warning => "Warning", + LogLevel.Error => "Error", + LogLevel.Critical => "Critical", + _ => "Info" + }; + private readonly IHttpClientFactory _httpClientFactory; private readonly LogBufferService _buffer; private readonly AgentState _state; @@ -73,7 +84,7 @@ public class LogUploadService : BackgroundService entries = entries.Select(e => new { timestampUtc = e.TimestampUtc, - level = e.Level.ToString(), + level = ToCentralLevel(e.Level), message = e.Message, exception = e.Exception, source = e.Source diff --git a/src/Heimdall.Application/DTOs/SiteDto.cs b/src/Heimdall.Application/DTOs/SiteDto.cs index a706ba6..e04c6c4 100644 --- a/src/Heimdall.Application/DTOs/SiteDto.cs +++ b/src/Heimdall.Application/DTOs/SiteDto.cs @@ -1,6 +1,6 @@ namespace Heimdall.Application.DTOs; -public record CreateSiteRequest(string Name, string? Address, string? Timezone); +public record CreateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null); public record UpdateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null, bool? AutoUpdateEnabled = null); diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index 7e734c2..05a4571 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -209,7 +209,7 @@ public class AgentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task GetLogs( Guid id, - AgentLogsQuery query, + [FromQuery] AgentLogsQuery query, CancellationToken ct) { var result = await _mediator.Send( diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index f9fc219..ffa1fc5 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -49,7 +49,7 @@ public class SitesController : ControllerBase if (!this.TryGetUserId(out var actorId)) return Unauthorized(new { error = "Invalid user identity" }); - var command = new CreateSiteCommand(request.Name, request.Address, request.Timezone, ActorId: actorId); + var command = new CreateSiteCommand(request.Name, request.Address, request.Timezone, request.NtfyTopic, ActorId: actorId); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index feb0bc7..b7b0df0 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -15,6 +15,7 @@ + + { + requests++; + return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); + })) { BaseAddress = new Uri("http://localhost/") }; + var service = new AnalysisJobPollingService(null!, null!, null!, null!, null!, + NullLogger.Instance); + + await service.SendResultAsync(client, Guid.NewGuid(), Guid.NewGuid(), + new AnalysisJobPollingService.AnalysisResult(Guid.NewGuid(), true, null, []), + CancellationToken.None); + + requests.ShouldBe(1); + } + [Theory] [InlineData("\"PersonDetection\"", true)] [InlineData("\"vehicLeClassification\"", true)] @@ -54,4 +86,12 @@ public sealed class AnalysisJobPollingServiceTests actual.ShouldBe(expected); } + + private sealed class StubHttpMessageHandler( + Func responseFactory) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(responseFactory(request)); + } } diff --git a/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs index d2da723..f734960 100644 --- a/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs @@ -1,4 +1,6 @@ using Heimdall.Agent.Logging; +using Heimdall.Agent.Services; +using Heimdall.Domain.Enums; using Microsoft.Extensions.Logging; using Shouldly; @@ -6,6 +8,21 @@ namespace Heimdall.Agent.Tests; public class LogBufferServiceTests { + [Theory] + [InlineData(LogLevel.Trace, "Trace")] + [InlineData(LogLevel.Debug, "Debug")] + [InlineData(LogLevel.Information, "Information")] + [InlineData(LogLevel.Warning, "Warning")] + [InlineData(LogLevel.Error, "Error")] + [InlineData(LogLevel.Critical, "Critical")] + public void ToCentralLevel_MapsMicrosoftNamesToAgentContract(LogLevel level, string expected) + { + var centralName = LogUploadService.ToCentralLevel(level); + centralName.ShouldBe(expected); + Enum.TryParse(centralName, true, out var parsed).ShouldBeTrue(); + parsed.ShouldBe((AgentLogLevel)level); + } + private static BufferedLogEntry Entry(string message, LogLevel level = LogLevel.Information) => new(DateTime.UtcNow, level, message, null, "TestService"); diff --git a/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs new file mode 100644 index 0000000..3a62b20 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs @@ -0,0 +1,45 @@ +using System.Net.Http.Json; +using Heimdall.Application.DTOs; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public sealed class AgentLogsControllerTests(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres) +{ + [Fact] + public async Task SubmitAgentLogs_CentralLevelNames_ArePersistedAndQueryable() + { + var admin = await Factory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", + new CreateSiteRequest("Agent log acceptance", null, "UTC")); + siteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var site = await siteResponse.Content.ReadFromJsonAsync(); + site.ShouldNotBeNull(); + site.RegistrationToken.ShouldNotBeNullOrWhiteSpace(); + + var agentClient = Factory.CreateClient(); + var registerResponse = await agentClient.PostAsJsonAsync("api/agents/register", + new RegisterAgentRequest(site.RegistrationToken!, "log-acceptance", "test", null)); + registerResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var agent = await registerResponse.Content.ReadFromJsonAsync(); + agent.ShouldNotBeNull(); + agent.ApiKey.ShouldNotBeNullOrWhiteSpace(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", agent.ApiKey); + + var timestamp = DateTime.UtcNow; + var levels = new[] { "Trace", "Debug", "Information", "Warning", "Error", "Critical", "Info", "Warn" }; + var submitResponse = await agentClient.PostAsJsonAsync($"api/agents/{agent.AgentId}/logs", + new SubmitAgentLogsRequest(levels.Select(level => new AgentLogEntryRequest( + timestamp, level, "Synthetic PR138 log", null, "acceptance")).ToArray())); + submitResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var readResponse = await admin.GetAsync($"api/agents/{agent.AgentId}/logs?page=1&pageSize=50"); + readResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var logs = await readResponse.Content.ReadFromJsonAsync>(); + logs.ShouldNotBeNull(); + logs.TotalCount.ShouldBe(6); + logs.Items.Select(log => log.Level).Order(StringComparer.Ordinal) + .ShouldBe(new[] { "Critical", "Debug", "Error", "Information", "Trace", "Warning" }); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs index 6628ed3..4daf290 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs @@ -24,11 +24,18 @@ public class SitesControllerTests : PostgresTestBase { name = "Site Test", address = "Paris", - timezone = "Europe/Paris" + timezone = "Europe/Paris", + ntfyTopic = "site-test-topic" }); - var body = await response.Content.ReadAsStringAsync(); - await File.WriteAllTextAsync("/tmp/test-response-body.txt", body); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var created = await response.Content.ReadFromJsonAsync(); + created.ShouldNotBeNull(); + + var siteResponse = await client.GetAsync($"api/sites/{created.Id}"); + siteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var site = await siteResponse.Content.ReadFromJsonAsync(); + site.ShouldNotBeNull(); + site.NtfyTopic.ShouldBe("site-test-topic"); } [Fact] diff --git a/todo.md b/todo.md index f29d4cc..1279f10 100644 --- a/todo.md +++ b/todo.md @@ -18,6 +18,12 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P1 — parcours caméra, agent et données +- [ ] **AGENT-INSTALL-ASSETS** Central renvoyait HTTP 404 pour `/install/agent-supervisor.py`, car le middleware statique ASP.NET Core n'associait aucun type MIME à `.py` et refusait le fichier pourtant présent dans le publish. `Program.ConfigureMiddleware` mappe maintenant `.py` vers `text/x-python`. Deux recettes source Compose ont confirmé `/healthz` sain et les deux assets HTTP 200 identiques à la source; la recette `hmd-pr138-verified-1793916772-972` vérifie aussi `text/x-python`. Projet final nettoyé 0/0/0 et image `heimdall:hmd-pr138-verified-1793916772-972-central` absente. Le Central public répondait encore 404 au contrôle initial; le déploiement/restart et la vérification publique restent à faire. Skill : `skills/agent-update-acceptance/SKILL.md`. + +- [x] **Contrats Agent / création de site** L'upload des logs envoie maintenant les noms d'énumération acceptés par Central (`Information`, `Warning`); une réponse 4xx à un résultat d'analyse est définitive et libère la boucle de polling. La création de site propage le sujet ntfy optionnel au handler. La recette source Compose a révélé puis corrigé le 415 de `GET /api/agents/{id}/logs` en liant son filtre depuis la query string. Tests Agent ciblés 25/25; intégration PostgreSQL source Compose 2/2 (création site/topic, ajout de logs, rejet des alias `Info`/`Warn`, lecture des six sévérités) et build Web sans avertissement. Projet `hmd-pr138-verified-1793916772-972` teardown 0/0/0, image exacte absente. Skills : `skills/agent-runtime-acceptance/SKILL.md`, `skills/analysis-job-pipeline/SKILL.md`, `skills/site-ntfy-creation/SKILL.md`. + +- [ ] **SECURITY/IMAGE-APT-UPDATE** Le run CI PR #756 a réussi les builds serveur/Agent/CUDA mais les trois scans Trivy et `CI policy` ont échoué. Le scan local du Central source a isolé `CVE-2026-109518` dans `apt` et `libapt-pkg6.0t64` 2.8.3 (correctif Ubuntu 2.8.4ubuntu0.1). Les trois Dockerfiles runtime mettent maintenant à niveau les paquets OS avant l'installation des dépendances. Tentative de recette Central source avec le tag isolé `heimdall:hmd-pr138-apt-1793946707-574639-central`: l'upgrade APT est resté bloqué en état noyau `D` pendant plus d'une minute; interruption de la tentative, projet vérifié sans conteneur/volume/réseau et tag absent. Le scan post-correctif n'est donc pas validé localement. La CI doit valider les builds et scans Trivy HIGH/CRITICAL des trois images; aucune publication ne doit être déclarée tant que ce run n'a pas réussi. Skill : `skills/central-auto-updates/SKILL.md`. + - [x] Corriger la fixture unitaire `CreateEventHandlerTests` révélée rouge par la CI de la PR #138 : elle ne configurait pas `Recordings`, requis par la requête EF du handler. Le test initialise maintenant un `MockDbSet` vide. Le run #753 a aussi révélé que la bannière PWA du contexte loopback interceptait les dialogues Playwright; la fixture E2E la ferme après navigation. Ces précautions sont documentées dans `skills/analysis-job-pipeline/SKILL.md`; la CI PR reste à relancer pour confirmer l’ensemble des suites. - [x] **AUTH-BOOTSTRAP** L’assistant `/setup` ne crée le premier compte que sur une base vide et lui attribue Admin dans une transaction PostgreSQL sérialisable; l’UI login redirige vers l’assistant au premier lancement. L’inscription anonyme et l’ancienne route `register-admin` renvoient 404; les comptes suivants passent par l’UI `/users` et l’API protégée `Admin.Users`. Recette Compose jetable finale du 4 novembre 2026 : statut initial ouvert → premier Admin → statut fermé → création d’utilisateurs protégée; vérification de la route setup, refus anonyme et suppression des deux anciennes routes. Tests PostgreSQL intégration complets 161/161; tests E2E AuthFlow/UI utilisateur réussis (résultats notés dans USER-RBAC ci-dessous). Le bootstrap concurrent reste couvert par les tests PostgreSQL dédiés.