From 38647d3623dedd4f0a6a1b84ae0eb20fe5f30d3e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 00:32:22 +0100 Subject: [PATCH 1/8] fix(web): render a 404 page for unknown routes (#294) Co-authored-by: Arnaud Dartois --- skills/ui-unknown-route/SKILL.md | 17 ++++++ src/Heimdall.Web/Program.cs | 49 ++++++++++++++++ .../Pages/PageRenderTests.cs | 56 +++++++++++++++++++ 3 files changed, 122 insertions(+) create mode 100644 skills/ui-unknown-route/SKILL.md diff --git a/skills/ui-unknown-route/SKILL.md b/skills/ui-unknown-route/SKILL.md new file mode 100644 index 0000000..1d3135f --- /dev/null +++ b/skills/ui-unknown-route/SKILL.md @@ -0,0 +1,17 @@ +--- +name: ui-unknown-route +description: Diagnose and verify unknown-route rendering in Heimdall's interactive Blazor UI. +--- + +# Unknown UI routes + +Heimdall renders its root `Routes` component in an interactive server circuit with prerendering disabled (`Components/App.razor`). In .NET 10, configure `Router.NotFoundPage`; the legacy `` fragment is not supported by Blazor Web Apps. Unknown direct browser requests have no matched endpoint and cannot start the circuit, so `Program` must render a small static HTML 404 using the same `NotFoundPage_*` resources and `/dashboard` link. Skip API, hub, health, Hangfire, non-HTML, and file-like requests so their 404 responses keep their native format. + +The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component. + +## Acceptance workflow + +1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response. +2. Verify client-side navigation from a known route to an unknown URL (for example `Blazor.navigateTo(...)`) and confirm the same page renders. +3. Confirm `/not-found` and a known route still render. Verify API 404 responses remain API responses and do not receive the UI document, even when the request accepts HTML. +4. Run the focused Playwright E2E tests and the disposable Central + PostgreSQL Compose acceptance from `compose-disposable-recipe`. Use generated credentials, unique project/port/volume/image names, probe the route through a browser after the health check, and verify cleanup of project resources and every exact local image tag. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index f5ce381..a12e411 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -850,6 +850,55 @@ public partial class Program localizationOptions.RequestCultureProviders.Insert(1, new CookieRequestCultureProvider()); app.UseRequestLocalization(localizationOptions); + // Unknown browser routes have no endpoint and cannot start the interactive + // Blazor circuit. Render the same localized NotFound content as a static + // 404 document; preserve native API, hub, health, Hangfire, and asset errors. + app.UseStatusCodePages(async statusCodeContext => + { + var context = statusCodeContext.HttpContext; + var path = context.Request.Path; + var isNonUiResponse = path.StartsWithSegments("/api") + || path.StartsWithSegments("/hubs") + || path.StartsWithSegments("/healthz") + || path.StartsWithSegments("/hangfire") + || Path.HasExtension(path.Value) + || !context.Request.Headers.Accept.Any(value => + value?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true); + if (context.Response.StatusCode != StatusCodes.Status404NotFound || isNonUiResponse) return; + + var text = context.RequestServices.GetRequiredService(); + var encoder = System.Text.Encodings.Web.HtmlEncoder.Default; + var title = encoder.Encode(text["NotFoundPage_Title"]); + var message = encoder.Encode(text["NotFoundPage_Body"]); + var back = encoder.Encode(text["NotFoundPage_Back"]); + context.Response.ContentType = "text/html; charset=utf-8"; + var document = $$""" + + + + + + {{title}} + + + +
+

{{title}}

+

{{message}}

+ {{back}} +
+ + + """; + await context.Response.WriteAsync(document); + }); + // Hangfire dashboard — Admin uniquement (policy AdminJobs). // MapHangfireDashboard est utilisé car UseHangfireDashboard avec // DashboardOptions.Authorization n'existe pas pour les policies ASP.NET. diff --git a/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs b/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs index 2d3e0dd..7b83177 100644 --- a/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs @@ -106,4 +106,60 @@ public class PageRenderTests : E2ETestBase var text = await body.TextContentAsync(); text.ShouldNotBeNull(); } + + [Fact] + public async Task Unknown_route_renders_not_found_after_direct_load_and_client_navigation() + { + var directUrl = $"{BaseUrl}/not-a-route-qa"; + var directResponseTask = Page.WaitForResponseAsync(response => response.Url == directUrl); + try + { + await Page.GotoAsync(directUrl, new PageGotoOptions + { + WaitUntil = WaitUntilState.DOMContentLoaded, + Timeout = 15000, + }); + } + catch (PlaywrightException) + { + // Playwright reports the expected HTTP 404 as a navigation exception. + } + var directResponse = await directResponseTask; + + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + var backLink = Page.GetByRole(AriaRole.Link, new() { Name = "Retour" }); + (await backLink.IsVisibleAsync()).ShouldBeTrue(); + (await backLink.GetAttributeAsync("href")).ShouldBe("/dashboard"); + directResponse.Status.ShouldBe(404); + + await Page.GotoAsync($"{BaseUrl}/not-found"); + await WaitForBlazorCircuitAsync(); + await Page.EvaluateAsync("Blazor.navigateTo('/not-a-route-navigation-qa')"); + await Page.WaitForURLAsync("**/not-a-route-navigation-qa"); + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + + await LoginViaUiAsync(); + var authenticatedResponseTask = Page.WaitForResponseAsync(response => + response.Url == $"{BaseUrl}/not-a-route-authenticated-qa"); + try + { + await Page.GotoAsync($"{BaseUrl}/not-a-route-authenticated-qa"); + } + catch (PlaywrightException) + { + // The server returns HTTP 404 while rendering the not-found page. + } + var authenticatedResponse = await authenticatedResponseTask; + authenticatedResponse.Status.ShouldBe(404); + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + + using var apiClient = new HttpClient(); + apiClient.DefaultRequestHeaders.Accept.ParseAdd("text/html"); + var apiNotFound = await apiClient.GetAsync($"{BaseUrl}/api/not-a-route-qa"); + apiNotFound.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); + (await apiNotFound.Content.ReadAsStringAsync()).ShouldNotContain("Page introuvable"); + } } From 43e6752a31d32a4dc9b2f918417d9f0f802adfa8 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 07:02:54 +0100 Subject: [PATCH 2/8] fix(web): make dashboard refresh disposal safe Refs #298 Co-authored-by: Arnaud Dartois --- skills/dashboard-refresh-lifecycle/SKILL.md | 17 +++++++ .../Components/Pages/Dashboard.razor | 49 ++++++++++++++++--- .../Components/Pages/DashboardTests.cs | 29 +++++++++++ 3 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 skills/dashboard-refresh-lifecycle/SKILL.md diff --git a/skills/dashboard-refresh-lifecycle/SKILL.md b/skills/dashboard-refresh-lifecycle/SKILL.md new file mode 100644 index 0000000..a1599cf --- /dev/null +++ b/skills/dashboard-refresh-lifecycle/SKILL.md @@ -0,0 +1,17 @@ +--- +name: dashboard-refresh-lifecycle +description: Maintain the Heimdall Web dashboard's post-render agent refresh loop and component shutdown behavior. +--- + +# Dashboard refresh lifecycle + +The dashboard starts its 15-second agent refresh only after the first interactive render. Keep the loop task and its `CancellationTokenSource` owned by the component. Capture the token once when starting the loop; do not read the mutable source inside the loop because disposal or a restart can replace it. + +When the component is disposed, mark it disposed under the same synchronization used to start the loop, cancel the source, and let the loop finish before disposing that source. Handle a request cancellation as a normal shutdown, keep transient/401 load failures from escaping the renderer, and do not schedule `StateHasChanged` after disposal. + +## Acceptance + +- Exercise component disposal while a refresh is pending and confirm no renderer exception escapes. +- Exercise an agent request failure (including unauthorized) and confirm dashboard rendering remains stable and no periodic work survives component disposal. +- Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj`. +- For behavior changes, run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, then verify project resource and exact locally built image tag cleanup. diff --git a/src/Heimdall.Web/Components/Pages/Dashboard.razor b/src/Heimdall.Web/Components/Pages/Dashboard.razor index 186799a..d4a96eb 100644 --- a/src/Heimdall.Web/Components/Pages/Dashboard.razor +++ b/src/Heimdall.Web/Components/Pages/Dashboard.razor @@ -282,6 +282,8 @@ // infinie awaitée dans OnInitializedAsync bloque le rendu initial // (SSR/prerender attend la fin du cycle de vie) → page lente. private CancellationTokenSource? _refreshCts; + private Task? _refreshTask; + private readonly object _refreshLock = new(); private bool _disposed; private bool _autoRefreshStarted; @@ -290,18 +292,24 @@ if (firstRender && !_autoRefreshStarted) { _autoRefreshStarted = true; - await StartAutoRefresh(); + lock (_refreshLock) + { + if (!_disposed) + { + _refreshCts = new CancellationTokenSource(); + _refreshTask = RunAutoRefreshAsync(_refreshCts.Token); + } + } } } - private async Task StartAutoRefresh() + private async Task RunAutoRefreshAsync(CancellationToken cancellationToken) { - _refreshCts = new CancellationTokenSource(); try { - while (!_refreshCts.Token.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { - await Task.Delay(TimeSpan.FromSeconds(15), _refreshCts.Token); + await Task.Delay(TimeSpan.FromSeconds(15), cancellationToken); if (_disposed) return; // Rafraîchit uniquement la section agents (léger) : les stats // globales restent au refresh manuel pour éviter le flash. @@ -311,6 +319,10 @@ var agentsPage = await Api.GetAllAgentsAsync(1, 5); _agents = agentsPage?.Items?.ToList(); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return; + } catch { /* keep last state */ } finally { @@ -320,6 +332,7 @@ } } catch (OperationCanceledException) { /* arrêt volontaire */ } + catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested) { /* arrêt concurrent */ } } private async Task LoadData() @@ -401,9 +414,29 @@ public void Dispose() { - _disposed = true; + CancellationTokenSource? refreshCts; + lock (_refreshLock) + { + _disposed = true; + refreshCts = _refreshCts; + _refreshCts = null; + } Language.LanguageChanged -= OnLanguageChanged; - _refreshCts?.Cancel(); - _refreshCts?.Dispose(); + if (refreshCts is not null) + { + try { refreshCts.Cancel(); } + catch (ObjectDisposedException) { /* shutdown already completed */ } + _ = DisposeRefreshAsync(refreshCts, _refreshTask); + } + } + + private static async Task DisposeRefreshAsync(CancellationTokenSource refreshCts, Task? refreshTask) + { + try + { + if (refreshTask is not null) await refreshTask; + } + catch (OperationCanceledException) { } + finally { refreshCts.Dispose(); } } } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs index dee3117..57136bf 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs @@ -173,4 +173,33 @@ public class DashboardTests : PageTestBase (snackbar.ShownSnackbars.First().Message?.ToString() ?? "").ShouldContain("Erreur"); }); } + + [Fact] + public async Task DashboardPage_DisposePendantRafraichissementNePropagePasException() + { + SetupHappyPath(); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agent-1")); + + // Le composant doit tolérer un 401 lors de son rafraîchissement périodique, + // puis annuler et attendre proprement sa boucle à la destruction. + Handler.OnGet("api/agents", System.Net.HttpStatusCode.Unauthorized); + cut.Dispose(); + await Task.Delay(50); + } + + [Fact] + public void DashboardPage_ErreurAgentsNeFaitPasEchouerLeRendu() + { + SetupHappyPath(); + Handler.OnGet("api/agents", System.Net.HttpStatusCode.InternalServerError); + LoginAs(); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agents en ligne")); + cut.Dispose(); + } } From 4c790e04899088827b38538453bd3ec6d8cbb66a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 08:55:07 +0100 Subject: [PATCH 3/8] fix(agent): repair installation and release paths Refs #293 Co-authored-by: Arnaud Dartois --- docker/Dockerfile.agent | 11 ++- docker/Dockerfile.agent.gpu | 11 ++- .../docker-compose.agent.dev.gpu-nvidia.yml | 2 + docker/docker-compose.agent.dev.yml | 3 + docs/agent-release-signing.md | 2 + docs/docker-compose.md | 11 +++ docs/gitea-builds.md | 2 +- install/install-agent.ps1 | 1 + install/install-agent.sh | 1 + readme.md | 3 + skills/agent-update-acceptance/SKILL.md | 32 ++++++ skills/release-automation/SKILL.md | 1 + .../Services/DockerUpdateService.cs | 4 + .../Components/Pages/SiteDetail.razor | 4 - .../Components/SiteInstallPanel.razor | 97 ++++++++++++++++--- .../Localization/SharedResources.en.resx | 11 ++- .../Localization/SharedResources.fr.resx | 11 ++- .../Localization/SharedResources.resx | 11 ++- 18 files changed, 192 insertions(+), 26 deletions(-) diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index 00f2962..02ca22d 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -12,12 +12,19 @@ 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 +ARG DOCKER_CLI_VERSION=29.9.3 +ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973 RUN apt-get update -qq \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \ && apt_version="$(dpkg-query -W -f='${Version}' apt)" \ && dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \ - && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata \ - && rm -rf /var/lib/apt/lists/* + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl ffmpeg wget libgomp1 tzdata \ + && curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ + "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \ + && echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \ + && tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \ + && install -m 0755 /tmp/docker/docker /usr/local/bin/docker \ + && rm -rf /tmp/docker /tmp/docker-cli.tgz /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 3b8ff72..2c328e9 100644 --- a/docker/Dockerfile.agent.gpu +++ b/docker/Dockerfile.agent.gpu @@ -13,6 +13,8 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003be FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime WORKDIR /app +ARG DOCKER_CLI_VERSION=29.9.3 +ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973 ENV DOTNET_ROOT=/usr/share/dotnet \ PATH=/usr/share/dotnet:$PATH \ LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \ @@ -24,8 +26,13 @@ RUN apt-get update -qq \ && apt_version="$(dpkg-query -W -f='${Version}' apt)" \ && dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \ && 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/* \ + ca-certificates curl ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \ + && curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ + "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \ + && echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \ + && tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \ + && install -m 0755 /tmp/docker/docker /usr/local/bin/docker \ + && rm -rf /tmp/docker /tmp/docker-cli.tgz /var/lib/apt/lists/* \ && install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/ COPY --from=build /out/ ./ diff --git a/docker/docker-compose.agent.dev.gpu-nvidia.yml b/docker/docker-compose.agent.dev.gpu-nvidia.yml index f52e4b3..0481bfb 100644 --- a/docker/docker-compose.agent.dev.gpu-nvidia.yml +++ b/docker/docker-compose.agent.dev.gpu-nvidia.yml @@ -10,6 +10,8 @@ services: dockerfile: docker/Dockerfile.agent.gpu environment: Agent__InferenceExecutionProvider: CUDA + volumes: + - /var/run/docker.sock:/var/run/docker.sock deploy: resources: reservations: diff --git a/docker/docker-compose.agent.dev.yml b/docker/docker-compose.agent.dev.yml index 8da30ad..9d2b374 100644 --- a/docker/docker-compose.agent.dev.yml +++ b/docker/docker-compose.agent.dev.yml @@ -7,6 +7,8 @@ services: dockerfile: docker/Dockerfile.agent restart: unless-stopped user: "1654:1654" + group_add: + - "${DOCKER_GID:-0}" network_mode: host environment: ASPNETCORE_URLS: http://127.0.0.1:8081 @@ -19,6 +21,7 @@ services: Agent__StateDirectory: /var/lib/heimdall volumes: - agent_state:/var/lib/heimdall + - /var/run/docker.sock:/var/run/docker.sock healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"] interval: 30s diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md index b5e7bcb..ccd1422 100644 --- a/docs/agent-release-signing.md +++ b/docs/agent-release-signing.md @@ -18,6 +18,8 @@ Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’or La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent ces références et leur SHA-256 est listé dans `SHA256SUMS`. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. +Avant de générer ou mettre à jour un Agent, configurer dans Central le réglage global `updates.releaseapiurl` avec l’URL HTTPS de l’API de la dernière release Gitea publiée, par exemple `https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest`. Le panneau d’installation Docker n’affiche le Compose que si cette API retourne une image et un digest signés. Les builds de `main` publient les images continues, mais ne créent pas de release Agent; il faut pousser un tag SemVer, attendre le brouillon, puis le promouvoir pour que l’API `latest` le serve. + Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM. ## Installer un Agent natif diff --git a/docs/docker-compose.md b/docs/docker-compose.md index 7ec2aef..294b5eb 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -148,6 +148,17 @@ local Central URL. The published Agent image uses CPU inference. The optional NVIDIA, AMD and Intel overlays expose hardware for inventory; they do not enable GPU inference. +Docker Agents mount `/var/run/docker.sock` so the Agent can pull and replace its +container when Central dispatches an update. This socket grants broad control +of the Docker host, effectively host-administrator access. Keep it only on +hosts where that trust is acceptable. The Agent image includes the Docker CLI +client; it does not run a Docker daemon. Updates preserve the previous image +for rollback if the replacement fails its health check. On Linux, start the +generated Compose with `DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)" +docker compose up -d` so the non-root Agent process can access hosts whose +socket is owned by the Docker group. The UI's `docker run` command determines +this group ID from the host socket automatically. + ## Optional software Start Central first to create the shared `heimdall-net` network. Optional diff --git a/docs/gitea-builds.md b/docs/gitea-builds.md index 241492a..b51b22e 100644 --- a/docs/gitea-builds.md +++ b/docs/gitea-builds.md @@ -25,7 +25,7 @@ Après validation de `verify` sur `main`, chaque job d'image publie son tag immu Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie. -Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. Le job reconstruit et scanne les trois images, puis publie les images CPU et CUDA de l’Agent et joint leurs manifestes au manifeste ECDSA signé. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release reste en brouillon jusqu'à promotion explicite. +Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` lancent le job séparé de release, après validation de `verify`. Un build réussi sur `main` ne crée pas de release Gitea : il publie les images `latest` et `sha-*` seulement. Pour préparer une version depuis le commit validé de `main`, créer et pousser un tag, par exemple `git tag -a v1.2.3 -m "Heimdall v1.2.3" && git push origin v1.2.3`. Le tag doit respecter la forme SemVer et viser un commit de `main`. Le job reconstruit et scanne les trois images, puis publie les images CPU et CUDA de l’Agent et joint leurs manifestes au manifeste ECDSA signé. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release Gitea reste en brouillon jusqu'à promotion explicite. Aucun tag n’existe encore sur le dépôt; aucun run de release tagué n’a donc eu lieu. ## Renovate diff --git a/install/install-agent.ps1 b/install/install-agent.ps1 index ba6a287..8e1916d 100644 --- a/install/install-agent.ps1 +++ b/install/install-agent.ps1 @@ -234,6 +234,7 @@ try { "Agent__SiteToken=$SiteToken", "Agent__AgentName=$AgentName", "Agent__StateDirectory=$stateDirectory", + "MODEL_PATH=$(Join-Path $releasePath 'models\yolov8n.onnx')", "Agent__UpdateInstallRoot=$releaseRoot", "Agent__UpdatePublicKeyPath=$publicKeyPath", "Agent__UpdateSupervisorPath=$supervisorPath", diff --git a/install/install-agent.sh b/install/install-agent.sh index c973d11..a209b84 100755 --- a/install/install-agent.sh +++ b/install/install-agent.sh @@ -151,6 +151,7 @@ if [[ "$RUN_MODE" == true ]]; then HEIMDALL_DOTNET="$DOTNET_BIN" \ ASPNETCORE_ENVIRONMENT=Production \ Agent__CentralUrl="$CENTRAL_URL" \ + Agent__AgentName="$AGENT_NAME" \ Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \ Agent__StateDirectory="$STATE_DIR" \ Agent__UpdateInstallRoot="$INSTALL_ROOT" \ diff --git a/readme.md b/readme.md index ca3f0dd..788c0e3 100644 --- a/readme.md +++ b/readme.md @@ -90,6 +90,9 @@ peut créer un service Windows (PowerShell administrateur requis). Pour Docker, utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de clé ni Compose de production ne doit être copié depuis le dépôt. Voir le [guide de signature et de mise à jour Agent](docs/agent-release-signing.md). +Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à +jour pilotées par Central; ce socket donne à l’Agent un contrôle étendu sur +l’hôte. N’installez ce mode que sur un hôte de confiance. ### 3. Développement local diff --git a/skills/agent-update-acceptance/SKILL.md b/skills/agent-update-acceptance/SKILL.md index 3fdeab4..5474136 100644 --- a/skills/agent-update-acceptance/SKILL.md +++ b/skills/agent-update-acceptance/SKILL.md @@ -7,6 +7,38 @@ description: Validate Heimdall native Agent install, signed update, startup heal Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`. +For Docker Agent install/update changes, also inspect the generated Compose and +`docker run` commands in `SiteInstallPanel.razor`, plus both CPU and NVIDIA +Agent images. The Docker updater shells out to the Docker CLI and therefore +requires the CLI in the image and `/var/run/docker.sock` mounted into the +container. Validate the generated Compose and Docker-run command together; +document that mounting this socket grants broad control of the host. The Docker +Run panel must provide POSIX and PowerShell commands, use an immutable signed +image reference, initialize the state volume, and keep the health endpoint +reachable for update rollback checks. A disposable image acceptance should +build with a project-unique tag and assert `docker --version` inside the image, +then remove and verify absence of that exact tag. When Compose has multiple +services using the built Agent image, the acceptance override must retag every +service, including one-shot volume initialization, so it does not create an +untracked `:local` image. + +For Windows Service installation, set `MODEL_PATH` to the installed +`current\models\yolov8n.onnx` path because the Service Control Manager does not +start services from the Agent release directory. Validate the service's model +path, enrollment, startup, signed update, and rollback on a real Windows host; +PowerShell parsing on Linux is not a substitute for that run. + +For Linux systemd installs, preserve the site display name through the existing +`LoadCredential=agent-name` credential and `AgentOptions` fallback. The +foreground installer may pass `Agent__AgentName` directly; do not put arbitrary +site names in an unescaped systemd `Environment=` assignment. + +Before accepting a native or Docker install flow, verify that Central's global +`updates.releaseapiurl` points to an HTTPS Gitea `releases/latest` API with a +published release containing the signed manifest, asset checksums, and required +image digest. A `main` Docker image build alone cannot supply the signed Agent +release metadata used by installers and the IHM. + ## Linux rollback simulation - Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`. diff --git a/skills/release-automation/SKILL.md b/skills/release-automation/SKILL.md index 669fea0..0963532 100644 --- a/skills/release-automation/SKILL.md +++ b/skills/release-automation/SKILL.md @@ -14,6 +14,7 @@ Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gi - Use a dedicated Gitea `RELEASE_TOKEN`, Docker Hub credentials, and a base64 encoded ECDSA P-256 key only in the tagged release job. Never make them available to PR jobs or print them. - Do not overwrite published image tags owned by another commit or mutate an already published Gitea release. Releases remain drafts until an operator promotes them. - The release includes deterministic Web and Agent archives, provenance, checksums, the public key, immutable image digests, and a signed Agent update manifest. +- A successful `main` build publishes Docker `latest` and immutable `sha-*` images but does not create a Gitea release. An operator starts versioned publication by pushing a SemVer tag (`git tag -a vX.Y.Z ... && git push origin vX.Y.Z`) that points to a commit on `main`. ## Offline end-to-end acceptance diff --git a/src/Heimdall.Agent/Services/DockerUpdateService.cs b/src/Heimdall.Agent/Services/DockerUpdateService.cs index d2a4e91..e853d65 100644 --- a/src/Heimdall.Agent/Services/DockerUpdateService.cs +++ b/src/Heimdall.Agent/Services/DockerUpdateService.cs @@ -162,6 +162,7 @@ public sealed class DockerUpdateService : BackgroundService if (!string.IsNullOrEmpty(c.NetworkMode)) a.AddRange(["--network", c.NetworkMode]); if (!string.IsNullOrEmpty(c.RestartPolicy)) a.AddRange(["--restart", c.RestartPolicy]); foreach (var e in c.Environment) a.AddRange(["-e", e]); + foreach (var group in c.Groups) a.AddRange(["--group-add", group]); foreach (var p in c.Ports) a.AddRange(["-p", p]); foreach (var v in c.Volumes) a.AddRange(["-v", v]); foreach (var d in c.Devices) a.AddRange(["--device", d]); @@ -292,6 +293,7 @@ public sealed class DockerUpdateService : BackgroundService c.CapAdd.AddRange(HostConfig.CapAdd ?? []); c.CapDrop.AddRange(HostConfig.CapDrop ?? []); c.SecurityOptions.AddRange(HostConfig.SecurityOptions ?? []); + c.Groups.AddRange(HostConfig.GroupAdd ?? []); c.Privileged = HostConfig.Privileged; c.IpcMode = HostConfig.IpcMode; c.PidMode = HostConfig.PidMode; @@ -312,6 +314,7 @@ public sealed class DockerUpdateService : BackgroundService [JsonPropertyName("CapAdd")] public List? CapAdd { get; init; } [JsonPropertyName("CapDrop")] public List? CapDrop { get; init; } [JsonPropertyName("SecurityOpt")] public List? SecurityOptions { get; init; } + [JsonPropertyName("GroupAdd")] public List? GroupAdd { get; init; } [JsonPropertyName("Privileged")] public bool Privileged { get; init; } [JsonPropertyName("IpcMode")] public string? IpcMode { get; init; } [JsonPropertyName("PidMode")] public string? PidMode { get; init; } @@ -350,6 +353,7 @@ internal sealed class ContainerConfig public string? ImageId { get; set; } public string? User { get; set; } public List Environment { get; set; } = []; + public List Groups { get; set; } = []; public List Ports { get; set; } = []; public List Volumes { get; set; } = []; public List Devices { get; set; } = []; diff --git a/src/Heimdall.Web/Components/Pages/SiteDetail.razor b/src/Heimdall.Web/Components/Pages/SiteDetail.razor index 6ccd3a4..c31b484 100644 --- a/src/Heimdall.Web/Components/Pages/SiteDetail.razor +++ b/src/Heimdall.Web/Components/Pages/SiteDetail.razor @@ -253,7 +253,6 @@ else private bool _generating; private string? _generatedToken; private DateTime _tokenExpiresAt; - private string _dockerComposeSnippet = ""; // ── Identifiants caméras ────────────────────────────────────── private List _credentials = []; @@ -385,15 +384,12 @@ else } _generatedToken = result.Token; _tokenExpiresAt = result.ExpiresAt; - _dockerComposeSnippet = GenerateDockerComposeSnippet(_generatedToken); Snackbar.Add(Text["SiteDetail_TokenGenerated"], Severity.Warning); } catch { Snackbar.Add(Text["SiteDetail_OperationFailed"], Severity.Error); } finally { _generating = false; } } - private string GenerateDockerComposeSnippet(string token) => ""; - /// Origin exposed by the browser that operators use to reach Central. private string CentralUrl => Nav.BaseUri.TrimEnd('/'); } diff --git a/src/Heimdall.Web/Components/SiteInstallPanel.razor b/src/Heimdall.Web/Components/SiteInstallPanel.razor index 71300a7..d2f75dd 100644 --- a/src/Heimdall.Web/Components/SiteInstallPanel.razor +++ b/src/Heimdall.Web/Components/SiteInstallPanel.razor @@ -64,18 +64,29 @@ else if (_method == "docker-compose" && !CanGenerateDocker) { @Text["SiteInstallPanel_ImageUnavailable"] } - -@Text["SiteInstallPanel_Commands"] -@foreach (var command in Commands) +else if (_method == "docker-run" && CanGenerateDocker) { - @Text[command.Label] - -
@command.Value
-
- - @Text["SiteInstallPanel_CopyCommand"] - + @Text["SiteInstallPanel_DockerUpdateNote"] +} +else if (_method == "docker-run") +{ + @Text["SiteInstallPanel_ImageUnavailable"] +} + +@if (_method != "docker-run" || CanGenerateDocker) +{ + @Text["SiteInstallPanel_Commands"] + @foreach (var command in Commands) + { + @Text[command.Label] + +
@command.Value
+
+ + @Text["SiteInstallPanel_CopyCommand"] + + } } @if (_method == "windows-run") @@ -165,7 +176,10 @@ else if (_method == "windows-service") [ ("SiteInstallPanel_Install", DockerRunInstallCommand), ("SiteInstallPanel_Run", DockerRunCommand), - ("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}") + ("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}"), + ("SiteInstallPanel_InstallPowerShell", DockerRunPowerShellInstallCommand), + ("SiteInstallPanel_RunPowerShell", DockerRunPowerShellCommand), + ("SiteInstallPanel_CheckPowerShell", DockerRunPowerShellCheckCommand) ]; return []; } @@ -208,6 +222,8 @@ else if (_method == "windows-service") container_name: heimdall-agent-{{safeName}} restart: unless-stopped user: "1654:1654" + group_add: + - "${DOCKER_GID:-0}" network_mode: host environment: Agent__CentralUrl: {{YamlScalar(CentralUrl)}} @@ -219,6 +235,7 @@ else if (_method == "windows-service") Agent__UpdatePublicKeyPem: "{{pem}}" volumes: - agent_state_{{safeName}}:/var/lib/heimdall + - /var/run/docker.sock:/var/run/docker.sock depends_on: agent-state-init: condition: service_completed_successfully @@ -249,8 +266,9 @@ else if (_method == "windows-service") get { var volume = "heimdall-agent-state-" + Slugify(SiteName); - return $"docker pull {_agentImageReference} && docker volume create {volume} && " + - $"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {_agentImageReference} -R 1654:1654 /state"; + var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; + return $"docker pull {image} && docker volume create {volume} && " + + $"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {image} -R 1654:1654 /state"; } } @@ -263,6 +281,8 @@ else if (_method == "windows-service") var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " + (_useGpuImage ? "--gpus all " : "") + + "--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " + + "-v /var/run/docker.sock:/var/run/docker.sock " + $"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " + $"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " + $"-e Agent__InferenceExecutionProvider={(_useGpuImage ? "CUDA" : "CPU")} " + @@ -271,6 +291,55 @@ else if (_method == "windows-service") } } + private string DockerRunPowerShellInstallCommand + { + get + { + var volume = "heimdall-agent-state-" + Slugify(SiteName); + var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; + return "$ErrorActionPreference = 'Stop'; " + + "docker pull " + PowerShellQuote(image ?? "") + "; if ($LASTEXITCODE -ne 0) { throw 'docker pull failed' }; " + + "docker volume create " + PowerShellQuote(volume) + "; if ($LASTEXITCODE -ne 0) { throw 'docker volume create failed' }; " + + "docker run --rm --user 0:0 --entrypoint chown -v " + PowerShellQuote(volume + ":/state") + " " + + PowerShellQuote(image ?? "") + " -R 1654:1654 /state; if ($LASTEXITCODE -ne 0) { throw 'state volume initialization failed' }"; + } + } + + private string DockerRunPowerShellCommand + { + get + { + var name = "heimdall-agent-" + Slugify(SiteName); + var volume = "heimdall-agent-state-" + Slugify(SiteName); + var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; + var args = new List { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" }; + if (_useGpuImage) args.AddRange(["--gpus", "all"]); + args.AddRange([ + "-e", "Agent__CentralUrl=" + CentralUrl, + "-e", "Agent__SiteToken=" + SiteToken, + "-e", "Agent__AgentName=" + SiteName, + "-e", "Agent__StateDirectory=/var/lib/heimdall", + "-e", "ASPNETCORE_URLS=http://+:8080", + "-e", "Agent__InferenceExecutionProvider=" + (_useGpuImage ? "CUDA" : "CPU"), + "-e", "Agent__UpdatePublicKeyPem=" + (_updatePublicKeyPem ?? ""), + "-v", volume + ":/var/lib/heimdall", + image ?? "" + ]); + return "$dockerArgs = @(" + string.Join(",", args.Select(PowerShellQuote)) + "); & docker @dockerArgs; if ($LASTEXITCODE -ne 0) { throw 'docker run failed' }"; + } + } + + private string DockerRunPowerShellCheckCommand + { + get + { + var name = "heimdall-agent-" + Slugify(SiteName); + return "$status = docker inspect --format '{{.State.Status}}' " + PowerShellQuote(name) + "; " + + "if ($LASTEXITCODE -ne 0) { throw 'container inspect failed' }; $status; " + + "docker logs --tail 50 " + PowerShellQuote(name) + "; if ($LASTEXITCODE -ne 0) { throw 'container logs failed' }"; + } + } + private string LinuxInstallCommand(bool service) { var baseUrl = CentralUrl.TrimEnd('/'); diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index ec33ac9..a98b8dc 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -4072,7 +4072,7 @@ Check - Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest. + Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)". The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot. @@ -4083,6 +4083,15 @@ Docker Run + + Install (PowerShell) + + + Run (PowerShell) + + + Check (PowerShell) + Use NVIDIA GPU inference diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index ec8e908..a5572f2 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4072,7 +4072,7 @@ Vérifier - Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. + Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)". L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage. @@ -4083,6 +4083,15 @@ Docker Run + + Installer (PowerShell) + + + Démarrer (PowerShell) + + + Vérifier (PowerShell) + Utiliser l’inférence GPU NVIDIA diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index cd2ffe4..7260461 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4072,7 +4072,7 @@ Check - Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest. + Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)". The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot. @@ -4083,6 +4083,15 @@ Docker Run + + Install (PowerShell) + + + Run (PowerShell) + + + Check (PowerShell) + Use NVIDIA GPU inference From 2d28771945c97d2948551210f9725bfab2fdb07c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 13:02:38 +0100 Subject: [PATCH 4/8] fix(web): avoid error notification for missing detail records (#303) Co-authored-by: Arnaud Dartois --- skills/detail-route-not-found/SKILL.md | 25 +++++++++++++++ .../Components/Pages/AgentDetail.razor | 7 ++++ .../Components/Pages/CameraDetail.razor | 18 ++++++++--- .../Components/Pages/PersonDetailPage.razor | 13 ++++++-- .../Components/Pages/AgentDetailTests.cs | 32 +++++++++++++++++++ .../Components/Pages/CameraDetailTests.cs | 17 ++++++++++ .../Components/Pages/PersonDetailPageTests.cs | 10 +++--- 7 files changed, 111 insertions(+), 11 deletions(-) create mode 100644 skills/detail-route-not-found/SKILL.md diff --git a/skills/detail-route-not-found/SKILL.md b/skills/detail-route-not-found/SKILL.md new file mode 100644 index 0000000..ecee02f --- /dev/null +++ b/skills/detail-route-not-found/SKILL.md @@ -0,0 +1,25 @@ +--- +name: detail-route-not-found +description: Keep Heimdall detail pages consistent when an API object no longer exists. +--- + +# Missing objects on detail routes + +Use this workflow when a detail page already has an explicit “not found” state and an API read can return HTTP 404. Current routes covered are Agent (`AgentDetail.razor`), Camera (`CameraDetail.razor`), and Person (`PersonDetailPage.razor`). + +## Implementation + +- Keep the API client's normal `GetFromJsonAsync` behavior. A 404 raises `HttpRequestException` with `StatusCode == NotFound`. Agent and Camera resource-boundary checks intentionally return 403 for missing or out-of-scope records; treat that expected privacy response like the existing not-found rendering too. Person reads use 404. +- Preserve the generic error notification for unexpected failures. Do not treat 401, server, timeout, or malformed-response errors as “not found”. +- Do not fetch dependent page data after the primary object is absent. In particular, Camera must not load events, recordings, snapshots, or start periodic refresh, and Person must not load faces, vehicles, or events. +- Keep authorization and API responses unchanged. The UI behavior handles stale links and objects deleted between navigation and load. + +## Acceptance + +1. Add a component test for each route with a synthetic UUID and its expected hidden/missing response (Agent/Camera 403, Person 404). +2. Assert the existing not-found state is rendered, no snackbar is shown, and no dependent API call is made. +3. Retain or add an unexpected HTTP failure check proving the generic notification still appears. +4. Run the focused Web tests and Web build. +5. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`; verify all three routes through the app boundary using isolated synthetic data and record exact project/image cleanup evidence. + +The route-level checks require an authenticated synthetic account. Do not create or retain real people, cameras, Agents, or camera connection data for acceptance. diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 9e731af..81c3faa 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -902,10 +902,17 @@ else _ = LoadUpdateInfoAsync(); } } + catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex)) + { + // Le filtre d'accès renvoie 403 pour masquer un agent absent ou non accessible. + } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _loading = false; } } + private static bool IsMissingOrHiddenResource(HttpRequestException exception) => + exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden; + private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged); private async Task LoadMetricHistoryAsync(string range) diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index ff259ae..1110c07 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -372,14 +372,24 @@ else _eventRecordingEnabled = _camera.EventRecordingEnabled; } } + catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex)) + { + // Le filtre d'accès renvoie 403 pour masquer une caméra absente ou non accessible. + } catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); } finally { _loading = false; } - await LoadEventsAsync(); - await LoadRecordingsAsync(); - await LoadLatestSnapshotAsync(); + if (_camera is not null) + { + await LoadEventsAsync(); + await LoadRecordingsAsync(); + await LoadLatestSnapshotAsync(); + } } + private static bool IsMissingOrHiddenResource(HttpRequestException exception) => + exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden; + private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged); // L'auto-refresh démarre après le premier rendu : une boucle infinie @@ -389,7 +399,7 @@ else protected override async Task OnAfterRenderAsync(bool firstRender) { - if (firstRender && !_autoRefreshStarted) + if (firstRender && !_autoRefreshStarted && _camera is not null) { _autoRefreshStarted = true; await StartAutoRefresh(); diff --git a/src/Heimdall.Web/Components/Pages/PersonDetailPage.razor b/src/Heimdall.Web/Components/Pages/PersonDetailPage.razor index b767198..f5272c8 100644 --- a/src/Heimdall.Web/Components/Pages/PersonDetailPage.razor +++ b/src/Heimdall.Web/Components/Pages/PersonDetailPage.razor @@ -309,12 +309,19 @@ else { _person = await Api.GetPersonAsync(Id); } + catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + // La vue dédiée affiche l'état introuvable sans lancer les lectures associées. + } catch { Snackbar.Add(Text["PersonDetailPage_OperationFailed"], Severity.Error); } finally { _loading = false; } - await LoadFaces(); - await LoadVehicles(); - await LoadEvents(); + if (_person is not null) + { + await LoadFaces(); + await LoadVehicles(); + await LoadEvents(); + } } private async Task LoadFaces() diff --git a/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs index 84da926..c1efe9e 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs @@ -13,6 +13,38 @@ public class AgentDetailTests : PageTestBase { private static readonly Guid AgentId = Guid.NewGuid(); + [Fact] + public void AgentDetail_AgentIntrouvable_NAffichePasDErreur() + { + // ResourceAccessFilter deliberately returns 403 to hide missing agents. + Handler.OnGet($"api/agents/{AgentId}", System.Net.HttpStatusCode.Forbidden); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("introuvable"); + Services.GetRequiredService().ShownSnackbars.ShouldBeEmpty(); + Handler.Requests.ShouldHaveSingleItem(); + }); + } + + [Fact] + public void AgentDetail_ErreurServeur_AfficheSnackbarErreur() + { + Handler.OnGet($"api/agents/{AgentId}", System.Net.HttpStatusCode.InternalServerError); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("introuvable"); + Services.GetRequiredService().ShownSnackbars.ShouldNotBeEmpty(); + }); + } + private static AgentItem Agent() => new() { Id = AgentId, diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index f2cae1e..63e7ddd 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -28,6 +28,23 @@ public class CameraDetailTests : PageTestBase private void HandlerCamera(CameraItem camera) => Handler.OnGet("api/cameras/", camera); + [Fact] + public void CameraDetail_CameraIntrouvable_NAffichePasDErreurEtNeChargePasLesDetails() + { + // ResourceAccessFilter deliberately returns 403 to hide missing cameras. + Handler.OnGet("api/cameras/", System.Net.HttpStatusCode.Forbidden); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("introuvable"); + Services.GetRequiredService().ShownSnackbars.ShouldBeEmpty(); + Handler.Requests.ShouldHaveSingleItem(); + }); + } + [Fact] public async Task PlateAssociationConfirmation_PostsCameraPlateEventAndVehicleIds() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs index d20efbc..b5ae75d 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs @@ -98,14 +98,16 @@ public class PersonDetailPageTests : PageTestBase public void PersonDetail_PersonneIntrouvable_AfficheAlerte() { Handler.OnGet("api/persons/", System.Net.HttpStatusCode.NotFound); - Handler.OnGet($"api/persons/{PersonId}/faces", new List()); - Handler.OnGet("api/vehicles", new List()); - Handler.OnGet("api/events", new EventPageResult([], 0, 1, 50)); LoginAs(); var cut = RenderPage(p => p.Add(x => x.Id, PersonId)); - cut.WaitForAssertion(() => cut.Markup.ShouldContain("Personne introuvable")); + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Personne introuvable"); + Services.GetRequiredService().ShownSnackbars.ShouldBeEmpty(); + Handler.Requests.ShouldHaveSingleItem(); + }); } [Fact] From b3d5ea5adda4dbde490d22b7a7ad22a5300123c4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 13:14:46 +0100 Subject: [PATCH 5/8] docs: align PR template with Gitea issue workflow (#306) Co-authored-by: Arnaud Dartois --- .gitea/PULL_REQUEST_TEMPLATE.md | 2 +- skills/gitea-ticket-workflow/SKILL.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md index f7788c6..f954d92 100644 --- a/.gitea/PULL_REQUEST_TEMPLATE.md +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -6,7 +6,7 @@ Refs # ## Vérification - + - [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images - [ ] Contrôles NuGet et images sans HIGH/CRITICAL diff --git a/skills/gitea-ticket-workflow/SKILL.md b/skills/gitea-ticket-workflow/SKILL.md index db09d4e..2f3bf7e 100644 --- a/skills/gitea-ticket-workflow/SKILL.md +++ b/skills/gitea-ticket-workflow/SKILL.md @@ -79,6 +79,7 @@ Render long historical logs as a clearly separated `
Historique ## Pull requests and closure - Before opening/updating a PR, verify the issue number, link, acceptance criteria, focused skill, and test/acceptance evidence are present. +- Keep `.gitea/PULL_REQUEST_TEMPLATE.md` aligned with this workflow: request the linked Gitea issue and observed CI/acceptance evidence; never direct contributors to update a markdown backlog. - Use `Closes #N` only when the PR completes every criterion owned by that issue. For partial work use `Refs #N` and leave the issue open with unchecked criteria and evidence updated. - Gitea closes a `Closes #N` issue when the PR merges. After merge, verify the issue state changed; if not, close it manually only after checking all criteria and posting the merge/CI/acceptance evidence. - Do not close tickets merely because code was merged when required acceptance (including the disposable Compose recipe, CI gate, external deployment, camera, storage, or release run) remains outstanding. Create a separate validation issue if code delivery and external validation have different owners or timelines. From adf8d73476dc61bde71faf276ea0f1c0a6506824 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 18:37:45 +0100 Subject: [PATCH 6/8] fix(agent): observe mDNS UDP receive cancellation (#309) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Résumé Le propriétaire des sockets UDP mDNS annule et observe maintenant les tâches de réception avant de quitter leur portée. Les erreurs socket inattendues restent propagées à la frontière de découverte. Refs #301 ## Validation - `dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode` : réussi. - Test de régression ciblé annulation / erreur socket : 1/1 réussi; suite `Heimdall.Agent.Tests` : 440/440 réussis. - Compose jetable `heimdall-agent-mdns-udp-retry-20261108162648-13721` : restore verrouillé réussi et tests ciblés : 9/9 réussis. - Nettoyage Compose vérifié : conteneurs, volumes et réseau absents; images construites localement : aucune; image SDK partagée conservée. - CI du commit `ee865931` : détection de portée réussie; build/tests et CI policy à revérifier après mise à jour de branche. - L’observation GlitchTip post-déploiement pendant 7 jours reste ouverte; le ticket reste donc référencé par `Refs #301`. Skill mise à jour : `skills/mdns-camera-discovery/SKILL.md`. Reviewed-on: https://sources.tordais.cc/arnaud.dartois/Heimdall/pulls/309 Co-authored-by: Arnaud Dartois --- skills/mdns-camera-discovery/SKILL.md | 6 +- src/Heimdall.Mdns/Heimdall.Mdns.csproj | 6 +- src/Heimdall.Mdns/MdnsClient.cs | 100 +++++++++++------- .../HomeKitMdnsProbeTests.cs | 13 +++ 4 files changed, 86 insertions(+), 39 deletions(-) diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index 263cd36..e3caf7c 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -24,8 +24,12 @@ Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md - The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists. - The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping. +## UDP receive lifetime at shutdown + +`MdnsClient` owns each `UdpClient` for one probe/discovery call. When a receive window expires, cancel the receive with a linked token and await its task before leaving the socket scope; this observes the expected cancellation and prevents a pending receive task from surfacing later as `UnobservedTaskException`. Do not swallow unrelated `SocketException` failures: keep them observable (or log a sanitized exception type at the discovery boundary). The focused regression test `ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures` covers expected cancellation and an unexpected socket failure. Run the focused and full `Heimdall.Agent.Tests` suites after changes to this lifecycle. + ## Disposable Compose -Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. +Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its recursively referenced source projects, plus root build props/targets and `global.json`, into a temporary archive outside the repository. Mount the archive read-only, extract it inside the SDK container with `tar --no-same-owner` into `/tmp` (the container filesystem there is writable), and restore with `--locked-mode`. For mDNS lifecycle changes, run `HomeKitMdnsProbeTests` and the focused receive-cancellation regression test; otherwise run the relevant focused Agent tests. Use a unique Compose project, project-scoped NuGet package volume, and isolated bridge; publish no ports and never use host networking. The container is read-only except for `/tmp`, `/root/.local/share/NuGet` (NuGet HTTP cache), and the project-scoped package volume. Do not mark the bridge `internal`: locked restore may need NuGet network access; the bridge remains isolated from host/production networks. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the archive and Compose file, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`. diff --git a/src/Heimdall.Mdns/Heimdall.Mdns.csproj b/src/Heimdall.Mdns/Heimdall.Mdns.csproj index 05ecbf0..ee33f4d 100644 --- a/src/Heimdall.Mdns/Heimdall.Mdns.csproj +++ b/src/Heimdall.Mdns/Heimdall.Mdns.csproj @@ -10,4 +10,8 @@ - \ No newline at end of file + + + + + diff --git a/src/Heimdall.Mdns/MdnsClient.cs b/src/Heimdall.Mdns/MdnsClient.cs index 07f743d..525fda5 100644 --- a/src/Heimdall.Mdns/MdnsClient.cs +++ b/src/Heimdall.Mdns/MdnsClient.cs @@ -52,44 +52,46 @@ public sealed class MdnsClient : IMdnsClient, IDisposable await udpClient.SendAsync(query, ct).ConfigureAwait(false); // Try to receive within timeout - var receiveTask = udpClient.ReceiveAsync(ct).AsTask(); - var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false); - - if (completedTask != receiveTask) + using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + receiveCts.CancelAfter(options.Timeout); + var receiveTask = udpClient.ReceiveAsync(receiveCts.Token).AsTask(); + try { - if (retry < options.MaxRetries) - continue; // retry - break; // timeout, try next service type - } + var result = await receiveTask.ConfigureAwait(false); + var response = MdnsResponse.Parse(result.Buffer); - var result = await receiveTask.ConfigureAwait(false); - var response = MdnsResponse.Parse(result.Buffer); - - if (response is not null) - { - // If it's a HomeKit device, parse HomeKit-specific info - if (response.Type == MdnsConstants.TypePtr && - response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true) + if (response is not null) { + // If it's a HomeKit device, parse HomeKit-specific info + if (response.Type == MdnsConstants.TypePtr && + response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true) + { + return new MdnsProbeResult + { + Target = target, + ServiceType = response.Name, + InstanceName = response.PtrName, + HostName = response.Address?.ToString(), + ResolvedAddress = response.Address, + HomeKitInfo = ParseHomeKitInfo(target, response) + }; + } + return new MdnsProbeResult { Target = target, ServiceType = response.Name, InstanceName = response.PtrName, HostName = response.Address?.ToString(), - ResolvedAddress = response.Address, - HomeKitInfo = ParseHomeKitInfo(target, response) + ResolvedAddress = response.Address }; } - - return new MdnsProbeResult - { - Target = target, - ServiceType = response.Name, - InstanceName = response.PtrName, - HostName = response.Address?.ToString(), - ResolvedAddress = response.Address - }; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + if (retry < options.MaxRetries) + continue; // timeout, retry + break; // timeout, try next service type } } catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused) @@ -167,17 +169,29 @@ public sealed class MdnsClient : IMdnsClient, IDisposable while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil) { - var receiveTask = udp.ReceiveAsync(ct).AsTask(); - var completed = await Task.WhenAny(receiveTask, Task.Delay(options.ListenWindow, ct)).ConfigureAwait(false); + using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + var remaining = listenUntil - DateTime.UtcNow; + if (remaining <= TimeSpan.Zero) + break; + receiveCts.CancelAfter(remaining); + var receiveTask = udp.ReceiveAsync(receiveCts.Token).AsTask(); + try + { + var result = await receiveTask.ConfigureAwait(false); + var replies = ParsePacket(result.Buffer); - if (completed != receiveTask) - break; // no more replies expected - - var result = await receiveTask.ConfigureAwait(false); - var replies = ParsePacket(result.Buffer); - - if (replies.Count > 0) - collected.AddRange(replies); + if (replies.Count > 0) + collected.AddRange(replies); + } + catch (SocketException ex) + { + _logger.LogWarning("mDNS multicast receive failed (error type {ErrorType})", ex.GetType().Name); + break; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + break; // listen window elapsed; receive cancellation is observed here + } } // Build devices from collected replies @@ -201,6 +215,18 @@ public sealed class MdnsClient : IMdnsClient, IDisposable } } + internal static async Task ObserveCanceledReceiveAsync(Task receiveTask, CancellationToken operationToken) + { + try + { + await receiveTask.ConfigureAwait(false); + } + catch (OperationCanceledException) when (!operationToken.IsCancellationRequested) + { + // The receive was canceled because its individual timeout elapsed. + } + } + // ─── DNS packet parsing (with compression pointers) ────────────── private sealed record MdnsReply( diff --git a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs index 1834f3d..14b9264 100644 --- a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs +++ b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs @@ -1,5 +1,6 @@ using System.Text; using System.Net; +using System.Net.Sockets; using Heimdall.Agent.Services; using Heimdall.Application.DTOs; using Heimdall.Mdns; @@ -12,6 +13,18 @@ namespace Heimdall.Agent.Tests; public class HomeKitMdnsProbeTests { + [Fact] + public async Task ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures() + { + var canceledReceive = Task.FromCanceled(new CancellationToken(canceled: true)); + + await Should.NotThrowAsync(() => MdnsClient.ObserveCanceledReceiveAsync(canceledReceive, CancellationToken.None)); + + var socketFailure = Task.FromException(new SocketException((int)SocketError.NetworkDown)); + await Should.ThrowAsync( + () => MdnsClient.ObserveCanceledReceiveAsync(socketFailure, CancellationToken.None)); + } + [Fact] public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow() { From e042b832d81d2fec780134303d45eeb14de6ea7e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 18:57:33 +0100 Subject: [PATCH 7/8] fix(web): open a notification center from the header (#307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Résumé La cloche du bandeau ouvre `/notifications`, qui affiche les notifications du compte courant et permet leur lecture individuelle ou globale. Closes #302 ## Validation - `dotnet restore tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --locked-mode` : réussi. - Tests bUnit ciblés `NotificationsPageTests` : 2/2 réussis; suite Web Release : 438/438 réussis avant merge concurrent de `main`. - Build Web Release : 0 avertissement, 0 erreur avant le merge concurrent. - Compose jetable `heimdall-notifications-acceptance-20261108140737-223989` : événement synthétique, isolation Admin/Viewer, lecture simple/globale, refus anonyme et compteur 0 vérifiés via API. - Navigateur Orca : clic de la cloche depuis `/profile`, contenu et badge sur `/notifications`, lecture simple et état vide Viewer vérifiés. `/events` n’a pas été chargé. - Nettoyage vérifié : conteneurs/volumes/réseaux absents et tags exacts supprimés pour les projets jetables. Voir le commentaire de l’issue pour les noms et tags. - Après merge concurrent de `main`, deux reruns locaux ont échoué par manque de ressources (`Out of memory`), pas par échec de test. CI du commit courant à surveiller avant fusion. Reviewed-on: https://sources.tordais.cc/arnaud.dartois/Heimdall/pulls/307 Co-authored-by: Arnaud Dartois --- skills/notification-center/SKILL.md | 17 ++++ .../Components/Pages/NotificationsPage.razor | 88 +++++++++++++++++++ .../Components/Shared/NotificationBadge.razor | 2 +- .../Localization/SharedResources.fr.resx | 6 ++ .../Localization/SharedResources.resx | 6 ++ .../Services/HeimdallApiClient.cs | 19 ++++ .../Pages/NotificationsPageTests.cs | 32 +++++++ 7 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 skills/notification-center/SKILL.md create mode 100644 src/Heimdall.Web/Components/Pages/NotificationsPage.razor create mode 100644 tests/Heimdall.Web.Tests/Components/Pages/NotificationsPageTests.cs diff --git a/skills/notification-center/SKILL.md b/skills/notification-center/SKILL.md new file mode 100644 index 0000000..39b7ab0 --- /dev/null +++ b/skills/notification-center/SKILL.md @@ -0,0 +1,17 @@ +--- +name: notification-center +description: Implement and accept the authenticated Heimdall in-app notification center. +--- + +# Notification center + +The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser. + +## Acceptance + +1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests. +2. In disposable Central + PostgreSQL Compose, create only synthetic notifications for the disposable admin, open `/notifications` from the header bell, confirm notification content appears and `/events` is not loaded. +3. Mark one item read and all items read; verify displayed state and unread badge refresh. Confirm empty and API failure states render. +4. Use unique Compose project, generated credentials, loopback port, and project-owned image tag. Follow `compose-disposable-recipe` exactly: remove only that project and exact local tag, verify project containers/volumes/networks and image tag are absent, and retain shared images. + +The empty and failed API states have focused bUnit coverage in `NotificationsPageTests`. Simulate the API error with an HTTP 500 response for `GET /api/notifications`; taking PostgreSQL offline also breaks server-side session validation before the page can handle the notification request. diff --git a/src/Heimdall.Web/Components/Pages/NotificationsPage.razor b/src/Heimdall.Web/Components/Pages/NotificationsPage.razor new file mode 100644 index 0000000..1ea34a7 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/NotificationsPage.razor @@ -0,0 +1,88 @@ +@page "/notifications" +@using Heimdall.Application.DTOs +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject NotificationsHubClient Hub +@inject UiText Text +@inject ISnackbar Snackbar + +@Text["NotificationsPage_Title"] +@if (_loading) +{ + +} +else if (_failed) +{ + @Text["NotificationsPage_Failed"] +} +else if (_items.Count == 0) +{ + @Text["NotificationsPage_Empty"] +} +else +{ +
+ + @Text["NotificationsPage_MarkAllRead"] + +
+ @foreach (var item in _items) + { + +
+
+ @item.Title + @item.Message + @item.CreatedAt.ToLocalTime().ToString("g") +
+ @if (!item.IsRead) + { + @Text["NotificationsPage_MarkRead"] + } +
+
+ } +} + +@code { + private List _items = []; + private bool _loading = true; + private bool _failed; + + protected override async Task OnInitializedAsync() => await LoadAsync(); + + private async Task LoadAsync() + { + _loading = true; + _failed = false; + try + { + var result = await Api.GetNotificationsAsync(); + _items = result?.Items.ToList() ?? []; + _failed = result is null; + } + catch (HttpRequestException) { _failed = true; } + finally { _loading = false; } + } + + private async Task MarkReadAsync(Guid id) + { + if (await Api.MarkNotificationAsReadAsync(id)) + { + await LoadAsync(); + await Hub.RefreshUnreadCountAsync(); + } + else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error); + } + + private async Task MarkAllReadAsync() + { + if (await Api.MarkAllNotificationsAsReadAsync()) + { + await LoadAsync(); + await Hub.RefreshUnreadCountAsync(); + } + else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error); + } +} diff --git a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor index c38e9fa..2e3f787 100644 --- a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor +++ b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor @@ -10,7 +10,7 @@ Visible="@(Hub.UnreadCount > 0)"> + OnClick="@(() => Navigation.NavigateTo("/notifications"))" /> diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index a5572f2..9dcebe2 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4133,4 +4133,10 @@ Confirmer le lien L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné. Aucun véhicule correspondant trouvé. L’observation reste sans lien. + Notifications + Impossible de charger les notifications. Réessayez. + Vous n’avez aucune notification. + Tout marquer comme lu + Marquer comme lu + Impossible de mettre à jour la notification. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 7260461..bf1fd06 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4133,4 +4133,10 @@ Confirmer le lien L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné. Aucun véhicule correspondant trouvé. L’observation reste sans lien. + Notifications + Notifications could not be loaded. Try again. + You have no notifications. + Mark all as read + Mark as read + The notification could not be updated. diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 0b65b7c..99a4e16 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -1037,6 +1037,25 @@ public class HeimdallApiClient : IDisposable // ─── Notification Config ───────────────────────────────────────── + public async Task?> GetNotificationsAsync(int page = 1, int pageSize = 20) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/notifications?page={page}&pageSize={pageSize}", Json); + } + + public async Task MarkNotificationAsReadAsync(Guid id) + { + using var response = await CreateClient().PostAsync($"api/notifications/{id}/read", content: null); + return response.IsSuccessStatusCode; + } + + public async Task MarkAllNotificationsAsReadAsync() + { + using var response = await CreateClient().PostAsync("api/notifications/mark-all-read", content: null); + return response.IsSuccessStatusCode; + } + public async Task GetNotificationConfigAsync() { var client = CreateClient(); diff --git a/tests/Heimdall.Web.Tests/Components/Pages/NotificationsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/NotificationsPageTests.cs new file mode 100644 index 0000000..3e8e947 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Components/Pages/NotificationsPageTests.cs @@ -0,0 +1,32 @@ +using Bunit; +using Bunit.TestDoubles; +using Heimdall.Application.DTOs; +using Heimdall.Web.Components.Pages; +using Shouldly; + +namespace Heimdall.Web.Tests.Components.Pages; + +public sealed class NotificationsPageTests : PageTestBase +{ + [Fact] + public void NotificationsPage_EmptyList_ShowsEmptyState() + { + Handler.OnGet("api/notifications", new PagedResult([], 0, 1, 20)); + LoginAs(); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Vous n’avez aucune notification.")); + } + + [Fact] + public void NotificationsPage_ApiFailure_ShowsErrorState() + { + Handler.OnGet("api/notifications", System.Net.HttpStatusCode.InternalServerError); + LoginAs(); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Impossible de charger les notifications. Réessayez.")); + } +} From 1d60f046910eb9c62a5173ddad79da582ed14d2e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 20:03:03 +0100 Subject: [PATCH 8/8] fix(auth): safely report cookie sign-in failures (#310) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Résumé Le flux navigateur reçoit maintenant un résultat HTTP explicite du pont cookie; les échecs de cookie sont diagnostiqués sans exposer les messages d’exception ni les données de session. La validation 2FA par code de récupération recharge également l’utilisateur après rotation du security stamp avant d’émettre la session. ## Issue Refs #304 — l’observation GlitchTip post-déploiement reste nécessaire avant résolution. ## Travail effectué - `/_auth/signin` renvoie des erreurs génériques et journalise uniquement l’étape et le type d’exception. - Le pont JavaScript retourne le statut HTTP; les interruptions de circuit sont distinctes des réponses non-2xx. - Suppression des adresses e-mail des journaux auth/2FA. - Correction du chemin code de récupération 2FA pour émettre un jeton cohérent avec le security stamp actualisé. - Ajout de tests unitaires et d’intégration; documentation dans `skills/heimdall-identity/SKILL.md`. ## Preuves - `dotnet restore tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --locked-mode` — réussi. - `dotnet restore tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --locked-mode` — réussi. - `AuthHelperTests` — 6/6 réussis. - Tests d’intégration ciblés 2FA/recovery-cookie/TOTP-cookie/token malformé — 3/3 réussis. - Acceptance Compose source-built `heimdall-auth-cookie-20261108170745-28547` — bootstrap 200, TOTP 200, cookie sign-in 200, API avec cookie 200, jeton malformé 401 générique, secrets absents des logs. Nettoyage vérifié: conteneurs/volumes/réseau absents et tag `heimdall:heimdall-auth-cookie-20261108170745-28547-central` supprimé. - Analyse de l’événement GlitchTip: le circuit navigateur se déconnecte avant toute trace HTTP observée de `/_auth/signin`; la cause de cette occurrence production reste donc non démontrée. La correction améliore la visibilité sûre et le flux synthétique, sans prétendre reproduire cet événement. ## À suivre Après déploiement de ce commit, observer GlitchTip pendant au moins sept jours et vérifier si HEIMDALL-DU réapparaît. Ne pas résoudre l’issue avant cette preuve réelle. Reviewed-on: https://sources.tordais.cc/arnaud.dartois/Heimdall/pulls/310 Co-authored-by: Arnaud Dartois --- skills/heimdall-identity/SKILL.md | 1 + .../Commands/Verify2fa/Verify2faHandler.cs | 4 + src/Heimdall.Web/Components/Pages/Login.razor | 31 +++---- .../Components/Pages/Profile.razor | 3 +- src/Heimdall.Web/Components/Pages/Setup.razor | 3 +- src/Heimdall.Web/Heimdall.Web.csproj | 1 + src/Heimdall.Web/Program.cs | 22 ++++- src/Heimdall.Web/Services/AuthHelper.cs | 25 ++++-- src/Heimdall.Web/wwwroot/js/auth.js | 4 +- .../Controllers/AuthSessionSecurityTests.cs | 87 ++++++++++++++++++- .../Components/Pages/LoginTests.cs | 8 +- .../Services/AuthHelperTests.cs | 70 +++++++++++++++ 12 files changed, 228 insertions(+), 31 deletions(-) create mode 100644 tests/Heimdall.Web.Tests/Services/AuthHelperTests.cs diff --git a/skills/heimdall-identity/SKILL.md b/skills/heimdall-identity/SKILL.md index d644e54..5a0ed82 100644 --- a/skills/heimdall-identity/SKILL.md +++ b/skills/heimdall-identity/SKILL.md @@ -15,6 +15,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git - Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed. - Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change. - Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation. +- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details. - Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled. - Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails. - Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint. diff --git a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs index 2e9a139..249d666 100644 --- a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs @@ -82,6 +82,10 @@ public class Verify2faHandler : IRequestHandler.Failure("Unable to complete sign-in"); } + var refreshedUser = await _userManager.FindByIdAsync(user.Id, ct).ConfigureAwait(false); + if (refreshedUser is null) + return ServiceResult.Failure("Unable to complete sign-in"); + user = refreshedUser; _logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId); } diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index a4d6a0d..47e409b 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -131,19 +131,19 @@ { _loading = true; _errorMessage = ""; - Logger.LogInformation("Login attempt for email: {Email}", _email); + Logger.LogInformation("Login attempt"); try { var result = await Api.LoginAsync(_email, _password); if (result is null) { - Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email); + Logger.LogWarning("Login failed: invalid credentials"); _errorMessage = Text["LoginPage_InvalidCredentials"]; return; } - Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa); + Logger.LogInformation("Login succeeded. Requires 2FA: {Requires2fa}", result.Requires2fa); // Check if 2FA is required if (result.Requires2fa) @@ -152,7 +152,7 @@ _password = ""; _requires2fa = true; _loading = false; - Logger.LogInformation("2FA required for {Email}", _email); + Logger.LogInformation("2FA required"); return; } @@ -160,7 +160,7 @@ } catch (Exception ex) { - Logger.LogError(ex, "Login error for {Email}", _email); + Logger.LogError("Login flow failed (error type {ErrorType})", ex.GetType().Name); _errorMessage = UiErrors.OperationFailed(); } finally { _loading = false; } @@ -170,31 +170,31 @@ { if (string.IsNullOrWhiteSpace(_twoFactorCode)) { - Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email); + Logger.LogWarning("2FA verification attempted with an empty code"); _errorMessage = Text["LoginPage_TwoFactorCodeRequired"]; return; } _loading = true; _errorMessage = ""; - Logger.LogInformation("2FA verification attempt for {Email}", _email); + Logger.LogInformation("2FA verification attempt"); try { var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim()); if (result is null) { - Logger.LogWarning("2FA verification failed for {Email}", _email); + Logger.LogWarning("2FA verification failed"); _errorMessage = Text["LoginPage_InvalidTwoFactorCode"]; return; } - Logger.LogInformation("2FA verification successful for {Email}", _email); + Logger.LogInformation("2FA verification succeeded"); await CompleteAuthAsync(result); } catch (Exception ex) { - Logger.LogError(ex, "2FA verification error for {Email}", _email); + Logger.LogError("2FA verification flow failed (error type {ErrorType})", ex.GetType().Name); _errorMessage = UiErrors.OperationFailed(); } finally { _loading = false; } @@ -202,7 +202,7 @@ private async Task CompleteAuthAsync(AuthResponse result) { - Logger.LogInformation("Completing authentication for {Email}", _email); + Logger.LogInformation("Completing authentication"); // Update Blazor-level auth state await AuthStateProvider.NotifyLoginAsync(result); @@ -211,23 +211,24 @@ var cookieOk = true; if (!string.IsNullOrEmpty(result.AccessToken)) { - Logger.LogDebug("Creating auth cookie for {Email}", _email); + Logger.LogDebug("Creating auth cookie"); cookieOk = await AuthHelper.SignInAsync(JsRuntime, + Logger, AuthHelper.CreateSignInPayload(result.AccessToken)); } else { - Logger.LogWarning("No access token in auth response for {Email}", _email); + Logger.LogWarning("No access token in auth response"); } if (!cookieOk) { - Logger.LogError("Failed to create auth cookie for {Email}", _email); + Logger.LogError("Failed to create auth cookie"); _errorMessage = Text["LoginPage_AuthSessionFailed"]; return; } - Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl); + Logger.LogInformation("Authentication completed successfully, redirecting to {ReturnUrl}", _returnUrl); Snackbar.Add(Text["LoginPage_SignInSucceeded"], Severity.Success); Navigation.NavigateTo(_returnUrl); } diff --git a/src/Heimdall.Web/Components/Pages/Profile.razor b/src/Heimdall.Web/Components/Pages/Profile.razor index 13a6649..1cb1f10 100644 --- a/src/Heimdall.Web/Components/Pages/Profile.razor +++ b/src/Heimdall.Web/Components/Pages/Profile.razor @@ -11,6 +11,7 @@ @inject ISnackbar Snackbar @inject HeimdallAuthStateProvider AuthProvider @inject IJSRuntime JS +@inject Microsoft.Extensions.Logging.ILogger Logger @@ -470,7 +471,7 @@ else if (_profile is not null) return; } await AuthProvider.NotifyLoginAsync(renewedSession); - if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken))) + if (!await AuthHelper.SignInAsync(JS, Logger, AuthHelper.CreateSignInPayload(renewedSession.AccessToken))) { _2faError = Text["OperationFailed"]; _show2faDialog = true; diff --git a/src/Heimdall.Web/Components/Pages/Setup.razor b/src/Heimdall.Web/Components/Pages/Setup.razor index bb3c5a3..dc741fe 100644 --- a/src/Heimdall.Web/Components/Pages/Setup.razor +++ b/src/Heimdall.Web/Components/Pages/Setup.razor @@ -5,6 +5,7 @@ @inject HeimdallAuthStateProvider AuthStateProvider @inject NavigationManager Navigation @inject IJSRuntime JsRuntime +@inject Microsoft.Extensions.Logging.ILogger Logger
@@ -96,7 +97,7 @@ } await AuthStateProvider.NotifyLoginAsync(result); var cookieOk = !string.IsNullOrEmpty(result.AccessToken) && await AuthHelper.SignInAsync( - JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken)); + JsRuntime, Logger, AuthHelper.CreateSignInPayload(result.AccessToken)); if (!cookieOk) { _error = Text["SetupAdmin_AutoLoginFailed"]; diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index b7b0df0..9fc0abf 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index a12e411..06e74c4 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -974,11 +974,13 @@ public partial class Program { if (string.IsNullOrEmpty(request.AccessToken)) return Results.BadRequest(new { error = "AccessToken is required" }); + var failureStage = "token validation"; try { var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(request.AccessToken, GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _); + failureStage = "account session validation"; if (!await ValidateAccountSessionAsync(principal, httpContext)) return Results.Unauthorized(); var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; @@ -1003,6 +1005,7 @@ public partial class Program claims.Add(new Claim("permission", permission.Value)); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + failureStage = "cookie issuance"; await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { @@ -1013,7 +1016,24 @@ public partial class Program return Results.Ok(); } catch (SecurityTokenExpiredException) { return Results.Unauthorized(); } - catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); } + catch (SecurityTokenException ex) + { + logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name); + return Results.Unauthorized(); + } + catch (ArgumentException ex) when (failureStage == "token validation") + { + logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name); + return Results.Unauthorized(); + } + catch (Exception ex) + { + logger.LogError("Cookie sign-in failed during {FailureStage} (error type {ErrorType})", + failureStage, ex.GetType().Name); + return Results.Problem( + statusCode: StatusCodes.Status500InternalServerError, + title: "Authentication session could not be created"); + } }); app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => diff --git a/src/Heimdall.Web/Services/AuthHelper.cs b/src/Heimdall.Web/Services/AuthHelper.cs index 6efde04..f59c7a6 100644 --- a/src/Heimdall.Web/Services/AuthHelper.cs +++ b/src/Heimdall.Web/Services/AuthHelper.cs @@ -1,4 +1,5 @@ using Microsoft.JSInterop; +using Microsoft.Extensions.Logging; namespace Heimdall.Web.Services; @@ -7,18 +8,30 @@ internal static class AuthHelper { /// Creates the middleware-level auth cookie via JS interop. /// True if the sign-in HTTP call succeeded (2xx). - public static async Task SignInAsync(IJSRuntime jsRuntime, object user) + public static async Task SignInAsync(IJSRuntime jsRuntime, ILogger logger, object user) { try { - var ok = await jsRuntime.InvokeAsync("heimdallAuth.signIn", user); - if (!ok) - Console.Error.WriteLine("[AuthHelper] SignInAsync: /_auth/signin returned non-2xx status"); - return ok; + var statusCode = await jsRuntime.InvokeAsync("heimdallAuth.signIn", user); + if (statusCode is >= 200 and < 300) + return true; + + logger.LogWarning("Cookie sign-in endpoint returned HTTP status {StatusCode}", statusCode); + return false; + } + catch (JSDisconnectedException) + { + logger.LogInformation("Cookie sign-in was interrupted because the browser circuit disconnected"); + return false; + } + catch (JSException ex) + { + logger.LogWarning("Cookie sign-in JavaScript interop failed (error type {ErrorType})", ex.GetType().Name); + return false; } catch (Exception ex) { - Console.Error.WriteLine($"[AuthHelper] SignInAsync JS interop failed: {ex.Message}"); + logger.LogWarning("Cookie sign-in bridge failed (error type {ErrorType})", ex.GetType().Name); return false; } } diff --git a/src/Heimdall.Web/wwwroot/js/auth.js b/src/Heimdall.Web/wwwroot/js/auth.js index bb4a3fd..73a426f 100644 --- a/src/Heimdall.Web/wwwroot/js/auth.js +++ b/src/Heimdall.Web/wwwroot/js/auth.js @@ -11,9 +11,9 @@ window.heimdallAuth = { body: JSON.stringify(data), credentials: 'include' }); - return response.ok; + return response.status; } catch { - return false; + return 0; } }, diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs index 87fcd1e..291ef76 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs @@ -1,6 +1,8 @@ +using System.Buffers.Binary; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; +using System.Security.Cryptography; using Heimdall.Application.Auth.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Users.Commands.AssignRoles; @@ -75,11 +77,94 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres challenge.AccessToken.ShouldBeEmpty(); var response = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); response.StatusCode.ShouldBe(HttpStatusCode.OK); - (await response.Content.ReadFromJsonAsync())!.AccessToken.ShouldNotBeNullOrEmpty(); + var verifiedSession = (await response.Content.ReadFromJsonAsync())!; + verifiedSession.AccessToken.ShouldNotBeNullOrEmpty(); + + var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = verifiedSession.AccessToken }); + cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + await AssertCookieSessionAsync(cookieResponse); + var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } + [Fact] + public async Task Authenticator_2fa_success_emits_token_accepted_by_cookie_signin() + { + string code; + using (var scope = _factory.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var user = (await users.FindByIdAsync(_userId.ToString()))!; + (await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue(); + (await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue(); + var key = await users.GetAuthenticatorKeyAsync(user); + code = GenerateTotp(key!); + (await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue(); + } + + var challenge = await LoginAsync(); + challenge.Requires2fa.ShouldBeTrue(); + var verification = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new + { + challengeId = challenge.ChallengeId, + code + }); + verification.StatusCode.ShouldBe(HttpStatusCode.OK, await verification.Content.ReadAsStringAsync()); + var session = (await verification.Content.ReadFromJsonAsync())!; + session.AccessToken.ShouldNotBeNullOrEmpty(); + + var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = session.AccessToken }); + cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + await AssertCookieSessionAsync(cookieResponse); + } + + [Fact] + public async Task Cookie_signin_rejects_malformed_tokens_without_returning_validation_details() + { + var response = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = "not-a-jwt" }); + + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + var body = await response.Content.ReadAsStringAsync(); + body.ShouldNotContain("not-a-jwt"); + body.ShouldNotContain("IDX"); + } + + private async Task AssertCookieSessionAsync(HttpResponseMessage cookieResponse) + { + var cookie = cookieResponse.Headers.GetValues("Set-Cookie") + .Single(value => value.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0]; + var authenticatedRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); + authenticatedRequest.Headers.Add("Cookie", cookie); + (await _client.SendAsync(authenticatedRequest)).StatusCode.ShouldBe(HttpStatusCode.OK); + } + +#pragma warning disable CA5350 + private static string GenerateTotp(string base32Key) + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + var key = new List(); + var buffer = 0; + var bits = 0; + foreach (var character in base32Key.TrimEnd('=')) + { + buffer = (buffer << 5) | alphabet.IndexOf(character); + bits += 5; + if (bits < 8) continue; + bits -= 8; + key.Add((byte)(buffer >> bits)); + } + + Span message = stackalloc byte[8]; + BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30); + var hash = HMACSHA1.HashData(key.ToArray(), message); + var offset = hash[^1] & 0x0f; + var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16) + | (hash[offset + 2] << 8) | hash[offset + 3]; + return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); + } +#pragma warning restore CA5350 + [Theory] [InlineData("lock")] [InlineData("roles")] diff --git a/tests/Heimdall.Web.Tests/Components/Pages/LoginTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/LoginTests.cs index b3ffe5f..af9dd45 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/LoginTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/LoginTests.cs @@ -47,7 +47,7 @@ public class LoginTests : PageTestBase public async Task LoginPage_Succes_NavigueVersDashboard() { Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse()); - JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(true); + JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(200); var nav = Navigate(); var cut = RenderPage(); @@ -119,7 +119,7 @@ public class LoginTests : PageTestBase var requires2fa = SuccessResponse() with { Requires2fa = true }; Handler.On(HttpMethod.Post, "api/auth/login", requires2fa); Handler.On(HttpMethod.Post, "api/auth/2fa/verify", SuccessResponse()); - JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(true); + JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(200); var nav = Navigate(); var cut = RenderPage(); @@ -151,7 +151,7 @@ public class LoginTests : PageTestBase public async Task LoginPage_ReturnUrl_UtilisePourLaNavigation() { Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse()); - JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(true); + JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(200); var nav = Navigate(); nav.NavigateTo("/login?returnUrl=/sites"); @@ -168,7 +168,7 @@ public class LoginTests : PageTestBase public async Task LoginPage_ReturnUrlExterne_IgnoreEtVaSurDashboard() { Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse()); - JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(true); + JSInterop.Setup("heimdallAuth.signIn", _ => true).SetResult(200); var nav = Navigate(); nav.NavigateTo("/login?returnUrl=https://evil.example.com"); diff --git a/tests/Heimdall.Web.Tests/Services/AuthHelperTests.cs b/tests/Heimdall.Web.Tests/Services/AuthHelperTests.cs new file mode 100644 index 0000000..3b199f6 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Services/AuthHelperTests.cs @@ -0,0 +1,70 @@ +using Heimdall.Web.Services; +using Microsoft.Extensions.Logging; +using Microsoft.JSInterop; +using Shouldly; + +namespace Heimdall.Web.Tests.Services; + +public sealed class AuthHelperTests +{ + [Theory] + [InlineData(200, true)] + [InlineData(204, true)] + [InlineData(401, false)] + [InlineData(500, false)] + [InlineData(0, false)] + public async Task SignInAsync_UsesOnlyTheReturnedHttpStatus(int statusCode, bool expected) + { + var jsRuntime = new StubJsRuntime(statusCode); + + var result = await AuthHelper.SignInAsync(jsRuntime, new RecordingLogger(), new { accessToken = "synthetic" }); + + result.ShouldBe(expected); + } + + [Fact] + public async Task SignInAsync_LogsInteropFailureTypeWithoutExceptionMessage() + { + const string privateDetail = "synthetic-private-detail"; + var jsRuntime = new StubJsRuntime(new JSException(privateDetail)); + var logger = new RecordingLogger(); + + (await AuthHelper.SignInAsync(jsRuntime, logger, new { accessToken = "synthetic" })).ShouldBeFalse(); + + var logged = string.Join(" ", logger.Messages); + logged.ShouldContain(nameof(JSException)); + logged.ShouldNotContain(privateDetail); + } + + private sealed class RecordingLogger : ILogger + { + public List Messages { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + => Messages.Add(formatter(state, exception)); + } + + private sealed class StubJsRuntime : IJSRuntime + { + private readonly int _statusCode; + private readonly Exception? _exception; + + public StubJsRuntime(int statusCode) => _statusCode = statusCode; + public StubJsRuntime(Exception exception) => _exception = exception; + + public ValueTask InvokeAsync(string identifier, object?[]? args) + => InvokeAsync(identifier, CancellationToken.None, args); + + public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) + { + if (_exception is not null) + return ValueTask.FromException(_exception); + + return ValueTask.FromResult((TValue)(object)_statusCode); + } + } +}