diff --git a/docker/Dockerfile b/docker/Dockerfile index 89b54cf..1801e0e 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,7 +10,7 @@ RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng && rm -rf /var/lib/apt/lists/* ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /out/ ./ EXPOSE 8080 diff --git a/docker/backup/README.md b/docker/backup/README.md index c6a8e0d..9e16286 100644 --- a/docker/backup/README.md +++ b/docker/backup/README.md @@ -22,7 +22,8 @@ docker compose --env-file .env -f docker-compose.backup.yml up -d Le Central et PostgreSQL doivent d'abord être démarrés. Le service `backup` rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine -avec crontab interne. Les dumps sont stockés dans `backup_data`; l'upload +avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils +de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload RustFS/S3 est facultatif. Le service monte aussi le volume `heimdall_data` du Compose Central : les objets stockés localement et les clés Data Protection sont archivés ensemble. diff --git a/docker/docker-compose.agent.dev.gpu-nvidia.yml b/docker/docker-compose.agent.dev.gpu-nvidia.yml index d02f6f7..f52e4b3 100644 --- a/docker/docker-compose.agent.dev.gpu-nvidia.yml +++ b/docker/docker-compose.agent.dev.gpu-nvidia.yml @@ -19,4 +19,7 @@ services: capabilities: [gpu] agent-state-init: - image: heimdall-agent:local + image: heimdall-agent:gpu-local + build: + context: .. + dockerfile: docker/Dockerfile.agent.gpu diff --git a/docker/docker-compose.backup.yml b/docker/docker-compose.backup.yml index 0bf4cc5..9012987 100644 --- a/docker/docker-compose.backup.yml +++ b/docker/docker-compose.backup.yml @@ -30,10 +30,9 @@ services: entrypoint: ["/bin/sh", "-c"] command: - | + set -e export POSTGRES_PASSWORD="$$(cat /run/secrets/db_password)" - apk add --no-cache curl bash >/dev/null 2>&1 || true - curl -fsSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc || true - chmod +x /usr/local/bin/mc 2>/dev/null || true + apk add --no-cache aws-cli bash coreutils echo '0 2 * * * bash /scripts/backup.sh >> /var/log/backup.log 2>&1' > /tmp/crontab.txt echo '15 2 * * * bash /scripts/backup-protected-data.sh >> /var/log/backup-protected-data.log 2>&1' >> /tmp/crontab.txt echo '0 3 * * 0 bash /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1' >> /tmp/crontab.txt diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 932c387..8adb32f 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -53,6 +53,7 @@ services: LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} + Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} Sentry__Dsn: ${SENTRY_DSN:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05} Sentry__Release: ${SENTRY_RELEASE:-} diff --git a/docker/docker-compose.webrtc-local-test.yml b/docker/docker-compose.webrtc-local-test.yml index 5ae6683..037d78f 100644 --- a/docker/docker-compose.webrtc-local-test.yml +++ b/docker/docker-compose.webrtc-local-test.yml @@ -7,10 +7,14 @@ services: HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} MTX_AUTHMETHOD: http MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL} + MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} + # The browser receives this ICE port in SDP; keep the published host port + # identical so Docker NAT does not advertise an unreachable container port. + MTX_WEBRTCLOCALUDPADDRESS: :${HEIMDALL_TEST_ICE_PORT:-18189} ports: - "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp" - "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp" - - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:8189/udp" + - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:${HEIMDALL_TEST_ICE_PORT:-18189}/udp" volumes: - ./mediamtx.local-test.yml:/mediamtx.yml:ro networks: diff --git a/docker/docker-compose.webrtc.yml b/docker/docker-compose.webrtc.yml index 4fd8ede..8f5fce3 100644 --- a/docker/docker-compose.webrtc.yml +++ b/docker/docker-compose.webrtc.yml @@ -9,6 +9,8 @@ services: HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} MTX_AUTHMETHOD: http MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL} + MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} + MTX_WEBRTCADDITIONALHOSTS: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname} ports: - "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp" - "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index b5a4177..164655c 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -43,6 +43,7 @@ services: LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} + Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} ports: - "${WEB_PORT:-5000}:8080" volumes: diff --git a/docker/mediamtx.yml b/docker/mediamtx.yml index a60015a..4001019 100644 --- a/docker/mediamtx.yml +++ b/docker/mediamtx.yml @@ -11,9 +11,9 @@ webrtcAddress: :8889 webrtcEncryption: true webrtcServerCert: /certs/server.crt webrtcServerKey: /certs/server.key -webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcAllowOrigins: [] webrtcLocalUDPAddress: :8189 -webrtcAdditionalHosts: ['${HEIMDALL_WEBRTC_PUBLIC_HOST}'] +webrtcAdditionalHosts: [] pathDefaults: source: publisher diff --git a/docker/scripts/backup-protected-data.sh b/docker/scripts/backup-protected-data.sh index c6a90cd..9957da4 100755 --- a/docker/scripts/backup-protected-data.sh +++ b/docker/scripts/backup-protected-data.sh @@ -35,9 +35,14 @@ find "$ARCHIVE_DIR" -type f -name 'heimdall-data-*.tar.gz' -mtime "+$RETENTION_D if [[ "$SKIP_S3_UPLOAD" == "1" ]]; then log "S3 upload disabled by BACKUP_SKIP_S3_UPLOAD" elif [[ -n "$S3_ENDPOINT" && -n "$S3_ACCESS_KEY" && -n "$S3_SECRET_KEY" ]]; then - command -v mc >/dev/null 2>&1 || die "mc is required to upload protected data backups" - mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null - mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + if command -v mc >/dev/null 2>&1; then + mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null + mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + elif command -v aws >/dev/null 2>&1; then + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$ARCHIVE" "s3://${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + else + die "Neither mc nor aws CLI is available to upload protected data backups" + fi log "Uploaded protected data archive to the configured object store" else log "S3 credentials are not configured; the archive remains in the local backup volume" diff --git a/docker/scripts/backup-rustfs.sh b/docker/scripts/backup-rustfs.sh index a9b87fb..25e1023 100755 --- a/docker/scripts/backup-rustfs.sh +++ b/docker/scripts/backup-rustfs.sh @@ -76,7 +76,7 @@ else 2>&1 | tail -10 else # AWS CLI: sync with exclusion - aws --endpoint-url "$S3_ENDPOINT" s3 sync \ + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 sync \ "s3://${S3_BUCKET}" \ "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \ --exclude "backup/*" \ @@ -102,6 +102,14 @@ if [[ -n "$CUTOFF_WEEK" ]]; then mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true fi done + else + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | awk '$1 == "PRE" {print $2}' | while read -r week; do + week="${week%/}" + if [[ "$week" < "$CUTOFF_WEEK" ]]; then + log " Deleting: ${BACKUP_PREFIX}/${week}/" + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm --recursive "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" >/dev/null + fi + done fi fi fi @@ -131,7 +139,7 @@ Total: ${TOTAL_SIZE} bytes if [[ "$CLIENT" == "mc" ]]; then echo "$MANIFEST" | mc pipe "heimdall-backup/${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null else - echo "$MANIFEST" | aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null + echo "$MANIFEST" | AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null fi log "Manifest written: ${MANIFEST_KEY}" fi diff --git a/docker/scripts/backup.sh b/docker/scripts/backup.sh index 36f9f9e..f05e7c6 100755 --- a/docker/scripts/backup.sh +++ b/docker/scripts/backup.sh @@ -109,8 +109,8 @@ if [[ -n "$S3_ENDPOINT" ]]; then mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 else - aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 - aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 fi log "Upload complete" fi @@ -141,6 +141,13 @@ if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true fi done + elif command -v aws >/dev/null 2>&1; then + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | awk '{print $4}' | while read -r key; do + if [[ "$key" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2})/ ]] && [[ "${BASH_REMATCH[1]}" < "$CUTOFF_DATE" ]]; then + log " Deleting: $key" + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm "s3://${S3_BUCKET}/${key}" >/dev/null + fi + done fi fi fi diff --git a/docker/scripts/restore.sh b/docker/scripts/restore.sh index c2ec315..3898bb0 100755 --- a/docker/scripts/restore.sh +++ b/docker/scripts/restore.sh @@ -124,7 +124,7 @@ if [[ -n "$S3_KEY" ]]; then mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null mc cp "heimdall-backup/${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 else - aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 fi log "Downloaded: $(du -h "$FILE" | cut -f1)" fi diff --git a/docs/docker-compose.md b/docs/docker-compose.md index 2e1c4ae..67cc636 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -90,10 +90,12 @@ JWT__ISSUER=heimdall JWT__AUDIENCE=heimdall-api ASPNETCORE_ENVIRONMENT=Production WEB_PORT=5000 +RECORDING_STORAGE_QUOTA_MAX_BYTES=1099511627776 Cors__AllowedOrigins=https://heimdall.example.org EOF unset db_password # Replace the example origin above with the public origin of your Central. +# The recording quota defaults to 1 TiB (1099511627776 bytes). docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d ``` @@ -221,3 +223,11 @@ project with `down --volumes --remove-orphans`, confirm its containers, named volumes and network are gone, and delete its temporary environment/secret files. This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS and HTTPS with a trusted certificate. + +A source-built disposable acceptance on 5 November 2026 decoded a 640×360 synthetic +frame through the actual `live-view.js` module in Chromium. WHEP resource deletion +returned 200, Central session release returned 204, and disabling the camera +reduced the Agent publisher count from one to zero. The project teardown left no +containers, volumes, or network. MediaMTX origins and public ICE host must be passed +through its `MTX_WEBRTCALLOWORIGINS` and `MTX_WEBRTCADDITIONALHOSTS` environment +variables; placeholders inside `mediamtx.yml` are not expanded. diff --git a/scripts/ci/test_ci.py b/scripts/ci/test_ci.py index 4767b7f..57aa9d9 100644 --- a/scripts/ci/test_ci.py +++ b/scripts/ci/test_ci.py @@ -99,6 +99,9 @@ class GpuAgentImageTests(unittest.TestCase): self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose) self.assertIn('driver: nvidia', compose) self.assertIn('capabilities: [gpu]', compose) + self.assertIn('image: heimdall-agent:gpu-local', compose) + state_init = compose.split(' agent-state-init:', 1)[1] + self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init) class AdvisoryTests(unittest.TestCase): def check(self, data): diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index eca9a27..0a77a66 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -12,7 +12,8 @@ Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL - `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically. - The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body. - Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again. -- Extend `ConfigReceiverServiceTests` with an in-memory HTTP handler that returns a transient failure before success. Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. +- `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`. +- Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. ## Local checks @@ -21,7 +22,7 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore ``` -For behavior changes, build the Agent from source in a uniquely named Docker Compose project using a private isolated network, generated credentials, loopback-only ports, and project-scoped volumes. Probe `/healthz`, then tear down that project with `down --volumes --remove-orphans` and verify its containers, volumes, and network are gone. Serialize Docker acceptance when another source build is using the shared daemon. +For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. Tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source. Serialize Docker acceptance when another source build is using the shared daemon. ## Acceptance boundary diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md index 37507b1..9236691 100644 --- a/skills/backup-restore/SKILL.md +++ b/skills/backup-restore/SKILL.md @@ -21,4 +21,6 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res 3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions. 4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. 5. Tear down only the disposable project with `docker compose -p down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files. -6. Keep S3 round trips, real-volume production recovery, and production RPO/RTO open until validated on their actual service and data. +6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation. +7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed. +8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 47ee6cd..cbf77a3 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -27,4 +27,4 @@ Use this skill when changing ONNX Runtime packages, execution provider configura ## Current limitation -The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. Their image/Compose build acceptance and physical CUDA execution remain open until those runs succeed. +The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from source with the locked GPU package. Rendered Compose confirmed that CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A disposable Central/PostgreSQL stack passed bootstrap and `/healthz`, but Docker could not create the GPU overlay's `agent-state-init` container (stalled/conflicting create calls in the shared daemon); the Agent never started. Therefore Agent health, token registration, and an actual CPU inference from the CUDA image remain unverified. Retry the complete recipe with an available Docker daemon slot: bootstrap a disposable site, run the GPU image without NVIDIA devices, attach a synthetic RTSP source, and verify an inference observation with `CPUExecutionProvider` before teardown. The first Central attempt used a malformed synthetic Npgsql connection string and produced one GlitchTip report; the fixture was corrected and the DSN disabled for the subsequent run. It contained no production data or secrets. Physical CUDA execution also remains open. diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md new file mode 100644 index 0000000..6194955 --- /dev/null +++ b/skills/mdns-camera-discovery/SKILL.md @@ -0,0 +1,27 @@ +--- +name: mdns-camera-discovery +description: Implement and validate HomeKit camera discovery from DNS-SD mDNS announcements in Heimdall Agent. +--- + +# Heimdall mDNS camera discovery + +Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing discovery behavior. + +## Ownership and data flow + +- `Heimdall.Mdns/MdnsClient` owns UDP multicast and DNS-SD PTR/SRV/TXT/A parsing. Keep network operations cancellable and dispose sockets per operation. +- `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records. +- `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN. +- Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback. + +## Synthetic acceptance + +- Build synthetic DNS response packets with PTR `_hap._tcp.local` → instance, SRV instance → hostname/port, TXT `ci`, `sf`, `id`, `md`, and A hostname → address. Include an unrelated A record to verify strict SRV association. +- Verify camera and doorbell categories are kept, unrelated categories are filtered, `sf=0` maps to paired, and missing SRV-target A does not invent an address. +- Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result. +- Run the focused Agent tests and the full Agent test project after changes. +- 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. + +## 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. Remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index f8a5ad5..ad0d940 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -10,9 +10,11 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. - Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. - Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. +- Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera. - The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL. - Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. -- Add PostgreSQL tests for migration, metadata/idempotency, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. +- Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. - For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. +- For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. -Current product gaps are audio/event-trigger capture, an explicit Central storage quota, and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. +Current product gaps are audio/event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 1f96f68..62de39e 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -1,33 +1,39 @@ --- name: vision-identity -description: Extend Heimdall's person, face-embedding, vehicle, and license-plate data paths without logging biometric data or shipping unapproved model weights. +description: Implement Heimdall's opt-in, self-hosted plate OCR and preserve the licensing/privacy gates for camera face and plate identity. --- -# Heimdall vision identity data +# Vision identity in Heimdall -## Current project behavior +Read `AGENTS.md` and FEAT-03/UI-02 in `todo.md`. Current API contract only supports a human-triggered OCR request with an operator-supplied JPEG/PNG plate crop. It does not infer plate boxes from video frames or recognize faces. -- `AnalysisJobPollingService` currently executes only `ObjectDetection`; do not describe the current Agent as performing face recognition or license-plate OCR. -- `KnownFace` is a manually registered vector record, not a face detector or recognition model. Inputs are limited to 4,096 finite float values, copied on construction, and the API body is capped at 256 KiB. Never log or include vector values in audit data. -- `LicensePlate` is a persisted observation record. Its text limit must match the PostgreSQL column (20 characters); confidence must be finite and in `[0,1]`. -- Face embeddings, plate text, and source images are sensitive. Preserve per-person deletion/cascade behavior, keep event camera authorization at API and application boundaries, and do not send frames or embeddings to external services. +## Plate OCR currently implemented -## Model review gate +- `PlateOcr:Enabled` defaults to false. Explicitly enable the on-prem Central option to offer OCR; the camera detail UI sends only the file the user selected. +- Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance. +- The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval. +- OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path. +- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it deliberately does not persist `VehicleId`/`PersonId` links. Never treat OCR output as verified identity; a human confirmation/linking workflow is still missing. +- OCR observations remain unassigned and use the existing cleanup that purges unassigned plate rows after 30 days. The `LicensePlateDetected` event label and metadata have no equivalent retention in this change, so event retention/privacy review remains open before enabling this in production. -Before adding inference, record the exact model artifact URL/version, checksum, training-data terms, model-weight license, code/runtime license, regions/languages represented, preprocessing, hardware/runtime requirements, and an offline installation path. A repository code license alone does not establish the license of its pretrained weights. +## Face-model gate -Review findings as of 2026-11-04: +ONNX Runtime is already used by the Agent and is MIT licensed. A model runtime license does not grant rights to a particular model's weights or training data. InsightFace's model-zoo documentation restricts its distributed pretrained weights to non-commercial research. ONNX Model Zoo's ArcFace/UltraFace listing points to sourced models but does not establish one blanket weight/data license. Do not bundle SFace, ArcFace, YuNet, or plate-detector weights unless the exact asset and training-data rights are reviewed. An operator-provided model also needs a documented tensor/preprocessing contract, stable model ID stored with enrollments, explicit opt-in, deletion/retention semantics, and representative accuracy testing before face matches can create events. -- [InsightFace model-zoo license notice](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) says its pretrained models are for non-commercial research; do not ship them for this product without separate permission. -- [FaceONNX model README](https://github.com/FaceONNX/FaceONNX.Models/blob/main/README.md) licenses the library as MIT but links models via Google Drive without specifying a separate model-weight license; treat weights as unresolved. -- [PaddleOCR license page](https://www.paddleocr.ai/v2.10.0/en/index.html) states Apache-2.0 for the project. It does not, by itself, establish rights for a particular license-plate model artifact; verify that artifact's own license and training data. -- [LdDl license-plate-recognition](https://github.com/LdDl/license_plate_recognition) declares Apache-2.0 for the repository and says its pretrained networks were trained on Russian plates. The repository does not separately establish weight rights or accuracy for Heimdall's target regions. +Official sources reviewed: -Do not download or bundle model files until their artifact-level rights and target-region accuracy are reviewed. Keep accuracy claims open until validated on an appropriately licensed, representative dataset and camera conditions. +- [Tesseract engine license and command-line formats](https://github.com/tesseract-ocr/tesseract) +- [Official `tessdata_best` license](https://github.com/tesseract-ocr/tessdata_best) +- [Official `tessdata` language-data license](https://github.com/tesseract-ocr/tessdata) +- [Official Tesseract data-file compatibility guidance](https://github.com/tesseract-ocr/tessdoc/blob/main/Data-Files.md) +- [ONNX Runtime repository license](https://github.com/microsoft/onnxruntime) +- [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md) +- [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) ## Acceptance -1. Run Domain, Application, Infrastructure, and Web tests for changed layers; test EF translation/deletion behavior with PostgreSQL when persistence semantics change. -2. For a new model, test model verification/hash rejection, explicit opt-in, CPU fallback, and no outbound frame/embedding requests. Keep the exact artifact out of the repo unless its license and source are approved. -3. Exercise person and vehicle access through the authenticated API/UI, including deletion of the person and the documented retention behavior of linked event history and embeddings. -4. For behavior changes, run the disposable Compose acceptance from `skills/compose-disposable-recipe/SKILL.md`; keep generated data and credentials isolated and remove only that project. +1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. +2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. +3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. +4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. +5. This acceptance covers one clean synthetic crop and API persistence only. It does not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index df5110e..27070c4 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -69,4 +69,4 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do 6. Tear down only that Compose project with volumes/orphans, then verify its containers, volumes and network are gone. -Record LAN browser and external TURN runs independently. Current focused API/Web and Agent tests pass. Disposable Compose verified Central bootstrap/site creation, Agent registration, synthetic camera assignment, publish-session issuance and relay start, read ticket callback acceptance, forged-ticket denial, unknown-camera denial, and teardown with no remaining project containers, volumes or networks. A deliberately invalid SDP reached MediaMTX and returned 400; a browser-decoded frame and API-driven disable stop were not verified. Physical camera, LAN, external TURN and real SDP/frame playback remain unvalidated; keep FEAT-01 open until these acceptance gaps are closed. +Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index 260af86..4359bec 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -265,7 +265,7 @@ public NetworkCameraScanner( /// are kept; the HomeKit* fields of the device are filled for the Central /// ClassifyAgentDevice HomeKit path. /// - private async Task> DiscoverHomeKitAsync(CancellationToken ct) + internal async Task> DiscoverHomeKitAsync(CancellationToken ct) { var devices = new List(); try diff --git a/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs b/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs new file mode 100644 index 0000000..416f98b --- /dev/null +++ b/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs @@ -0,0 +1,14 @@ +namespace Heimdall.Application.Common; + +/// Serializes recording usage checks across cameras and exposes the validated Central quota. +public interface IRecordingQuotaGuard +{ + long MaxStorageBytes { get; } + Task AcquireAsync(CancellationToken ct = default); +} + +/// A short-lived database transaction holding the global recording quota lock. +public interface IRecordingQuotaLease : IAsyncDisposable +{ + Task CommitAsync(CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs index afc8fc5..d6a95c8 100644 --- a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs +++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs @@ -4,6 +4,7 @@ using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using MediatR; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; namespace Heimdall.Application.Recordings.Commands.UploadRecording; @@ -18,7 +19,10 @@ public sealed record UploadRecordingCommand( public sealed class UploadRecordingHandler( IApplicationDbContext db, - IRecordingStorage storage) : IRequestHandler> + IRecordingStorage storage, + IRecordingQuotaGuard quota, + IStorageObjectDeletion objectDeletion, + ILogger logger) : IRequestHandler> { public async Task> Handle(UploadRecordingCommand request, CancellationToken ct) { @@ -29,9 +33,9 @@ public sealed class UploadRecordingHandler( var camera = await db.Cameras.AsNoTracking() .Where(c => c.Id == request.CameraId && !c.IsDeleted) - .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId }) + .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled }) .SingleOrDefaultAsync(ct).ConfigureAwait(false); - if (camera?.AgentId != request.AgentId) + if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled) return ServiceResult.NotFound("Camera not found"); var existing = await db.Recordings.AsNoTracking() @@ -45,23 +49,100 @@ public sealed class UploadRecordingHandler( var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp); var location = storage.CaptureCurrentLocation(); - var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4"; - if (request.Content.CanSeek) request.Content.Position = 0; - await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); + // Each attempt gets its own key so a racing retry cannot overwrite the winner's object + // before the transaction discovers its already-persisted metadata row. + var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}/{Guid.NewGuid():N}.mp4"; - var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, - key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); - db.Recordings.Add(recording); - await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + var shouldDeleteObject = false; + var commitAttempted = false; + try + { + if (request.Content.CanSeek) request.Content.Position = 0; + await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); - var end = timestamp.AddSeconds(request.DurationSeconds); - await db.CameraEvents - .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end) - .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) - .ConfigureAwait(false); + ServiceResult result; + await using (var quotaLease = await quota.AcquireAsync(ct).ConfigureAwait(false)) + { + // Recheck under the quota lock to keep duplicate retries safe when uploads race. + existing = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (existing is not null) + { + // The uploaded key is unique to this attempt, so it cannot be the + // already-persisted object's key and is safe to remove in either case. + shouldDeleteObject = true; + result = existing.CameraId == request.CameraId + ? ServiceResult.Success(Map(existing.Id, existing.CameraId, + existing.Timestamp, existing.DurationSeconds, existing.SizeBytes)) + : ServiceResult.Conflict("Recording identifier already belongs to another camera"); + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + } + else + { + var usedBytes = await db.Recordings.AsNoTracking() + .SumAsync(r => (long?)r.SizeBytes, ct).ConfigureAwait(false) ?? 0; + var overQuota = request.SizeBytes > quota.MaxStorageBytes || + usedBytes > quota.MaxStorageBytes - request.SizeBytes; + if (overQuota) + { + shouldDeleteObject = true; + result = ServiceResult.Failure( + "Central recording storage quota exceeded; segment was not retained", 507); + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + } + else + { + var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, + key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); + db.Recordings.Add(recording); + await db.SaveChangesAsync(ct).ConfigureAwait(false); - return ServiceResult.Success(Map(recording.Id, recording.CameraId, - recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + var end = timestamp.AddSeconds(request.DurationSeconds); + await db.CameraEvents + .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && + e.OccurredAt >= timestamp && e.OccurredAt < end) + .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) + .ConfigureAwait(false); + + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + result = ServiceResult.Success(Map(recording.Id, recording.CameraId, + recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + } + } + } + + if (shouldDeleteObject) + await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, ct).ConfigureAwait(false); + return result; + } + catch + { + // Once commit starts its outcome can be ambiguous; leave this attempt's unique object + // for the retry/orphan sweep instead of risking deletion after a successful DB commit. + if (!commitAttempted) + await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, CancellationToken.None) + .ConfigureAwait(false); + throw; + } + } + + private async Task TryDeleteUploadedObjectAsync(string key, StorageLocation location, Guid recordingId, + CancellationToken ct) + { + try + { + await objectDeletion.DeleteBatchAsync([key], location, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + logger.LogWarning("Could not clean up an unretained recording object {RecordingId} (error type {ErrorType})", + recordingId, ex.GetType().Name); + } } private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) => diff --git a/src/Heimdall.Application/Services/ILicensePlateOcr.cs b/src/Heimdall.Application/Services/ILicensePlateOcr.cs new file mode 100644 index 0000000..d1247d4 --- /dev/null +++ b/src/Heimdall.Application/Services/ILicensePlateOcr.cs @@ -0,0 +1,18 @@ +namespace Heimdall.Application.Services; + +public sealed record PlateOcrResult(string Text, double Confidence); + +/// Runs self-hosted OCR over a user-supplied plate crop. +public interface ILicensePlateOcr +{ + Task RecognizeAsync(ReadOnlyMemory image, CancellationToken ct); +} + +public sealed record LicensePlateRecognitionResponse(Guid PlateId, Guid EventId, string PlateText, + double Confidence, Guid? SuggestedVehicleId, Guid? SuggestedPersonId); + +public interface ILicensePlateRecognitionService +{ + Task> RecognizeAsync( + Guid cameraId, ReadOnlyMemory image, CancellationToken ct); +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 6973e32..7f6b219 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -45,6 +45,12 @@ public static class DependencyInjection services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); + services.AddOptions() + .Bind(configuration.GetSection(PlateOcrOptions.SectionName)) + .Validate(options => options.IsValid(), "Plate OCR options are invalid") + .ValidateOnStart(); + services.AddSingleton(); + services.AddScoped(); // Stockage (spec Phase 8) — provider résolu depuis les settings DB // (storage.provider = Local | S3), factory scoped (lit la config à @@ -52,7 +58,6 @@ public static class DependencyInjection services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); - services.AddScoped(); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs b/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs new file mode 100644 index 0000000..dc7e5c9 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs @@ -0,0 +1,50 @@ +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +public sealed class LicensePlateRecognitionService( + IDbContextFactory dbFactory, + ILicensePlateOcr ocr) : ILicensePlateRecognitionService +{ + public async Task> RecognizeAsync( + Guid cameraId, ReadOnlyMemory image, CancellationToken ct) + { + var result = await ocr.RecognizeAsync(image, ct).ConfigureAwait(false); + if (result is null) return ServiceResult.Failure("OCR could not read this plate crop", 422); + var plateText = new string(result.Text.Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray()) + .ToUpperInvariant(); + if (plateText.Length is < 3 or > LicensePlate.MaxPlateTextLength) + return ServiceResult.Failure("OCR output is not a valid plate candidate", 422); + + await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false); + var camera = await db.Cameras.AsNoTracking() + .Where(c => c.Id == cameraId && !c.IsDeleted) + .Select(c => new { c.Id, c.SiteId }) + .FirstOrDefaultAsync(ct).ConfigureAwait(false); + if (camera is null) return ServiceResult.NotFound("Camera not found"); + + var normalized = plateText.Replace("-", string.Empty); + var vehicles = await db.Vehicles.AsNoTracking() + .Where(v => v.LicensePlate != null && v.LicensePlate.Replace("-", "") == normalized) + .OrderBy(v => v.Id) + .Take(2) + .Select(v => new { v.Id, v.PersonId }) + .ToListAsync(ct).ConfigureAwait(false); + // Suggest only. OCR output is not proof of identity: a human must verify it before linking. + var vehicle = vehicles.Count == 1 ? vehicles[0] : null; + var observation = new LicensePlate(plateText, confidence: result.Confidence); + var ev = new CameraEvent(cameraId, EventType.LicensePlateDetected, result.Confidence); + ev.SetMetadata(plateText, JsonSerializer.Serialize(new { source = "local-opt-in-ocr", plateId = observation.Id })); + db.LicensePlates.Add(observation); + db.CameraEvents.Add(ev); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + return ServiceResult.Success( + new(observation.Id, ev.Id, plateText, result.Confidence, vehicle?.Id, vehicle?.PersonId)); + } +} diff --git a/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs b/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs new file mode 100644 index 0000000..d62f91f --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs @@ -0,0 +1,150 @@ +using System.Diagnostics; +using System.Globalization; +using Microsoft.Extensions.Options; + +namespace Heimdall.Infrastructure.Services; + +public sealed class PlateOcrOptions +{ + public const string SectionName = "PlateOcr"; + public bool Enabled { get; set; } + public string ExecutablePath { get; set; } = "/usr/bin/tesseract"; + public int MaxImageBytes { get; set; } = 512 * 1024; + public int TimeoutSeconds { get; set; } = 10; + + public bool IsValid() => !Enabled || + (!string.IsNullOrWhiteSpace(ExecutablePath) && MaxImageBytes is >= 1024 and <= 512 * 1024 && + TimeoutSeconds is >= 1 and <= 60); +} + +/// Invokes local Tesseract against a temporary, bounded image crop. +public sealed class TesseractPlateOcr(IOptionsMonitor options) : Application.Services.ILicensePlateOcr +{ + public async Task RecognizeAsync(ReadOnlyMemory image, CancellationToken ct) + { + var settings = options.CurrentValue; + if (!settings.Enabled || !IsSafeImage(image.Span, settings.MaxImageBytes)) + return null; + + var tempFile = Path.Combine(Path.GetTempPath(), $"heimdall-plate-{Guid.NewGuid():N}.img"); + try + { + var fileOptions = new FileStreamOptions + { + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + Share = FileShare.None, + BufferSize = 4096 + }; + if (!OperatingSystem.IsWindows()) + fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + await using (var output = new FileStream(tempFile, fileOptions)) + await output.WriteAsync(image, ct).ConfigureAwait(false); + var start = new ProcessStartInfo(settings.ExecutablePath) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + start.ArgumentList.Add(tempFile); + start.ArgumentList.Add("stdout"); + start.ArgumentList.Add("--oem"); start.ArgumentList.Add("1"); + start.ArgumentList.Add("--psm"); start.ArgumentList.Add("7"); + start.ArgumentList.Add("-l"); start.ArgumentList.Add("eng"); + start.ArgumentList.Add("tsv"); + start.ArgumentList.Add("-c"); start.ArgumentList.Add("tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); + + using var process = Process.Start(start); + if (process is null) return null; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(settings.TimeoutSeconds)); + try + { + var stdoutTask = process.StandardOutput.ReadToEndAsync(timeout.Token); + var stderrTask = process.StandardError.ReadToEndAsync(timeout.Token); + await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(timeout.Token)).ConfigureAwait(false); + var stdout = await stdoutTask.ConfigureAwait(false); + if (process.ExitCode != 0 || stdout.Length > 32_768) return null; + return ParseTsv(stdout); + } + catch (OperationCanceledException) + { + try { process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } + if (ct.IsCancellationRequested) throw; + return null; + } + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or IOException or + UnauthorizedAccessException or InvalidOperationException) + { + return null; + } + finally + { + try { File.Delete(tempFile); } catch (IOException) { } + } + } + + public static Application.Services.PlateOcrResult? ParseTsv(string tsv) + { + var text = new System.Text.StringBuilder(); + var confidenceSum = 0d; + var words = 0; + foreach (var line in tsv.Split('\n').Skip(1)) + { + var fields = line.TrimEnd('\r').Split('\t'); + if (fields.Length < 12 || !double.TryParse(fields[10], NumberStyles.Float, + CultureInfo.InvariantCulture, out var confidence) || !double.IsFinite(confidence) || confidence < 0 || string.IsNullOrWhiteSpace(fields[11])) + continue; + var token = new string(fields[11].Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray()); + if (token.Length == 0) continue; + if (text.Length > 0) text.Append(' '); + text.Append(token.ToUpperInvariant()); + confidenceSum += Math.Clamp(confidence / 100d, 0, 1); + words++; + } + return words == 0 ? null : new Application.Services.PlateOcrResult(text.ToString(), confidenceSum / words); + } + + public static bool IsSafeImage(ReadOnlySpan image, int maxBytes = 512 * 1024) => + image.Length is >= 16 && image.Length <= maxBytes && + PlateImageHeader.TryGetDimensions(image, out var width, out var height) && + width is >= 32 and <= 4096 && height is >= 16 and <= 4096 && (long)width * height <= 4_000_000; +} + +internal static class PlateImageHeader +{ + public static bool TryGetDimensions(ReadOnlySpan data, out int width, out int height) + { + width = height = 0; + if (data.Length >= 24 && data[..8].SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 })) + { + width = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(16, 4)); + height = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(20, 4)); + return width > 0 && height > 0; + } + + if (data.Length < 4 || data[0] != 0xff || data[1] != 0xd8) return false; + var offset = 2; + while (offset + 4 <= data.Length) + { + if (data[offset++] != 0xff) return false; + while (offset < data.Length && data[offset] == 0xff) offset++; + if (offset >= data.Length) return false; + var marker = data[offset++]; + if (marker is 0xd8 or 0xd9 or 0x01 || marker is >= 0xd0 and <= 0xd7) continue; + var segmentLength = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2)); + if (segmentLength < 2 || offset + segmentLength > data.Length) return false; + if (marker is >= 0xc0 and <= 0xc3 or >= 0xc5 and <= 0xc7 or >= 0xc9 and <= 0xcb or >= 0xcd and <= 0xcf) + { + if (segmentLength < 7) return false; + height = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 3, 2)); + width = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 5, 2)); + return width > 0 && height > 0; + } + offset += segmentLength; + } + return false; + } +} diff --git a/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs b/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs new file mode 100644 index 0000000..7e9cb03 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs @@ -0,0 +1,43 @@ +using System.Data; +using Heimdall.Application.Common; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Options; + +namespace Heimdall.Infrastructure.Storage; + +/// Uses one PostgreSQL transaction advisory lock to make the global quota check atomic. +public sealed class RecordingQuotaGuard( + AppDbContext db, + IOptions options) : IRecordingQuotaGuard +{ + private const long QuotaLockKey = 0x4845494D44525155; + + public long MaxStorageBytes => options.Value.MaxBytes; + + public async Task AcquireAsync(CancellationToken ct = default) + { + var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct) + .ConfigureAwait(false); + try + { + // EF Core exception: PostgreSQL transaction advisory locks have no portable LINQ equivalent. + // The lock serializes only the short metadata/quota check, after object upload has completed. + await db.Database.ExecuteSqlInterpolatedAsync( + $"SELECT pg_advisory_xact_lock({QuotaLockKey})", ct).ConfigureAwait(false); + return new TransactionLease(transaction); + } + catch + { + await transaction.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private sealed class TransactionLease(IDbContextTransaction transaction) : IRecordingQuotaLease + { + public Task CommitAsync(CancellationToken ct = default) => transaction.CommitAsync(ct); + public ValueTask DisposeAsync() => transaction.DisposeAsync(); + } +} diff --git a/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs b/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs new file mode 100644 index 0000000..db2d316 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace Heimdall.Infrastructure.Storage; + +/// Central-wide cap for bytes stored as camera recordings. +public sealed class RecordingStorageQuotaOptions +{ + public const string SectionName = "Recordings:StorageQuota"; + + /// Maximum persisted recording bytes; defaults to 1 TiB. + [Range(1, long.MaxValue)] + public long MaxBytes { get; set; } = 1L << 40; +} diff --git a/src/Heimdall.Mdns/AssemblyInfo.cs b/src/Heimdall.Mdns/AssemblyInfo.cs new file mode 100644 index 0000000..3770251 --- /dev/null +++ b/src/Heimdall.Mdns/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Heimdall.Agent.Tests")] diff --git a/src/Heimdall.Mdns/MdnsClient.cs b/src/Heimdall.Mdns/MdnsClient.cs index e2572ab..07f743d 100644 --- a/src/Heimdall.Mdns/MdnsClient.cs +++ b/src/Heimdall.Mdns/MdnsClient.cs @@ -289,6 +289,21 @@ public sealed class MdnsClient : IMdnsClient, IDisposable } } + internal static IReadOnlyList ParseMulticastResponses(IEnumerable packets) + { + ArgumentNullException.ThrowIfNull(packets); + var replies = new List(); + foreach (var packet in packets) + { + if (packet is not null) + replies.AddRange(ParsePacket(packet)); + } + + return BuildDevices(replies) + .Where(device => device.HomeKitInfo?.Category is 17 or 18) + .ToArray(); + } + private static List ParsePacket(byte[] data) { var replies = new List(); @@ -453,7 +468,6 @@ public sealed class MdnsClient : IMdnsClient, IDisposable // target host, then any A record seen (best effort). var ip = info.Ips.FirstOrDefault() ?? (info.SrvTarget is not null && addressByHost.TryGetValue(info.SrvTarget, out var srvIp) ? srvIp : null) - ?? addressByHost.Values.FirstOrDefault() ?? ""; if (string.IsNullOrEmpty(ip) || !seenIps.Add(ip)) diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 1c63c88..0473a1b 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -5,6 +5,7 @@ @inject ISnackbar Snackbar @inject NavigationManager Nav @inject UiText Text +@using Microsoft.AspNetCore.Components.Forms @inject UiLanguageService Language @inject IJSRuntime JS @implements IAsyncDisposable @@ -199,6 +200,20 @@ else @Text["CameraDetail_NoRecordings"] } + + @Text["CameraDetail_PlateOcrTitle"] + @Text["CameraDetail_PlateOcrPrivacy"] + + @if (_recognizingPlate) + { + + } + @if (!string.IsNullOrEmpty(_plateOcrMessage)) + { + @_plateOcrMessage + } + + @* ─── Mini-timeline : événements récents ─── *@ @Text["CameraDetail_RecentEvents"] @@ -285,6 +300,9 @@ else private bool _togglingStatus; private bool _showRtsp; private bool _confirmDeleteShow; + private bool _recognizingPlate; + private bool _plateOcrSuccess; + private string? _plateOcrMessage; private List? _events; private List _recordings = []; @@ -350,6 +368,33 @@ else finally { _eventsLoading = false; } } + private async Task RecognizePlateCropAsync(InputFileChangeEventArgs args) + { + var file = args.File; + if (file.Size is < 16 or > 512 * 1024 || file.ContentType is not ("image/jpeg" or "image/png")) + { + _plateOcrSuccess = false; + _plateOcrMessage = Text["CameraDetail_PlateOcrInvalid"]; + return; + } + + _recognizingPlate = true; + _plateOcrMessage = null; + try + { + await using var stream = file.OpenReadStream(512 * 1024); + var response = await Api.RecognizePlateCropAsync(Id, stream, file.ContentType, file.Name); + _plateOcrSuccess = response.Succeeded; + _plateOcrMessage = response.Succeeded && response.Data is not null + ? string.Format(Language.Culture, Text["CameraDetail_PlateOcrResult"], response.Data.PlateText, + (response.Data.Confidence * 100).ToString("0", Language.Culture)) + : response.ErrorMessage ?? Text["CameraDetail_OperationFailed"]; + if (response.Succeeded) await LoadEventsAsync(); + } + catch { _plateOcrSuccess = false; _plateOcrMessage = Text["CameraDetail_OperationFailed"]; } + finally { _recognizingPlate = false; } + } + private async Task LoadRecordingsAsync() { _recordingsLoading = true; @@ -531,6 +576,7 @@ else "PersonDetected" => Text["CameraDetail_EventPerson"], "VehicleDetected" => Text["CameraDetail_EventVehicle"], "FaceRecognized" => Text["CameraDetail_EventFace"], + "LicensePlateDetected" => Text["LicensePlateDetected"], "CameraOffline" => Text["CameraDetail_StatusOffline"], _ => type }; @@ -541,6 +587,7 @@ else "PersonDetected" => Color.Error, "VehicleDetected" => Color.Info, "FaceRecognized" => Color.Success, + "LicensePlateDetected" => Color.Info, _ => Color.Default }; diff --git a/src/Heimdall.Web/Components/Pages/EventsPage.razor b/src/Heimdall.Web/Components/Pages/EventsPage.razor index e525378..0feeb60 100644 --- a/src/Heimdall.Web/Components/Pages/EventsPage.razor +++ b/src/Heimdall.Web/Components/Pages/EventsPage.razor @@ -242,6 +242,7 @@ else "PersonDetected" => Text["EventsPage_Person"], "VehicleDetected" => Text["EventsPage_Vehicle"], "FaceRecognized" => Text["EventsPage_Face"], + "LicensePlateDetected" => Text["LicensePlateDetected"], "CameraOffline" => Text["EventsPage_Offline"], _ => type }; @@ -252,6 +253,7 @@ else "PersonDetected" => Color.Error, "VehicleDetected" => Color.Info, "FaceRecognized" => Color.Success, + "LicensePlateDetected" => Color.Info, _ => Color.Default }; diff --git a/src/Heimdall.Web/Controllers/PlateRecognitionController.cs b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs new file mode 100644 index 0000000..2702e81 --- /dev/null +++ b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs @@ -0,0 +1,48 @@ +using Heimdall.Application.Services; +using Heimdall.Api.Security; +using Heimdall.Infrastructure.Security; +using Heimdall.Infrastructure.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/cameras/{cameraId:guid}/plate-recognition")] +[EnableRateLimiting("Api")] +public sealed class PlateRecognitionController( + ResourceAccess access, + ILicensePlateRecognitionService recognition, + IOptionsMonitor options) : ControllerBase +{ + private const int MaxCropBytes = 512 * 1024; + + /// Processes a user-selected plate crop locally; image bytes are discarded after OCR. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost] + [RequestSizeLimit(MaxCropBytes + 16 * 1024)] + [Consumes("multipart/form-data")] + public async Task Recognize(Guid cameraId, IFormFile? image, CancellationToken ct) + { + if (!options.CurrentValue.Enabled) return StatusCode(503, new { error = "Local plate OCR is disabled" }); + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + if (image is null || image.Length is < 16 or > MaxCropBytes || image.Length > options.CurrentValue.MaxImageBytes || + image.ContentType is not ("image/jpeg" or "image/png")) + return BadRequest(new { error = "Provide a JPEG or PNG plate crop up to 512 KiB" }); + + await using var input = image.OpenReadStream(); + using var buffer = new MemoryStream((int)image.Length); + await input.CopyToAsync(buffer, ct); + var bytes = buffer.ToArray(); + var png = bytes.AsSpan().StartsWith(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }); + var jpeg = bytes.AsSpan().StartsWith(new byte[] { 255, 216, 255 }); + if (!png && !jpeg) return BadRequest(new { error = "Image content does not match JPEG or PNG" }); + + var result = await recognition.RecognizeAsync(cameraId, bytes, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 422, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 5e00620..557b133 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -4109,4 +4109,8 @@ Watch live Stop live Live view is unavailable. Check the media service and camera access. + Local plate reading (manual action) + Select a JPEG/PNG crop of the plate. The image is processed on this Heimdall server and deleted afterward; only the plate observation and history event are stored. Enable the feature in configuration first. + Select a JPEG or PNG crop no larger than 512 KiB. + Plate {0} recognized with {1}% confidence; an event was added to history. diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 7773b7a..456a691 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4109,4 +4109,8 @@ Voir en direct Arrêter le direct Le direct est indisponible. Vérifiez le service média et les droits caméra. + Lecture de plaque locale (action manuelle) + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. + Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index a2306e9..0f31954 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4109,4 +4109,8 @@ Watch live Stop live Live view is unavailable. Check the media service and camera access. + Lecture de plaque locale (action manuelle) + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. + Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 0542169..a8811c9 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -3,6 +3,7 @@ using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; namespace Heimdall.Web.Services; @@ -514,6 +515,22 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } + public async Task> RecognizePlateCropAsync( + Guid cameraId, Stream image, string contentType, string fileName, CancellationToken ct = default) + { + using var content = new MultipartFormDataContent(); + using var imageContent = new StreamContent(image); + imageContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + content.Add(imageContent, "image", Path.GetFileName(fileName)); + using var response = await CreateClient().PostAsync($"api/cameras/{cameraId:D}/plate-recognition", content, ct); + if (!response.IsSuccessStatusCode) + return ApiResult.Failure(await ReadErrorMessageAsync(response)); + var result = await response.Content.ReadFromJsonAsync(Json, ct); + return result is null + ? ApiResult.Failure(InvalidServerResponse) + : ApiResult.Success(result); + } + public async Task?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20) { var client = CreateClient(); diff --git a/src/Heimdall.Web/wwwroot/js/live-view.js b/src/Heimdall.Web/wwwroot/js/live-view.js index f297a07..b274b26 100644 --- a/src/Heimdall.Web/wwwroot/js/live-view.js +++ b/src/Heimdall.Web/wwwroot/js/live-view.js @@ -36,8 +36,8 @@ export async function stop(cameraId) { const s = active.get(cameraId); if (!s) return; active.delete(cameraId); - s.pc.close(); if (s.resource) { try { await fetch(s.resource, { method: "DELETE", headers: { Authorization: `Bearer ${s.token}` } }); } catch { } } + s.pc.close(); try { await fetch(`/api/live-media/cameras/${cameraId}/session/${s.sessionId}`, { method: "DELETE", credentials: "same-origin" }); } catch { } const v = document.querySelector(`[data-live-camera="${cameraId}"]`); if (v) v.srcObject = null; diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 8e65235..dadca78 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -485,21 +485,63 @@ public class ConfigReceiverServiceTests { var cameraId = Guid.NewGuid(); var settings = new Dictionary { [$"camera.{cameraId}.enabled"] = "true" }; - var handler = new RetryingCameraAckHandler(settings); + var expectedVersion = CameraConfigVersion.Compute(settings); + var configFetches = 0; + var ackAttempts = 0; + var persistedAcks = 0; + var acknowledgedVersions = new List(); + var builder = WebApplication.CreateBuilder(); + var fixturePort = int.TryParse(Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_PORT"), out var configuredPort) && + configuredPort is > 0 and <= 65535 ? configuredPort : 0; + var fixtureBindHost = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_BIND_HOST") ?? "127.0.0.1"; + var fixtureApiKey = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_API_KEY") ?? "fixture-key"; + builder.WebHost.UseUrls($"http://{fixtureBindHost}:{fixturePort}"); + builder.Logging.ClearProviders(); + await using var central = builder.Build(); + central.MapGet("/api/settings/agent/{id:guid}", (HttpContext context) => + { + Interlocked.Increment(ref configFetches); + if (!string.Equals(context.Request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal)) + return Results.Unauthorized(); + context.Response.Headers["X-Camera-Config-Version"] = expectedVersion; + return Results.Json(settings); + }); + central.MapPost("/api/settings/agent/{id:guid}/camera-config-ack", async (HttpRequest request) => + { + Interlocked.Increment(ref ackAttempts); + if (!string.Equals(request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal)) + return Results.Unauthorized(); + var ack = await request.ReadFromJsonAsync(); + if (ack is null || !string.Equals(ack.Version, expectedVersion, StringComparison.Ordinal)) + return Results.BadRequest(); + acknowledgedVersions.Add(ack.Version); + if (ackAttempts == 1) return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); + Interlocked.Increment(ref persistedAcks); + return Results.NoContent(); + }); + await central.StartAsync(); + var factory = Substitute.For(); - factory.CreateClient("Central").Returns(_ => new HttpClient(handler, disposeHandler: false)); + factory.CreateClient("Central").Returns(_ => new HttpClient()); var cameraStore = new CameraConfigStore(); - var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture-key" }; - using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore); + var configurationApplications = 0; + cameraStore.Changed += (_, _) => Interlocked.Increment(ref configurationApplications); + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = fixtureApiKey }; + using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore, + centralUrl: fixturePort == 0 ? central.Urls.Single() : $"http://127.0.0.1:{fixturePort}"); var fetch = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync", BindingFlags.NonPublic | BindingFlags.Instance); fetch.ShouldNotBeNull(); await (Task)fetch.Invoke(service, [CancellationToken.None])!; - handler.AcknowledgementAttempts.ShouldBe(2); + configFetches.ShouldBe(1); + ackAttempts.ShouldBe(2); + persistedAcks.ShouldBe(1); + acknowledgedVersions.ShouldBe([expectedVersion, expectedVersion]); + configurationApplications.ShouldBe(1); cameraStore.Cameras.ShouldHaveSingleItem().CameraId.ShouldBe(cameraId); - cameraStore.CurrentVersion.ShouldBe(CameraConfigVersion.Compute(settings)); + cameraStore.CurrentVersion.ShouldBe(expectedVersion); } [Fact] @@ -557,31 +599,7 @@ public class ConfigReceiverServiceTests } } - private sealed class RetryingCameraAckHandler : HttpMessageHandler - { - private readonly IReadOnlyDictionary _settings; - private int _acknowledgementAttempts; - - public RetryingCameraAckHandler(IReadOnlyDictionary settings) => _settings = settings; - public int AcknowledgementAttempts => Volatile.Read(ref _acknowledgementAttempts); - - protected override Task SendAsync(HttpRequestMessage request, - CancellationToken cancellationToken) - { - if (request.Method == HttpMethod.Post) - { - var attempt = Interlocked.Increment(ref _acknowledgementAttempts); - return Task.FromResult(new HttpResponseMessage(attempt == 1 - ? System.Net.HttpStatusCode.ServiceUnavailable - : System.Net.HttpStatusCode.NoContent)); - } - - var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) - { Content = JsonContent.Create(_settings) }; - response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(_settings)); - return Task.FromResult(response); - } - } + private sealed record CameraConfigAckRequest(string Version); /// Captures formatted log messages for assertions (in-memory, no sinks). private sealed class ListLoggerProvider : ILoggerProvider diff --git a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs index 63b3db8..1834f3d 100644 --- a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs +++ b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs @@ -1,6 +1,11 @@ using System.Text; +using System.Net; using Heimdall.Agent.Services; +using Heimdall.Application.DTOs; +using Heimdall.Mdns; using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Microsoft.Extensions.Logging; using Shouldly; namespace Heimdall.Agent.Tests; @@ -35,4 +40,159 @@ public class HomeKitMdnsProbeTests var probe = new HomeKitMdnsProbe(NullLogger.Instance); probe.ShouldNotBeNull(); } -} \ No newline at end of file + + [Fact] + public async Task DiscoverAsync_MapsCameraAnnouncementIntoAgentDevice() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns([new MdnsDiscoveredDevice + { + Address = IPAddress.Parse("192.0.2.40"), + InstanceName = "Front Door._hap._tcp.local", + Port = 51926, + HomeKitInfo = new HomeKitDeviceInfo + { + Name = "Front Door", DeviceId = "AA:BB:CC:DD:EE:FF", Model = "TestCam", + Category = 18, IsPaired = true, Port = 51926 + } + }]); + + var devices = await new HomeKitMdnsProbe(mdns, NullLogger.Instance) + .DiscoverAsync(); + + devices.ShouldHaveSingleItem().ShouldBe(new HomeKitDevice( + "192.0.2.40", "Front Door", "AA:BB:CC:DD:EE:FF", "TestCam", 18, true, 51926)); + await mdns.Received(1).DiscoverMulticastAsync( + Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DiscoverAsync_Canceled_ReturnsEmpty() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new OperationCanceledException()); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + (await new HomeKitMdnsProbe(mdns, NullLogger.Instance) + .DiscoverAsync(cts.Token)).ShouldBeEmpty(); + } + + [Fact] + public async Task NetworkCameraScanner_MapsHomeKitDiscoveryIntoCentralPayloadShape() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns([new MdnsDiscoveredDevice + { + Address = IPAddress.Parse("192.0.2.41"), + InstanceName = "Garden._hap._tcp.local", + Port = 51927, + HomeKitInfo = new HomeKitDeviceInfo + { + Name = "Garden", DeviceId = "AA:BB:CC:DD:EE:11", Model = "Doorbell", + Category = 18, IsPaired = false, Port = 51927 + } + }]); + var probe = new HomeKitMdnsProbe(mdns, NullLogger.Instance); + var scanner = new NetworkCameraScanner(NullLogger.Instance, + NullLoggerFactory.Instance, probe); + + var result = await scanner.DiscoverHomeKitAsync(CancellationToken.None); + + var discovered = result.ShouldHaveSingleItem(); + discovered.Ip.ShouldBe("192.0.2.41"); + discovered.OpenPorts.ShouldBe([51927]); + discovered.Vendor.ShouldBe("Apple"); + discovered.HomeKitName.ShouldBe("Garden"); + discovered.HomeKitDeviceId.ShouldBe("AA:BB:CC:DD:EE:11"); + discovered.HomeKitModel.ShouldBe("Doorbell"); + discovered.HomeKitCategory.ShouldBe(18); + discovered.HomeKitIsPaired.ShouldBe(false); + discovered.HomeKitPort.ShouldBe(51927); + } + + [Fact] + public void ParseMulticastResponses_ResolvesSrvHostAndNeverBorrowsAnotherHostAddress() + { + var packet = BuildAnnouncement( + unrelatedHost: "other.local", unrelatedIp: "192.0.2.99", + instance: "Porch._hap._tcp.local", target: "porch.local", ip: "192.0.2.18"); + + var camera = MdnsClient.ParseMulticastResponses([packet]).ShouldHaveSingleItem(); + + camera.Address.ShouldBe(IPAddress.Parse("192.0.2.18")); + camera.Port.ShouldBe(51926); + camera.HomeKitInfo!.Category.ShouldBe(17); + camera.HomeKitInfo.IsPaired.ShouldBeTrue(); + camera.HomeKitInfo.DeviceId.ShouldBe("AA:BB:CC:DD:EE:18"); + } + + [Fact] + public void ParseMulticastResponses_DoesNotAssignUnrelatedAddressWhenSrvHostIsUnresolved() + { + var packet = BuildAnnouncement( + unrelatedHost: "other.local", unrelatedIp: "192.0.2.99", + instance: "Porch._hap._tcp.local", target: "missing.local", ip: null); + + MdnsClient.ParseMulticastResponses([packet]).ShouldBeEmpty(); + } + + private static byte[] BuildAnnouncement( + string unrelatedHost, string unrelatedIp, string instance, string target, string? ip) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: true); + writer.Write(new byte[2]); // transaction id + WriteUInt16(writer, 0x8400); // authoritative response + WriteUInt16(writer, 0); // questions + WriteUInt16(writer, (ushort)(ip is null ? 4 : 5)); // answers + WriteUInt16(writer, 0); // authority + WriteUInt16(writer, 0); // additional + WriteRecord(writer, "_hap._tcp.local", 12, EncodeName(instance)); + using (var srv = new MemoryStream()) + using (var srvWriter = new BinaryWriter(srv, Encoding.ASCII, leaveOpen: true)) + { + WriteUInt16(srvWriter, 0); WriteUInt16(srvWriter, 0); WriteUInt16(srvWriter, 51926); + srvWriter.Write(EncodeName(target)); + WriteRecord(writer, instance, 33, srv.ToArray()); + } + var txt = new byte[] { 5, (byte)'c', (byte)'i', (byte)'=', (byte)'1', (byte)'7', + 4, (byte)'s', (byte)'f', (byte)'=', (byte)'0', + 20, (byte)'i', (byte)'d', (byte)'=', (byte)'A', (byte)'A', (byte)':', (byte)'B', (byte)'B', (byte)':', (byte)'C', (byte)'C', (byte)':', (byte)'D', (byte)'D', (byte)':', (byte)'E', (byte)'E', (byte)':', (byte)'1', (byte)'8' }; + WriteRecord(writer, instance, 16, txt); + WriteRecord(writer, unrelatedHost, 1, IPAddress.Parse(unrelatedIp).GetAddressBytes()); + if (ip is not null) + WriteRecord(writer, target, 1, IPAddress.Parse(ip).GetAddressBytes()); + writer.Flush(); + return stream.ToArray(); + } + + private static void WriteRecord(BinaryWriter writer, string name, ushort type, byte[] data) + { + writer.Write(EncodeName(name)); + WriteUInt16(writer, type); WriteUInt16(writer, 1); // IN + writer.Write(new byte[] { 0, 0, 0, 120 }); + WriteUInt16(writer, (ushort)data.Length); + writer.Write(data); + } + + private static byte[] EncodeName(string name) + { + using var stream = new MemoryStream(); + foreach (var label in name.Split('.')) + { + var bytes = Encoding.ASCII.GetBytes(label); + stream.WriteByte((byte)bytes.Length); stream.Write(bytes); + } + stream.WriteByte(0); + return stream.ToArray(); + } + + private static void WriteUInt16(BinaryWriter writer, ushort value) + { + writer.Write((byte)(value >> 8)); writer.Write((byte)value); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png b/tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png new file mode 100644 index 0000000..248b75b Binary files /dev/null and b/tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png differ diff --git a/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj b/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj index 2c5b078..2e150a5 100644 --- a/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj +++ b/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj @@ -22,10 +22,14 @@ + + + + - \ No newline at end of file + diff --git a/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs b/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs new file mode 100644 index 0000000..9338803 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs @@ -0,0 +1,44 @@ +using Heimdall.Infrastructure.Services; +using Shouldly; +using Xunit; + +namespace Heimdall.Infrastructure.Tests; + +public sealed class PlateOcrTests +{ + [Fact] + public void Parses_synthetic_tsv_word_and_confidence() + { + const string fixture = "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n" + + "5\t1\t1\t1\t1\t1\t0\t0\t100\t30\t92.5\tAB-123-CD\n"; + + var result = TesseractPlateOcr.ParseTsv(fixture); + + result.ShouldNotBeNull(); + result!.Text.ShouldBe("AB-123-CD"); + result.Confidence.ShouldBe(0.925); + } + + [Fact] + public void Rejects_empty_or_unconfident_tsv_rows() + { + var result = TesseractPlateOcr.ParseTsv("header\n5\t1\t1\t1\t1\t1\t0\t0\t1\t1\t-1\t"); + result.ShouldBeNull(); + } + + [Fact] + public void OCR_options_are_bounded_when_enabled() + { + new PlateOcrOptions { Enabled = true, MaxImageBytes = 128 }.IsValid().ShouldBeFalse(); + new PlateOcrOptions { Enabled = true, TimeoutSeconds = 100 }.IsValid().ShouldBeFalse(); + new PlateOcrOptions { Enabled = false, MaxImageBytes = 0 }.IsValid().ShouldBeTrue(); + } + + [Fact] + public void Accepts_bounded_synthetic_plate_crop_and_rejects_invalid_bytes() + { + var fixture = File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-plate.png")); + TesseractPlateOcr.IsSafeImage(fixture).ShouldBeTrue(); + TesseractPlateOcr.IsSafeImage(new byte[32]).ShouldBeFalse(); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs b/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs new file mode 100644 index 0000000..5f36f76 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs @@ -0,0 +1,27 @@ +using Heimdall.Infrastructure.Storage; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests.Storage; + +public sealed class RecordingStorageQuotaOptionsTests +{ + private readonly DataAnnotationValidateOptions _validator = + new(RecordingStorageQuotaOptions.SectionName); + + [Fact] + public void PositiveQuota_IsValid() + { + _validator.Validate(RecordingStorageQuotaOptions.SectionName, + new RecordingStorageQuotaOptions { MaxBytes = 24 }).Succeeded.ShouldBeTrue(); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonPositiveQuota_IsRejected(long maxBytes) + { + _validator.Validate(RecordingStorageQuotaOptions.SectionName, + new RecordingStorageQuotaOptions { MaxBytes = maxBytes }).Failed.ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs index b2c06a3..1732bc0 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs @@ -23,7 +23,7 @@ public abstract class PostgresTestBase : IAsyncLifetime protected PostgresTestBase(PostgreSqlContainerFixture postgres) { _postgres = postgres; - _connectionString = postgres.ConnectionString; + _connectionString = postgres.IsAvailable ? postgres.ConnectionString : string.Empty; _factoryLazy = new Lazy( () => new HeimdallWebApplicationFactory(postgres.ConnectionString)); } diff --git a/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs b/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs new file mode 100644 index 0000000..ee6166f --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs @@ -0,0 +1,200 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.IntegrationTests.Factories; +using Heimdall.TestCommon; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.EntityFrameworkCore; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public sealed class RecordingQuotaTests : PostgresTestBase +{ + private readonly PostgreSqlContainerFixture _postgres; + + public RecordingQuotaTests(PostgreSqlContainerFixture postgres) : base(postgres) + { + _postgres = postgres; + } + + [Fact] + public async Task ConcurrentAgentUploads_DoNotExceedConfiguredCentralQuota() + { + if (!_postgres.IsAvailable) return; + + var storage = new BarrierRecordingStorage(expectedConcurrentUploads: 2); + await using var quotaFactory = new HeimdallWebApplicationFactory(_postgres.ConnectionString, + recordingQuotaMaxBytes: 32, + configureTestServices: services => + { + services.RemoveAll(); + services.AddSingleton(storage); + services.RemoveAll(); + services.AddSingleton(storage); + }); + + var admin = await quotaFactory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = "Recording quota site", + timezone = "UTC" + }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var site = JsonDocument.Parse(await siteResponse.Content.ReadAsStringAsync()); + var siteId = site.RootElement.GetProperty("id").GetGuid(); + var registrationToken = site.RootElement.GetProperty("registrationToken").GetString(); + registrationToken.ShouldNotBeNullOrWhiteSpace(); + + var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new + { + token = registrationToken, + hostname = "recording-quota-agent", + version = "quota-test", + publicIp = (string?)null + }); + registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var agent = JsonDocument.Parse(await registerResponse.Content.ReadAsStringAsync()); + var agentId = agent.RootElement.GetProperty("agentId").GetGuid(); + var apiKey = agent.RootElement.GetProperty("apiKey").GetString(); + apiKey.ShouldNotBeNullOrWhiteSpace(); + + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Quota camera", + rtspUrl = "rtsp://quota-camera.invalid/stream", + manufacturer = "test", + model = "test" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var cameraJson = JsonDocument.Parse(await cameraResponse.Content.ReadAsStringAsync()); + var cameraId = cameraJson.RootElement.GetProperty("id").GetGuid(); + + var assignmentResponse = await admin.PostAsJsonAsync("api/assignments", new + { + cameraId, + agentId, + reason = "quota-test" + }); + assignmentResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var enableResponse = await admin.PutAsJsonAsync($"api/cameras/{cameraId}", new + { + name = "Quota camera", + rtspUrl = "rtsp://quota-camera.invalid/stream", + status = "Online", + recordingEnabled = true + }); + enableResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + + using var agentClient = quotaFactory.CreateClient(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey); + var timestamp = Uri.EscapeDataString(DateTime.UtcNow.ToString("O")); + // Force two first attempts with the same id to finish object upload before either + // can persist metadata. The loser must not overwrite the winner's object key. + var racedId = Guid.NewGuid(); + var racedUploads = await Task.WhenAll( + UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....AAAA"u8.ToArray()), + UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....BBBB"u8.ToArray())); + racedUploads.Select(response => response.StatusCode).Distinct().ShouldBe([HttpStatusCode.OK]); + string racedStoragePath; + await using (var scope = quotaFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + (await db.Recordings.CountAsync(recording => recording.Id == racedId)).ShouldBe(1); + racedStoragePath = await db.Recordings.Where(recording => recording.Id == racedId) + .Select(recording => recording.StoragePath).SingleAsync(); + } + var racedKeyParts = racedStoragePath.Split('/'); + racedKeyParts.Length.ShouldBe(4); + racedKeyParts[0].ShouldBe("recordings"); + racedKeyParts[1].ShouldBe(cameraId.ToString("D")); + racedKeyParts[2].ShouldBe(racedId.ToString("D")); + Guid.TryParseExact(Path.GetFileNameWithoutExtension(racedKeyParts[3]), "N", out _).ShouldBeTrue(); + storage.ObjectCount.ShouldBe(1); + + var firstId = Guid.NewGuid(); + var secondId = Guid.NewGuid(); + var responses = await Task.WhenAll( + UploadAsync(agentClient, cameraId, firstId, timestamp), + UploadAsync(agentClient, cameraId, secondId, timestamp)); + responses.Select(response => response.StatusCode) + .OrderBy(status => (int)status) + .ShouldBe(new[] { HttpStatusCode.OK, (HttpStatusCode)507 }); + var denied = responses.Single(response => (int)response.StatusCode == 507); + (await denied.Content.ReadAsStringAsync()).Contains("quota exceeded", StringComparison.OrdinalIgnoreCase) + .ShouldBeTrue(); + storage.ObjectCount.ShouldBe(2); + + var accepted = responses.Single(response => response.StatusCode == HttpStatusCode.OK); + using var acceptedJson = JsonDocument.Parse(await accepted.Content.ReadAsStringAsync()); + var acceptedId = acceptedJson.RootElement.GetProperty("id").GetGuid(); + await using (var scope = quotaFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + (await db.Recordings.CountAsync()).ShouldBe(2); + (await db.Recordings.SumAsync(recording => recording.SizeBytes)).ShouldBe(32); + } + + var retry = await UploadAsync(agentClient, cameraId, acceptedId, timestamp); + retry.StatusCode.ShouldBe(HttpStatusCode.OK); + storage.ObjectCount.ShouldBe(2); + } + + private static Task UploadAsync(HttpClient client, Guid cameraId, Guid recordingId, + string timestamp, byte[]? bytes = null) + { + var content = new ByteArrayContent(bytes ?? "....ftyp....1234"u8.ToArray()); + content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4"); + return client.PutAsync( + $"api/cameras/{cameraId}/recordings/{recordingId}/content?timestamp={timestamp}&durationSeconds=1", + content); + } + + private sealed class BarrierRecordingStorage(int expectedConcurrentUploads) : IRecordingStorage, IStorageObjectDeletion + { + private readonly ConcurrentDictionary _objects = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _uploadBarriers = new(); + private int _uploads; + + public int ObjectCount => _objects.Count; + + public StorageLocation CaptureCurrentLocation() => + new(StorageProvider.Local, LocalRoot: "/quota-test-recordings"); + + public async Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, + CancellationToken ct = default) + { + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + _objects[key] = buffer.ToArray(); + var uploadNumber = Interlocked.Increment(ref _uploads); + var batch = (uploadNumber - 1) / expectedConcurrentUploads; + var barrier = _uploadBarriers.GetOrAdd(batch, + _ => new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + if (uploadNumber % expectedConcurrentUploads == 0) + barrier.TrySetResult(); + await barrier.Task.WaitAsync(ct); + } + + public Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) + => Task.FromResult(_objects.TryGetValue(key, out var bytes) ? new MemoryStream(bytes, writable: false) : null); + + public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default) + => Task.FromResult(null); + + public Task DeleteBatchAsync(IReadOnlyCollection keys, StorageLocation location, + CancellationToken ct = default) + { + foreach (var key in keys) _objects.TryRemove(key, out _); + return Task.CompletedTask; + } + } +} diff --git a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs index f09f696..9392097 100644 --- a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs +++ b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc.Testing; using Heimdall.Application.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Globalization; namespace Heimdall.IntegrationTests.Factories; @@ -13,11 +14,16 @@ namespace Heimdall.IntegrationTests.Factories; public class HeimdallWebApplicationFactory : WebApplicationFactory { private readonly string _connectionString; + private readonly long? _recordingQuotaMaxBytes; + private readonly Action? _configureTestServices; /// Creates a factory connected to a real PostgreSQL instance via Testcontainers. - public HeimdallWebApplicationFactory(string connectionString) + public HeimdallWebApplicationFactory(string connectionString, long? recordingQuotaMaxBytes = null, + Action? configureTestServices = null) { _connectionString = connectionString; + _recordingQuotaMaxBytes = recordingQuotaMaxBytes; + _configureTestServices = configureTestServices; } protected override void ConfigureWebHost(IWebHostBuilder builder) @@ -27,6 +33,8 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory builder.UseSetting("ConnectionStrings:Default", _connectionString); builder.UseSetting("Database:MigrateOnStartup", "true"); + if (_recordingQuotaMaxBytes is long maxBytes) + builder.UseSetting("Recordings:StorageQuota:MaxBytes", maxBytes.ToString(CultureInfo.InvariantCulture)); // JWT config builder.UseSetting("Jwt:Key", "ThisIsATestKeyThatIsAtLeast32BytesLong!"); @@ -43,6 +51,7 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory { services.RemoveAll(); services.AddScoped(); + _configureTestServices?.Invoke(services); }); } } diff --git a/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs new file mode 100644 index 0000000..6649725 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs @@ -0,0 +1,26 @@ +using Heimdall.Api.Controllers; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using NSubstitute; +using Xunit; + +namespace Heimdall.Web.Tests.Controllers; + +public sealed class PlateRecognitionControllerTests +{ + [Fact] + public async Task Recognition_is_disabled_by_default_and_does_not_call_OCR() + { + var config = Substitute.For>(); + config.CurrentValue.Returns(new PlateOcrOptions()); + var service = Substitute.For(); + var controller = new PlateRecognitionController(null!, service, config); + + var result = await controller.Recognize(Guid.NewGuid(), null, CancellationToken.None); + + Assert.Equal(503, Assert.IsType(result).StatusCode); + await service.DidNotReceiveWithAnyArgs().RecognizeAsync(default, default, default); + } +} diff --git a/todo.md b/todo.md index d0eecf1..ede68d8 100644 --- a/todo.md +++ b/todo.md @@ -32,25 +32,25 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. -- [ ] **AGENT-08** Reconnexion, remplacement atomique du snapshot caméra et ACK exact par digest sont couverts par les fixtures SignalR/HTTP de `ConfigReceiverServiceTests`. L’ACK réessaie maintenant jusqu’à trois fois après une erreur transitoire (test 503 puis 204 : 1/1; suite Agent de référence avant ce changement : 388/388). La suite Agent passe maintenant 389/389 après ce changement; la recette Compose isolée reste à lancer quand le créneau Docker sera libre. La validation sur Agent déployé avec caméra réelle et coupure réseau reste ouverte. +- [ ] **AGENT-08** Le Central simulé par Kestrel sert une configuration une seule fois; l’Agent applique une fois son snapshot, envoie deux ACK avec le même digest après un HTTP 503, puis Central persiste exactement un ACK avec HTTP 204. Test ciblé 1/1 et suite Agent 399/399 réussis localement. La recette Compose isolée construite depuis les dépendances source avec SDK 10.0.100 a exécuté le test Kestrel : configuration GET une fois, ACK même digest après 503 puis 204, application snapshot une fois, résultat 1/1. Le projet `hmdack_8df77197` a été démonté; conteneurs, volumes, réseau et source temporaire vérifiés/supprimés à 0. La validation sur Agent/caméra réels et coupure réseau reste ouverte. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [x] **Accès caméra #141** Les PR #65/#88/#100 valident API, remplacement UI atomique, chargement paginé, protection du brouillon et révocation des grants excédentaires (>500). Validation complétée sur la branche de clôture : `ResourceAccessTests` vérifie l’union direct + groupe et la révocation live; `HttpIsolationTests` exerce le pipeline HTTP avec périmètres; un test bUnit `GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera` vérifie l’affichage site/caméra et les appels d’ajout/retrait depuis l’UI. Les tests couvrent les priorités d’accès dans l’interface et la révocation; aucune caméra physique n’est requise pour cette gestion des autorisations. Skill dédiée : `skills/camera-access-groups/SKILL.md`. - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. -- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Restent l’aller-retour S3 et les mesures RPO/RTO sur installation/données réelles. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. +- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Le 5 novembre 2026, le projet `hmdbk_a466d0ce` a vérifié le dump S3 daté, `latest.sql.gz`, sa restauration avec retour de `after-backup` à `before-restore`, l’upload protégé et le miroir RustFS/manifest. La recette a aussi révélé que l’ancien téléchargement de `mc` échouait en HTTP 410 et que BusyBox `date` ne calculait pas les seuils relatifs; Compose installe maintenant AWS CLI, Bash et GNU coreutils, et chaque appel AWS reçoit les clés configurées. Une nouvelle acceptance depuis `docker/docker-compose.backup.yml` + overlay jetable a vérifié le roundtrip PostgreSQL `after-backup`→`before-restore`, la purge de clés journalières et hebdomadaires anciennes, le manifeste RustFS et l’upload protégé; teardown vérifié à 0 conteneur/volume/réseau. Les mesures RPO/RTO sur installation/données réelles restent externes. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. ## P2 — fonctionnalités et exploitation - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. -- [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Après correctif, un conteneur basé sur CUDA sans device a répondu 200 sur `/health/live`, mais une publication Agent CPU bind-mountée masquait ses bibliothèques ONNX GPU; l’absence de Central/token a aussi interrompu l’enregistrement. Cela valide le garde-fou startup, pas le paquet GPU final. Restent rebuild de l’image GPU post-correctif, acceptation avec Central + token et preuve d’inférence CPU sans device, puis GPU NVIDIA réel. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut, limites fichier/dimensions/délai et suppression du crop temporaire. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. L’acceptation Agent n’est pas concluante: les `docker create` de `agent-state-init` sont restés bloqués/ont fait conflit dans le daemon partagé; aucun Agent GPU n’a démarré, donc pas de preuve healthz/enregistrement/inférence CPU dans cette image. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent l’acceptation complète de l’Agent CUDA sans device (inscription, frame synthétique et inférence CPU effective), puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. -- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. +- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` à revérifier après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures.