Merge remote-tracking branch 'origin/main' into fix-camera-access-nullable-select

This commit is contained in:
arnaud.dartois committed 2026-11-08 20:14:28 +01:00
commit 81b794daf7
53 files changed
+997 -117

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ Refs #
## Vérification
<!-- Liens des runs Gitea, suites exécutées, résultats et item actualisé dans todo.md. -->
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
+9 -2
View File
@@ -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/ ./
+9 -2
View File
@@ -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/ ./
@@ -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:
+3
View File
@@ -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
+2
View File
@@ -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
+11
View File
@@ -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
+1 -1
View File
@@ -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
+1
View File
@@ -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",
+1
View File
@@ -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" \
+3
View File
@@ -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
+32
View File
@@ -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`.
@@ -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.
+25
View File
@@ -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.
+1
View File
@@ -79,6 +79,7 @@ Render long historical logs as a clearly separated `<details><summary>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.
+1
View File
@@ -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.
+5 -1
View File
@@ -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`.
+17
View File
@@ -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.
+1
View File
@@ -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
+17
View File
@@ -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 `<NotFound>` 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.
@@ -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<string>? CapAdd { get; init; }
[JsonPropertyName("CapDrop")] public List<string>? CapDrop { get; init; }
[JsonPropertyName("SecurityOpt")] public List<string>? SecurityOptions { get; init; }
[JsonPropertyName("GroupAdd")] public List<string>? 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<string> Environment { get; set; } = [];
public List<string> Groups { get; set; } = [];
public List<string> Ports { get; set; } = [];
public List<string> Volumes { get; set; } = [];
public List<string> Devices { get; set; } = [];
@@ -82,6 +82,10 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
}
var refreshedUser = await _userManager.FindByIdAsync(user.Id, ct).ConfigureAwait(false);
if (refreshedUser is null)
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
user = refreshedUser;
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
}
+5 -1
View File
@@ -10,4 +10,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
</ItemGroup>
</Project>
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.Agent.Tests" />
</ItemGroup>
</Project>
+63 -37
View File
@@ -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<UdpReceiveResult> 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(
@@ -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)
@@ -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();
@@ -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(); }
}
}
+16 -15
View File
@@ -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);
}
@@ -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
<MudText Typo="Typo.h1" Class="mb-4">@Text["NotificationsPage_Title"]</MudText>
@if (_loading)
{
<MudProgressLinear Indeterminate="true" />
}
else if (_failed)
{
<MudAlert Severity="Severity.Error">@Text["NotificationsPage_Failed"]</MudAlert>
}
else if (_items.Count == 0)
{
<MudAlert Severity="Severity.Info">@Text["NotificationsPage_Empty"]</MudAlert>
}
else
{
<div class="d-flex justify-end mb-3">
<MudButton Variant="Variant.Outlined" Disabled="@(!_items.Any(x => !x.IsRead))" OnClick="MarkAllReadAsync">
@Text["NotificationsPage_MarkAllRead"]
</MudButton>
</div>
@foreach (var item in _items)
{
<MudPaper Class="pa-4 mb-2" Elevation="1">
<div class="d-flex justify-space-between align-start">
<div>
<MudText Typo="Typo.h6">@item.Title</MudText>
<MudText>@item.Message</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">@item.CreatedAt.ToLocalTime().ToString("g")</MudText>
</div>
@if (!item.IsRead)
{
<MudButton Variant="Variant.Text" OnClick="@(() => MarkReadAsync(item.Id))">@Text["NotificationsPage_MarkRead"]</MudButton>
}
</div>
</MudPaper>
}
}
@code {
private List<NotificationDto> _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);
}
}
@@ -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()
@@ -11,6 +11,7 @@
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthProvider
@inject IJSRuntime JS
@inject Microsoft.Extensions.Logging.ILogger<Profile> Logger
<MudText Typo="Typo.h1" Class="mb-6">
<i class="fas fa-user-circle mr-2"></i>
@@ -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;
@@ -5,6 +5,7 @@
@inject HeimdallAuthStateProvider AuthStateProvider
@inject NavigationManager Navigation
@inject IJSRuntime JsRuntime
@inject Microsoft.Extensions.Logging.ILogger<Setup> Logger
<div class="auth-page">
<div class="auth-card">
@@ -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"];
@@ -253,7 +253,6 @@ else
private bool _generating;
private string? _generatedToken;
private DateTime _tokenExpiresAt;
private string _dockerComposeSnippet = "";
// ── Identifiants caméras ──────────────────────────────────────
private List<SiteCredentialItem> _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) => "";
/// <summary>Origin exposed by the browser that operators use to reach Central.</summary>
private string CentralUrl => Nav.BaseUri.TrimEnd('/');
}
@@ -10,7 +10,7 @@
Visible="@(Hub.UnreadCount > 0)">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
aria-label="@Text["SharedNotificationBadge_Title"]"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
OnClick="@(() => Navigation.NavigateTo("/notifications"))" />
</MudBadge>
</MudTooltip>
@@ -64,18 +64,29 @@ else if (_method == "docker-compose" && !CanGenerateDocker)
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
@foreach (var command in Commands)
else if (_method == "docker-run" && CanGenerateDocker)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
}
else if (_method == "docker-run")
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
@if (_method != "docker-run" || CanGenerateDocker)
{
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
}
}
@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<string> { "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('/');
+1
View File
@@ -12,6 +12,7 @@
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.Api.Tests" />
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
<InternalsVisibleTo Include="Heimdall.Web.Tests" />
</ItemGroup>
<ItemGroup>
@@ -4072,7 +4072,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
<value>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)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>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.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Install (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Run (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Check (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
@@ -4072,7 +4072,7 @@
<value>Vérifier</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé.</value>
<value>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)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>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.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Installer (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Démarrer (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Vérifier (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Utiliser l’inférence GPU NVIDIA</value>
</data>
@@ -4124,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Impossible de charger les notifications. Réessayez.</value></data>
<data name="NotificationsPage_Empty"><value>Vous n’avez aucune notification.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Tout marquer comme lu</value></data>
<data name="NotificationsPage_MarkRead"><value>Marquer comme lu</value></data>
<data name="NotificationsPage_UpdateFailed"><value>Impossible de mettre à jour la notification.</value></data>
</root>
@@ -4072,7 +4072,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
<value>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)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>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.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Install (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Run (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Check (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
@@ -4124,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Notifications could not be loaded. Try again.</value></data>
<data name="NotificationsPage_Empty"><value>You have no notifications.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Mark all as read</value></data>
<data name="NotificationsPage_MarkRead"><value>Mark as read</value></data>
<data name="NotificationsPage_UpdateFailed"><value>The notification could not be updated.</value></data>
</root>
+70 -1
View File
@@ -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<UiText>();
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 = $$"""
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{title}}</title>
<style>
body { margin: 0; background: #101828; color: #f9fafb; font: 16px Inter, system-ui, sans-serif; }
main { box-sizing: border-box; max-width: 48rem; margin: 12vh auto; padding: 2rem; }
h1 { color: #60a5fa; font-size: 2.5rem; }
p { color: #cbd5e1; line-height: 1.6; }
a { display: inline-block; margin-top: 1rem; padding: .75rem 1rem; border-radius: .5rem; background: #2563eb; color: white; text-decoration: none; }
</style>
</head>
<body>
<main>
<h1>{{title}}</h1>
<p>{{message}}</p>
<a href="/dashboard">{{back}}</a>
</main>
</body>
</html>
""";
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.
@@ -925,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;
@@ -954,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
{
@@ -964,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<Program> logger) =>
+19 -6
View File
@@ -1,4 +1,5 @@
using Microsoft.JSInterop;
using Microsoft.Extensions.Logging;
namespace Heimdall.Web.Services;
@@ -7,18 +8,30 @@ internal static class AuthHelper
{
/// <summary>Creates the middleware-level auth cookie via JS interop.</summary>
/// <returns>True if the sign-in HTTP call succeeded (2xx).</returns>
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, object user)
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, ILogger logger, object user)
{
try
{
var ok = await jsRuntime.InvokeAsync<bool>("heimdallAuth.signIn", user);
if (!ok)
Console.Error.WriteLine("[AuthHelper] SignInAsync: /_auth/signin returned non-2xx status");
return ok;
var statusCode = await jsRuntime.InvokeAsync<int>("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;
}
}
@@ -1037,6 +1037,25 @@ public class HeimdallApiClient : IDisposable
// ─── Notification Config ─────────────────────────────────────────
public async Task<PagedResult<NotificationDto>?> GetNotificationsAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedResult<NotificationDto>>(
$"api/notifications?page={page}&pageSize={pageSize}", Json);
}
public async Task<bool> MarkNotificationAsReadAsync(Guid id)
{
using var response = await CreateClient().PostAsync($"api/notifications/{id}/read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<bool> MarkAllNotificationsAsReadAsync()
{
using var response = await CreateClient().PostAsync("api/notifications/mark-all-read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<NotificationConfigItem?> GetNotificationConfigAsync()
{
var client = CreateClient();
+2 -2
View File
@@ -11,9 +11,9 @@ window.heimdallAuth = {
body: JSON.stringify(data),
credentials: 'include'
});
return response.ok;
return response.status;
} catch {
return false;
return 0;
}
},
@@ -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<UdpReceiveResult>(new CancellationToken(canceled: true));
await Should.NotThrowAsync(() => MdnsClient.ObserveCanceledReceiveAsync(canceledReceive, CancellationToken.None));
var socketFailure = Task.FromException<UdpReceiveResult>(new SocketException((int)SocketError.NetworkDown));
await Should.ThrowAsync<SocketException>(
() => MdnsClient.ObserveCanceledReceiveAsync(socketFailure, CancellationToken.None));
}
[Fact]
public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow()
{
@@ -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");
}
}
@@ -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<AuthResponse>())!.AccessToken.ShouldNotBeNullOrEmpty();
var verifiedSession = (await response.Content.ReadFromJsonAsync<AuthResponse>())!;
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<UserManager<IdentityAppUser>>();
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<AuthResponse>())!;
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<byte>();
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<byte> 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")]
@@ -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<AgentDetail>(p => p.Add(x => x.Id, AgentId));
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("introuvable");
Services.GetRequiredService<ISnackbar>().ShownSnackbars.ShouldBeEmpty();
Handler.Requests.ShouldHaveSingleItem();
});
}
[Fact]
public void AgentDetail_ErreurServeur_AfficheSnackbarErreur()
{
Handler.OnGet($"api/agents/{AgentId}", System.Net.HttpStatusCode.InternalServerError);
LoginAs();
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("introuvable");
Services.GetRequiredService<ISnackbar>().ShownSnackbars.ShouldNotBeEmpty();
});
}
private static AgentItem Agent() => new()
{
Id = AgentId,
@@ -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<CameraDetail>(p => p.Add(x => x.Id, CameraId));
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("introuvable");
Services.GetRequiredService<MudBlazor.ISnackbar>().ShownSnackbars.ShouldBeEmpty();
Handler.Requests.ShouldHaveSingleItem();
});
}
[Fact]
public async Task PlateAssociationConfirmation_PostsCameraPlateEventAndVehicleIds()
{
@@ -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<Dashboard>();
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<Dashboard>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agents en ligne"));
cut.Dispose();
}
}
@@ -47,7 +47,7 @@ public class LoginTests : PageTestBase
public async Task LoginPage_Succes_NavigueVersDashboard()
{
Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse());
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
var nav = Navigate();
var cut = RenderPage<Login>();
@@ -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<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
var nav = Navigate();
var cut = RenderPage<Login>();
@@ -151,7 +151,7 @@ public class LoginTests : PageTestBase
public async Task LoginPage_ReturnUrl_UtilisePourLaNavigation()
{
Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse());
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
JSInterop.Setup<int>("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<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
var nav = Navigate();
nav.NavigateTo("/login?returnUrl=https://evil.example.com");
@@ -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<NotificationDto>([], 0, 1, 20));
LoginAs();
var cut = RenderPage<NotificationsPage>();
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<NotificationsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Impossible de charger les notifications. Réessayez."));
}
}
@@ -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<KnownFaceClientItem>());
Handler.OnGet("api/vehicles", new List<VehicleClientItem>());
Handler.OnGet("api/events", new EventPageResult([], 0, 1, 50));
LoginAs();
var cut = RenderPage<PersonDetailPage>(p => p.Add(x => x.Id, PersonId));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Personne introuvable"));
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("Personne introuvable");
Services.GetRequiredService<ISnackbar>().ShownSnackbars.ShouldBeEmpty();
Handler.Requests.ShouldHaveSingleItem();
});
}
[Fact]
@@ -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<string> Messages { get; } = [];
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> 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<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
=> InvokeAsync<TValue>(identifier, CancellationToken.None, args);
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args)
{
if (_exception is not null)
return ValueTask.FromException<TValue>(_exception);
return ValueTask.FromResult((TValue)(object)_statusCode);
}
}
}