diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index d8be3e2..907907b 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -152,4 +152,5 @@ jobs: AGENT_REGISTRY_USER: ${{ secrets.AGENT_REGISTRY_USER }} AGENT_REGISTRY_TOKEN: ${{ secrets.AGENT_REGISTRY_TOKEN }} RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} + RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }} run: bash scripts/ci/publish.sh diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md new file mode 100644 index 0000000..7342367 --- /dev/null +++ b/docs/agent-release-signing.md @@ -0,0 +1,38 @@ +# Signatures des mises à jour Agent + +Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. Central transmet le manifeste et sa signature, mais ne fournit jamais la clé de confiance aux Agents. Chaque Agent lit sa clé publique depuis un fichier local monté ou installé par l’exploitant. + +## Préparer les clés + +Créer une paire ECDSA P-256 hors du dépôt et conserver la clé privée dans le coffre de secrets CI : + +```sh +openssl ecparam -name prime256v1 -genkey -noout -out agent-release-private.pem +openssl pkey -in agent-release-private.pem -pubout -out agent-release-public.pem +base64 -w0 agent-release-private.pem +``` + +La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Distribuer `agent-release-public.pem` par un canal d’administration indépendant de Central. La publication d’une release échoue si le secret de signature manque. + +La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. + +## Installer un Agent natif + +Installer les dépendances `.NET 10`, `jq`, `openssl` et `python3`, puis exécuter le script d’installation avec sa copie locale de la clé publique : + +```sh +sudo bash install/install-agent.sh \ + --central-url https://central.example.org \ + --site-token 'JETON_DE_SITE' \ + --update-public-key /chemin/local/agent-release-public.pem +``` + +Le script lit le manifeste signé via Central, vérifie la signature et l’archive, puis installe la release sous `/opt/heimdall/agent/releases/`. Le service utilise le lien `current`; lors d’une mise à jour, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue. Garder ensemble `install-agent.sh` et `agent-supervisor.py` lors d’une installation depuis une copie des scripts. + +Pour un Agent Docker, monter la clé publique en lecture seule dans le conteneur et définir `Agent__UpdatePublicKeyPath` vers ce fichier. L’Agent refuse la mise à jour si le chemin ou la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. + +## Rotation + +Une rotation de clé exige de déployer d’abord la nouvelle clé publique sur chaque Agent par le canal d’administration local. Publier ensuite les releases avec la nouvelle clé privée. Les Agents non mis à jour refusent ces releases; aucun remplacement automatique de la clé via Central n’est autorisé. Conserver une procédure de retour arrière et la dernière release vérifiée pendant la transition. + +La CI distante doit encore démontrer une release signée complète sur un runner capable de joindre la forge et le registre. Les plateformes autres que l’installation Linux gérée restent à valider sur leurs environnements cibles. diff --git a/docs/audits/2026-10-20-audit-complet.md b/docs/audits/2026-10-20-audit-complet.md index 88c4714..d64bb72 100644 --- a/docs/audits/2026-10-20-audit-complet.md +++ b/docs/audits/2026-10-20-audit-complet.md @@ -1,10 +1,10 @@ # Audit fonctionnel et technique Heimdall -Date de l’audit initial : 20 octobre 2026. Révision initiale : `7792353`. La matrice « État des corrections » ci-dessus fait foi pour le suivi au 22 octobre 2026. +Date de l’audit initial : 20 octobre 2026. Révision initiale : `7792353`. La matrice « État des corrections » ci-dessous fait foi pour le suivi au 23 octobre 2026. -## État des corrections au 22 octobre 2026 +## État des corrections au 23 octobre 2026 -La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les constats restent utiles pour comprendre le défaut, mais leur état opérationnel est désormais celui de cette matrice. Au 22 octobre, `main` inclut les PR #2–#54. Les PR #52 et #53 mettent à jour les guides et filtrent la CI pour les changements sans incidence sur le build. Les PR #38–#44 durcissent le diagnostic et l’enrôlement agent, les mises à jour, l’image depuis Central, les rapports de statut et le tri des utilisateurs. La PR #45 traite PIPE-10, la #46 raccorde les détections aux notifications, la #47 sécurise la rétention des recordings, la #49 persiste leur destination historique, la #50 corrige le filtrage par identité dans l’historique et la #51 expose l’état réel de capture dans `/healthz`. Le run #155 a compilé les projets et révélé sept erreurs héritées dans les notifications, l’agent Docker et le spool SQLite; elles ont été corrigées dans la PR #49. Le run #161 a compilé `Heimdall.Agent.dll` après correction de deux erreurs, puis a échoué lors de la copie des runtimes vers les tests faute d’espace disque; aucun test n’a démarré. Les essais #156–#160 ont aussi été interrompus par des erreurs réseau au checkout. Domain compile localement avec SDK 10.0.112; les tests et la compilation complète restent à confirmer sur un runner fonctionnel. Les PR antérieures et leurs résultats restent détaillés ci-dessous; la publication d’une release n’a pas été exercée. +La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les constats restent utiles pour comprendre le défaut, mais leur état opérationnel est désormais celui de cette matrice. Au 23 octobre, `main` inclut les PR #2–#58, dont la capture manuelle corrélée, son statut durable, la configuration caméra atomique et les miniatures des nouveaux JPEG. Les PR #52 et #53 mettent à jour les guides et filtrent la CI pour les changements sans incidence sur le build. Les PR #38–#44 durcissent le diagnostic et l’enrôlement agent, les mises à jour, l’image depuis Central, les rapports de statut et le tri des utilisateurs. La PR #45 traite PIPE-10, la #46 raccorde les détections aux notifications, la #47 sécurise la rétention des recordings, la #49 persiste leur destination historique, la #50 corrige le filtrage par identité dans l’historique et la #51 expose l’état réel de capture dans `/healthz`. Le run #155 a compilé les projets et révélé sept erreurs héritées dans les notifications, l’agent Docker et le spool SQLite; elles ont été corrigées dans la PR #49. Le run #161 a compilé `Heimdall.Agent.dll` après correction de deux erreurs, puis a échoué lors de la copie des runtimes vers les tests faute d’espace disque; aucun test n’a démarré. Les essais #156–#160 ont aussi été interrompus par des erreurs réseau au checkout. La solution complète compile localement avec SDK 10.0.402 sans avertissement ni erreur; les CI #176 et #178 échouent avant checkout car le conteneur runner ne peut pas joindre la forge. La publication d’une release reste à confirmer sur un runner fonctionnel. Les PR antérieures et leurs résultats restent détaillés ci-dessous; la publication d’une release n’a pas été exercée. | État | Constats | Preuve / réserve | |---|---|---| @@ -14,14 +14,17 @@ La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les | Corrigé dans son périmètre UI | UI-01 | PR #10 ; filtres et pagination serveur de la galerie. L’ingestion et la lecture sécurisée des médias restent PIPE-09. | | Corrigé | UI-04 | PR #5, #14, #16 ; stabilisation de la session et des attentes navigateur. Le run #64 passe les 34 tests E2E. | | Partiellement validé | BUILD-01 | PR #3, #13–#18 ; run #64 vert (tests, images et scans). Protection bloquante des branches, reproductibilité sur builds propres et publication d’une release taguée restent à démontrer sur l’instance Gitea. | -| Corrigé et validé CI | OPS-05 | PR #18, run #64 vert sur `0bde726` : manifeste accessible par identité agent, ordre manuel ciblé via ConfigHub, traitement natif/Docker. | -| Corrigé et fusionné | AGENT-01 à AGENT-07, PIPE-10, FEAT-05, OPS-01 (recordings) | PR #38–#43, #45–#47. PIPE-10 utilise un spool SQLite stable; FEAT-05 crée une alerte par destinataire caméra autorisé et enfile les canaux externes; OPS-01 supprime les objets avant leurs références SQL. Les runs récents n’ont pas pu valider ces changements à cause des runners. | -| Partiellement corrigé | OPS-02 | PR #49 capture la destination des nouveaux recordings. Le raccordement des snapshots ajoute cette provenance aux nouveaux événements, la lecture depuis l’ancienne destination et la suppression avant effacement d’événement ou de partition. Les références anciennes, les objets staging et les autres médias restent à réconcilier. | -| Partiellement corrigé | PIPE-09 | PR #54 : la capture issue de l’analyse est conservée avec l’événement dans le spool SQLite, puis téléversée vers une destination enregistrée. Une lecture sous contrôle d’accès caméra remplace les URL publiques pour les nouveaux JPEG. La solution compile avec SDK 10.0.402; 25 tests ciblés et le test d’intégration PostgreSQL passent localement. Capture manuelle, miniatures et validation sur caméra réelle restent ouvertes. | +| Partiellement validé | OPS-05 | PR #18, run #64 vert sur `0bde726` : manifeste accessible par identité agent et ordre manuel ciblé via ConfigHub. PR #58 ajoute les archives natives signées et leur rollback; une release et son installation réelles restent à démontrer. | +| Corrigé et fusionné | AGENT-01 à AGENT-05, AGENT-07, PIPE-10, FEAT-05, OPS-01 (recordings) | PR #38–#43, #45–#47. PIPE-10 utilise un spool SQLite stable; FEAT-05 crée une alerte par destinataire caméra autorisé et enfile les canaux externes; OPS-01 supprime les objets avant leurs références SQL. Les runs récents n’ont pas pu valider ces changements à cause des runners. | +| Partiellement corrigé | OPS-02 | PR #49 capture la destination des nouveaux recordings. Le raccordement des snapshots ajoute cette provenance aux nouveaux événements, la lecture depuis l’ancienne destination et la suppression avant effacement d’événement ou de partition. La PR #57 purge quotidiennement les objets staging âgés de plus de 24 h sur la destination active. La PR #58 réconcilie les objets finaux de snapshots dont la destination est connue, avec un délai de sept jours. Les références anciennes, les destinations perdues et les autres médias restent à réconcilier. | +| Partiellement corrigé | PIPE-09 | PR #54 : la capture issue de l’analyse est conservée avec l’événement dans le spool SQLite, puis téléversée vers une destination enregistrée. Une lecture sous contrôle d’accès caméra remplace les URL publiques pour les nouveaux JPEG. La solution compile avec SDK 10.0.402; 25 tests ciblés et le test d’intégration PostgreSQL passent localement. La capture manuelle corrélée utilise le prochain frame de l'agent, avec livraison par la même boîte d'envoi. La PR #57 a ajouté un statut persistant pour les commandes et leur échec. La PR #58 génère des miniatures pour les nouveaux JPEG et sert leur lecture sous contrôle d’accès caméra; la validation sur caméra réelle reste ouverte. | | Partiellement corrigé | UI-02 | PR #50 ajoute PersonId aux événements, filtre l’historique et les véhicules côté API et charge l’historique par pages. Le détecteur biométrique FEAT-03 devra renseigner PersonId lors de la création des événements pour que les nouvelles détections apparaissent par identité. | +| Partiellement corrigé | AGENT-06 | PR #58 : manifeste signé ECDSA P-256 vérifié par une clé publique locale indépendante de Central, archive native et image Docker liées aux digests. La clé CI et les clés publiques des installations doivent être provisionnées; release réelle et rollback matériel restent à valider. | +| Corrigé dans le périmètre configuration | AGENT-08 | PR #57 : snapshot caméra complet validé et remplacé atomiquement, version vérifiée, ACK persisté et visible sur l’agent. La version est une empreinte de contenu; les validations de reconnexion terrain restent à faire. | +| Partiellement corrigé | AGENT-10 | PR #58 sérialise les démarrages/arrêts du même flux et attend le nettoyage FFmpeg avant de libérer le quota. Les essais de charge et de redémarrage rapide sur matériel représentatif restent ouverts. | | Partiellement corrigé | AGENT-09 | PR #51 distingue capture et santé d’enregistrement, expose les identifiants caméras en retard, compteurs et date du dernier frame analysé dans `/healthz`. Les seuils et scénarios panne restent à valider sur un agent déployé. | | Corrigé dans le périmètre documentaire | DOC-01 | Les guides identifient le plan MVP comme historique, pointent vers l’audit comme état courant, décrivent les projets présents et corrigent routes et limites API. Les spécifications plus anciennes restent des descriptions de cible et ne prouvent pas la livraison. | -| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09 (capture manuelle, miniatures et validation terrain), OPS-02 (objets staging, autres médias et lignes historiques), UI-02 (liaison FEAT-03), FEAT-01, FEAT-02, FEAT-03, QA-01, AGENT-08, AGENT-09 (validation terrain), AGENT-10 | Parcours incomplets, références de stockage historiques impossibles à reconstituer pour les anciennes lignes et intégration de la provenance aux futurs uploads de médias; validations nécessitant des intégrations, du matériel ou de l’exploitation. | +| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09 (validation terrain), AGENT-06 (clés et release réelle), BUILD-01 (runner et publication), OPS-02 (autres médias, destinations perdues et lignes historiques), UI-02 (liaison FEAT-03), FEAT-01, FEAT-02, FEAT-03, QA-01, AGENT-09 (validation terrain), AGENT-10 (charge et arrêt sous contrainte) | Parcours incomplets, références de stockage historiques impossibles à reconstituer pour les anciennes lignes et intégration de la provenance aux futurs uploads de médias; validations nécessitant des intégrations, du matériel ou de l’exploitation. | | Corrigé et fusionné | UI-03 | PR #36, commit `56a6177` : digests quotidiens/hebdomadaires bornés en UTC sur `OccurredAt`, filtrés avec la politique caméra complète. Les tests Infrastructure passent (307/307); le build et les tests post-fusion #114 passent, ainsi que les archives, images et contrôles de sécurité. | | À valider hors CI | Vérifications complémentaires § ci-dessous | Caméras réelles, réseau/TURN, SMTP/ntfy, S3, charge et restauration de sauvegarde ne sont pas certifiés par le run automatisé. | @@ -216,7 +219,7 @@ Sources : `Agent/Services/DetectionReporterService.cs`, `Web/Controllers/EventsC L’agent publie les métadonnées mais n’upload pas le JPEG et ne raccorde pas l’image à l’événement. Les providers Upload/Download n’ont pas d’appel métier trouvé. Aucun endpoint de capture/upload/lecture caméra n’est exposé. Le bouton TakeSnapshot affiche seulement un snackbar puis Task.CompletedTask ; RefreshSnapshot relit l’historique. -Correction en cours : l’agent persiste le JPEG avec la détection et le rejoue après coupure réseau; Central vérifie l’identité agent, borne le corps JPEG, persiste la destination et sert l’image via une route autorisée à la caméra. Les suppressions d’événement et de partition retirent d’abord les objets gérés. Restent la commande manuelle avec corrélation, les miniatures, le nettoyage des objets orphelins et la réception sur caméra réelle. +Correction en cours : l’agent persiste le JPEG avec la détection et le rejoue après coupure réseau; Central vérifie l’identité agent, borne le corps JPEG, persiste la destination et sert l’image via une route autorisée à la caméra. Les suppressions d’événement et de partition retirent d’abord les objets gérés. Une commande manuelle corrélée demande le prochain frame de l'agent; l'UI suit l'événement par son identifiant. Restent les miniatures, le nettoyage des objets finaux orphelins et la réception sur caméra réelle. La branche en cours ajoute le statut durable des demandes et la purge des objets temporaires anciens. ### PIPE-10 — P1 — Événements perdus pendant une indisponibilité réseau — confirmé @@ -236,9 +239,9 @@ Correction : représenter l’éligibilité séparément du score, ou employer u Sources : `Web/Program.cs` (hubs mappés), `Web/Components/Pages/CameraDetail.razor`, inventaire des fichiers de streaming. -Pas de hub de signaling ou pipeline SIPSorcery trouvé ; le détail web montre le dernier snapshot événementiel rafraîchi, potentiellement ancien. Le client natif a été retiré ; le streaming devra être fourni par la surface web/PWA. Coturn dans Docker et des permissions Live ne constituent pas un parcours de streaming. +Pas de hub de signaling ou pipeline SIPSorcery trouvé ; le détail web montre le dernier snapshot événementiel avec son horodatage, potentiellement ancien, sans indicateur « live ». Le client natif a été retiré ; le streaming devra être fourni par la surface web/PWA. Coturn dans Docker et des permissions Live ne constituent pas un parcours de streaming. -À implémenter : signaling autorisé, gestion sessions, transport média, ICE/TURN, reconnexion et lecteur web/PWA ; commandes PTZ/audio selon caméras et capacités réellement prises en charge. Afficher l’horodatage et éviter l’indication trompeuse « live » tant que le flux n’est pas actif. +À implémenter : signaling autorisé, gestion sessions, transport média, ICE/TURN, reconnexion et lecteur web/PWA ; commandes PTZ/audio selon caméras et capacités réellement prises en charge. ### FEAT-02 — P2 — Enregistrement, replay et politiques de stockage non livrés — confirmé diff --git a/docs/audits/2026-10-20-plan-implementation.md b/docs/audits/2026-10-20-plan-implementation.md index 4109e38..c85affd 100644 --- a/docs/audits/2026-10-20-plan-implementation.md +++ b/docs/audits/2026-10-20-plan-implementation.md @@ -72,7 +72,7 @@ Acceptation : saturation contrôlée sans attente infinie, arrêt sans tâches o Priorité P1. Défauts PIPE-09, SEC-08, UI-01. Estimation : 5–8 jours. Dépend des lots 2 et 3. -État : confinement local, filtres de galerie, upload et lecture autorisés des JPEG de détection sont raccordés dans le code. Chaque nouveau snapshot porte sa destination de stockage; la boîte d’envoi de l’agent conserve le JPEG jusqu’à son acquittement. La capture manuelle, les miniatures, la réconciliation des orphelins et la validation sur caméra réelle restent à livrer. +État : confinement local, filtres de galerie, upload et lecture autorisés des JPEG de détection sont raccordés dans le code. Chaque nouveau snapshot porte sa destination de stockage; la boîte d’envoi de l’agent conserve le JPEG jusqu’à son acquittement. La demande manuelle corrélée est raccordée au prochain frame complet de l'agent. Les miniatures, l'état d'échec explicite, la réconciliation des orphelins et la validation sur caméra réelle restent à livrer. Travaux : diff --git a/install/agent-supervisor.py b/install/agent-supervisor.py new file mode 100644 index 0000000..e62340f --- /dev/null +++ b/install/agent-supervisor.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Run a native agent and roll back a release that fails its startup probe.""" +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request + +root = Path(os.environ["Agent__UpdateInstallRoot"]).resolve() +releases = root / "releases" +current = root / "current" +pending = root / "pending-update.json" +dotnet = os.environ.get("HEIMDALL_DOTNET", "/usr/bin/dotnet") +process = None + + +def terminate(_signum, _frame): + if process is not None and process.poll() is None: + process.terminate() + + +signal.signal(signal.SIGTERM, terminate) +signal.signal(signal.SIGINT, terminate) + + +def within_releases(path): + resolved = Path(path).resolve() + return resolved != releases and releases in resolved.parents + + +def restore(previous): + if not within_releases(previous): + raise RuntimeError("Rollback target is outside the release root") + replacement = root / (".rollback-" + str(os.getpid())) + replacement.symlink_to(previous, target_is_directory=True) + os.replace(replacement, current) + pending.unlink(missing_ok=True) + + +try: + marker = json.loads(pending.read_text()) if pending.exists() else None + if marker is not None and (not within_releases(marker["previous"]) or + not within_releases(current)): + raise RuntimeError("Invalid pending update marker") + process = subprocess.Popen([dotnet, str(current / "Heimdall.Agent.dll")], cwd=current) + if marker is not None: + wanted = str(marker["version"]).removeprefix("v") + deadline = time.monotonic() + 180 + healthy_since = None + healthy = False + while time.monotonic() < deadline and process.poll() is None: + try: + with urllib.request.urlopen("http://127.0.0.1:8081/api/version", timeout=3) as response: + info = json.load(response) + if str(info.get("version", "")).split("+")[0].removeprefix("v") == wanted: + healthy_since = healthy_since or time.monotonic() + if time.monotonic() - healthy_since >= 60: + healthy = True + break + else: + healthy_since = None + except (urllib.error.URLError, TimeoutError, ValueError): + healthy_since = None + time.sleep(2) + if not healthy: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + restore(marker["previous"]) + raise RuntimeError("Updated agent failed startup; previous release restored") + pending.unlink(missing_ok=True) + sys.exit(process.wait()) +except Exception as error: + print(f"Agent supervisor: {error}", file=sys.stderr) + sys.exit(75) diff --git a/install/install-agent.sh b/install/install-agent.sh index c95b571..92e477b 100755 --- a/install/install-agent.sh +++ b/install/install-agent.sh @@ -1,10 +1,13 @@ #!/usr/bin/env bash # install-agent.sh — Heimdall Agent installer for Linux set -euo pipefail -CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" ALLOW_INSECURE_HTTP=false -BINARY_NAME="heimdall-agent" INSTALL_DIR="/usr/local/bin" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall" -while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done -[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token required" >&2; exit 1; } +CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false +INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall" +while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN --update-public-key LOCAL_PEM [--agent-name NAME] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done +[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" || -z "$UPDATE_PUBLIC_KEY" ]] && { echo "Error: --central-url, --site-token and --update-public-key required" >&2; exit 1; } +[[ -f "$UPDATE_PUBLIC_KEY" ]] || { echo 'Publisher public key file is missing' >&2; exit 1; } +command -v jq >/dev/null && command -v openssl >/dev/null && command -v python3 >/dev/null && command -v dotnet >/dev/null || { echo 'jq, openssl, python3 and the .NET 10 runtime are required' >&2; exit 1; } +DOTNET_BIN=$(command -v dotnet) CENTRAL_URL="${CENTRAL_URL%/}" if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then echo "Error: --central-url must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2 @@ -12,17 +15,55 @@ if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CEN fi ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac echo "Installing Heimdall Agent for $PLATFORM..." -RELEASE_JSON=$(curl -sf "$CENTRAL_URL/api/updates/latest") || { echo "Failed to fetch release" >&2; exit 1; } -if command -v jq &>/dev/null; then VERSION=$(echo "$RELEASE_JSON" | jq -r '.version'); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].url // empty"); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].sha256 // empty"); else VERSION=$(echo "$RELEASE_JSON" | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"url":"[^"]*"' | head -1 | cut -d'"' -f4); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"sha256":"[^"]*"' | head -1 | cut -d'"' -f4); fi -[[ -z "$DOWNLOAD_URL" ]] && { echo "No binary for $PLATFORM" >&2; exit 1; } -[[ ! "$EXPECTED_SHA256" =~ ^[[:xdigit:]]{64}$ ]] && { echo "Release manifest has no valid SHA-256 digest for $PLATFORM; refusing an unverified install" >&2; exit 1; } -echo "Latest version: $VERSION" TMP_DIR=$(mktemp -d); trap 'rm -rf "$TMP_DIR"' EXIT -curl -sfL "$DOWNLOAD_URL" -o "$TMP_DIR/$BINARY_NAME" || { echo "Download failed" >&2; exit 1; } -ACTUAL=$(sha256sum "$TMP_DIR/$BINARY_NAME" | cut -d' ' -f1); [[ "${ACTUAL,,}" != "${EXPECTED_SHA256,,}" ]] && { echo "SHA256 mismatch" >&2; exit 1; }; echo "SHA256 verified" -chmod +x "$TMP_DIR/$BINARY_NAME"; [[ $EUID -eq 0 ]] && cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME" || sudo cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME" +curl -fsS "$CENTRAL_URL/api/updates/latest" -o "$TMP_DIR/release.json" || { echo "Failed to fetch release" >&2; exit 1; } +jq -r '.signedManifest // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.json" || { echo 'Invalid signed manifest encoding' >&2; exit 1; } +jq -r '.manifestSignature // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.sig" || { echo 'Invalid release signature encoding' >&2; exit 1; } +openssl dgst -sha256 -verify "$UPDATE_PUBLIC_KEY" -signature "$TMP_DIR/manifest.sig" "$TMP_DIR/manifest.json" >/dev/null || { echo 'Release signature verification failed' >&2; exit 1; } +VERSION=$(jq -r '.version' "$TMP_DIR/manifest.json") +[[ "$VERSION" == "$(jq -r '.version' "$TMP_DIR/release.json")" && "$VERSION" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+([._-][0-9A-Za-z.-]+)?$ ]] || { echo 'Invalid signed release version' >&2; exit 1; } +ASSET_PLATFORM=$(jq -r --arg platform "$PLATFORM" 'if .assets[$platform] then $platform elif .assets.portable then "portable" else empty end' "$TMP_DIR/manifest.json") +[[ -n "$ASSET_PLATFORM" ]] || { echo "No signed archive for $PLATFORM" >&2; exit 1; } +EXPECTED_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform]' "$TMP_DIR/manifest.json") +DOWNLOAD_URL=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].url // empty' "$TMP_DIR/release.json") +RELEASE_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].sha256 // empty' "$TMP_DIR/release.json") +[[ "$EXPECTED_SHA256" =~ ^[[:xdigit:]]{64}$ && "${EXPECTED_SHA256,,}" == "${RELEASE_SHA256,,}" && "$DOWNLOAD_URL" == https://* ]] || { echo 'Release archive differs from signed manifest' >&2; exit 1; } +curl -fsSL --proto '=https' --proto-redir '=https' "$DOWNLOAD_URL" -o "$TMP_DIR/agent.tar.gz" || { echo "Download failed" >&2; exit 1; } +ACTUAL=$(sha256sum "$TMP_DIR/agent.tar.gz" | cut -d' ' -f1); [[ "${ACTUAL,,}" == "${EXPECTED_SHA256,,}" ]] || { echo "SHA256 mismatch" >&2; exit 1; } +echo "Signed archive verified: $VERSION" +mkdir -p "$TMP_DIR/agent" +python3 - "$TMP_DIR/agent.tar.gz" "$TMP_DIR/agent" <<'PY' +import pathlib, shutil, sys, tarfile +root=pathlib.Path(sys.argv[2]).resolve() +with tarfile.open(sys.argv[1], 'r:gz') as archive: + members=archive.getmembers() + if len(members)>20000 or sum(m.size for m in members)>2_000_000_000: + raise SystemExit('Archive exceeds extraction limits') + for member in members: + if not (member.isfile() or member.isdir()): + raise SystemExit('Archive contains a link or unsupported entry') + target=(root/member.name).resolve() + if target!=root and root not in target.parents: + raise SystemExit('Archive path escapes extraction root') + if member.isdir(): + target.mkdir(parents=True,exist_ok=True) + else: + target.parent.mkdir(parents=True,exist_ok=True) + with archive.extractfile(member) as source, open(target,'xb') as output: + shutil.copyfileobj(source,output) +PY +[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; } id "$SERVICE_USER" &>/dev/null || sudo useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" 2>/dev/null || true sudo mkdir -p "$STATE_DIR" && sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR" && sudo chmod 700 "$STATE_DIR" +sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$INSTALL_ROOT" "$INSTALL_ROOT/releases" +[[ ! -e "$INSTALL_ROOT/releases/$VERSION" ]] || { echo 'Release already installed' >&2; exit 1; } +sudo mv "$TMP_DIR/agent" "$INSTALL_ROOT/releases/$VERSION" +sudo chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_ROOT/releases/$VERSION" +sudo ln -sfn "$INSTALL_ROOT/releases/$VERSION" "$INSTALL_ROOT/current" +sudo install -d -o root -g root -m 755 /etc/heimdall +sudo install -o root -g root -m 644 "$UPDATE_PUBLIC_KEY" /etc/heimdall/update-public-key.pem +sudo install -d -o root -g root -m 755 /usr/local/libexec +sudo install -o root -g root -m 755 "$(dirname "$0")/agent-supervisor.py" /usr/local/libexec/heimdall-agent-supervisor.py sudo install -d -o root -g root -m 700 /etc/heimdall/credentials printf '%s' "$SITE_TOKEN" | sudo tee /etc/heimdall/credentials/site-token >/dev/null sudo chmod 600 /etc/heimdall/credentials/site-token @@ -39,12 +80,18 @@ After=network-online.target [Service] Type=simple User=$SERVICE_USER -ExecStart=$INSTALL_DIR/$BINARY_NAME -Restart=on-failure +ExecStart=/usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py +WorkingDirectory=$INSTALL_ROOT/current +Restart=always +RestartSec=5 +Environment=ASPNETCORE_URLS=http://127.0.0.1:8081 +Environment=HEIMDALL_DOTNET=$DOTNET_BIN Environment=ASPNETCORE_ENVIRONMENT=Production Environment=Agent__CentralUrl=$CENTRAL_URL Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP Environment=Agent__StateDirectory=$STATE_DIR +Environment=Agent__UpdateInstallRoot=$INSTALL_ROOT +Environment=Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem LoadCredential=site-token:/etc/heimdall/credentials/site-token $AGENT_NAME_CREDENTIAL [Install] diff --git a/readme.md b/readme.md index 00cd1a8..89440a0 100644 --- a/readme.md +++ b/readme.md @@ -220,6 +220,8 @@ du dépôt `sources.tordais.cc/arnaud.dartois/Heimdall` et peut être changée s recompiler le serveur. L'agent lit le nom et le digest de l'image dans le manifeste authentifié de Central ; le dépôt d'image publié est défini dans `docker/agent-image.json` lors de la release. +La [procédure de signature des releases agent](docs/agent-release-signing.md) +décrit la clé publique locale requise pour les mises à jour natives et Docker. | Méthode | Usage | Endpoints | |---------|-------|-----------| @@ -272,6 +274,7 @@ Compte par défaut (dev) : | GET | `/api/events/{id}/snapshot/content` | JWT/cookie | Lire le JPEG stocké après contrôle d’accès à la caméra | | POST | `/api/events/{id}/snapshot` | API Key | Ancienne route retirée (`410 Gone`) | | GET | `/api/events/camera/{cameraId}` | JWT | Événements récents d'une caméra (`count` optionnel) | +| POST | `/api/cameras/{id}/snapshot` | JWT/cookie | Demander une nouvelle capture à l'agent assigné ; retourne un `requestId` corrélé à l'événement produit | | GET | `/api/events` | JWT | Rechercher des événements paginés et filtrés | | POST | `/api/agents/{id}/discovery` | API Key | Soumettre les résultats de découverte de caméras d'un agent | | POST | `/api/cameras/{id}/toggle-status` | JWT | Activer ou désactiver une caméra | diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index 5141780..23488ab 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -3,11 +3,21 @@ set -euo pipefail : "${REGISTRY_USER:?Dedicated registry user is required}" : "${REGISTRY_TOKEN:?Dedicated registry token is required}" : "${RELEASE_TOKEN:?Dedicated Gitea release token is required}" +: "${RELEASE_SIGNING_KEY_B64:?Publisher ECDSA P-256 private key is required}" : "${BUILD_SERVER_URL:?Gitea URL is required}" : "${BUILD_REPOSITORY:?Repository is required}" [[ "$BUILD_SERVER_URL" == https://sources.tordais.cc ]] || { echo 'Unexpected publication host' >&2; exit 1; } [[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; } sha=$(git rev-parse HEAD) +umask 077 +signing_key=$(mktemp) +trap 'rm -f "$signing_key"' EXIT +printf '%s' "$RELEASE_SIGNING_KEY_B64" | base64 -d > "$signing_key" +openssl pkey -in "$signing_key" -noout >/dev/null +openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prime256v1' || { + echo 'Release signing key must use ECDSA P-256' >&2 + exit 1 +} tag=${BUILD_REF#refs/tags/} [[ "$BUILD_REF" == refs/tags/v* ]] || exit 1 python3 - "$sha" "$tag" <<'PY' @@ -22,7 +32,7 @@ bash scripts/ci/images.sh # No mutation is attempted until all credentials, provenance and local builds pass. export DOCKER_CONFIG DOCKER_CONFIG=$(mktemp -d) -trap 'rm -rf "$DOCKER_CONFIG"' EXIT +trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin agent_image=$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])') [[ "$agent_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${agent_image##*/}" != *:* ]] || { echo 'Invalid agent image repository in docker/agent-image.json' >&2; exit 1; } @@ -73,4 +83,30 @@ with open('artifacts/packages/agent-image.json','w') as f: f.write('\n') PY (cd artifacts/packages && sha256sum agent-image.json >> SHA256SUMS) +python3 - <<'PY' +import hashlib,json,re +from pathlib import Path +root=Path('artifacts/packages') +image=json.loads((root/'agent-image.json').read_text()) +package_version=Path('artifacts/version').read_text().strip() +version='v'+package_version +assets={} +for path in root.glob('heimdall-agent-*.tar.gz'): + suffix=f'-{package_version}.tar.gz' + if not path.name.endswith(suffix): + continue + platform=path.name[len('heimdall-agent-'):-len(suffix)] + if not re.fullmatch(r'[a-z0-9-]+',platform): + raise SystemExit('Invalid agent archive platform') + assets[platform]=hashlib.sha256(path.read_bytes()).hexdigest() +if not assets: + raise SystemExit('No agent archive to sign') +payload={'version':version,'assets':assets,'containerImage':image['image'], + 'containerImageDigest':image['digest']} +(root/'agent-update-manifest.json').write_text( + json.dumps(payload,sort_keys=True,separators=(',',':'))+'\n') +PY +openssl dgst -sha256 -sign "$signing_key" \ + -out artifacts/packages/agent-update-manifest.sig artifacts/packages/agent-update-manifest.json +(cd artifacts/packages && sha256sum agent-update-manifest.json agent-update-manifest.sig >> SHA256SUMS) python3 scripts/ci/release-gitea.py diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 23b941c..901bef3 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -104,6 +104,12 @@ public sealed class AgentOptions public string DockerSocketPath { get; init; } = "/var/run/docker.sock"; public bool AutoUpdateEnabled { get; set; } + /// Locally provisioned publisher public key; Central cannot change this setting. + public string? UpdatePublicKeyPath { get; init; } + + /// Locally installed agent release root containing current and releases. + public string? UpdateInstallRoot { get; init; } + private static string? ReadSystemdCredential(string name) { var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY"); diff --git a/src/Heimdall.Agent/Services/AgentUpdateService.cs b/src/Heimdall.Agent/Services/AgentUpdateService.cs index 67d9c19..44e86cf 100644 --- a/src/Heimdall.Agent/Services/AgentUpdateService.cs +++ b/src/Heimdall.Agent/Services/AgentUpdateService.cs @@ -75,6 +75,10 @@ public sealed class AgentUpdateService : BackgroundService _logger.LogInformation("Checking for updates..."); var release = await FetchLatestReleaseAsync(ct); if (release is null) return; + var signed = ReleaseSignatureVerifier.Verify(release.SignedManifest, release.ManifestSignature, + _options.Value.UpdatePublicKeyPath); + if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal)) + throw new InvalidOperationException("Release version differs from the signed manifest"); var currentVersion = _options.Value.Version; var remoteVersion = release.Version; _logger.LogInformation("Current: v{Current}, Remote: v{Remote}", currentVersion, remoteVersion); @@ -82,21 +86,28 @@ public sealed class AgentUpdateService : BackgroundService { _logger.LogInformation("Up to date (v{Version})", currentVersion); return; } _logger.LogInformation("New version available: v{Remote}", remoteVersion); var platformKey = GetPlatformKey(); - if (platformKey is null || !release.Assets.TryGetValue(platformKey, out var asset)) + if (platformKey is null || + !release.Assets.TryGetValue(platformKey, out var asset) && + !release.Assets.TryGetValue("portable", out asset)) { _logger.LogWarning("No binary for platform"); return; } - var currentBinaryPath = Environment.ProcessPath; - if (string.IsNullOrEmpty(currentBinaryPath)) return; - var tempPath = currentBinaryPath + ".update.tmp"; + var signedPlatform = release.Assets.TryGetValue(platformKey, out _) ? platformKey : "portable"; + if (!signed.Assets.TryGetValue(signedPlatform, out var signedSha256) || + !string.Equals(signedSha256, asset.Sha256, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("Agent archive digest differs from the signed manifest"); + var installRoot = _options.Value.UpdateInstallRoot; + if (!OperatingSystem.IsLinux() || string.IsNullOrWhiteSpace(installRoot)) + throw new InvalidOperationException("Native update requires a managed Linux installation root"); + var tempPath = Path.Combine(Path.GetTempPath(), "heimdall-update-" + Guid.NewGuid().ToString("N") + ".tar.gz"); try { - await DownloadAndVerifyAsync(asset.Url, asset.Sha256, tempPath, ct); - File.Move(currentBinaryPath, currentBinaryPath + ".bak", overwrite: true); - File.Move(tempPath, currentBinaryPath, overwrite: true); + await DownloadAndVerifyAsync(asset.Url, signedSha256, tempPath, ct); + await NativeAgentPackageInstaller.ActivateAsync(tempPath, installRoot, signed.Version, ct); _logger.LogInformation("Updated from v{Old} to v{New}. Restarting...", currentVersion, remoteVersion); Environment.Exit(0); } catch (Exception ex) - { _logger.LogError(ex, "Failed to apply update"); try { if (File.Exists(tempPath)) File.Delete(tempPath); } catch { } } + { _logger.LogError(ex, "Failed to apply update"); } + finally { try { File.Delete(tempPath); } catch { } } } private async Task FetchLatestReleaseAsync(CancellationToken ct) @@ -146,7 +157,7 @@ public sealed class AgentUpdateService : BackgroundService private static int[] ParseVersion(string version) { - var clean = version.Split('-', '+')[0]; + var clean = version.Split('-', '+')[0].TrimStart('v', 'V'); var parts = clean.Split('.', StringSplitOptions.RemoveEmptyEntries); var result = new int[3]; for (var i = 0; i < Math.Min(parts.Length, 3); i++) @@ -178,6 +189,10 @@ public sealed class AgentUpdateService : BackgroundService public string Version { get; set; } = string.Empty; [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; + [JsonPropertyName("signedManifest")] + public string? SignedManifest { get; set; } + [JsonPropertyName("manifestSignature")] + public string? ManifestSignature { get; set; } } private sealed class AssetDto diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index e5a4ec8..066c3ed 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.Text.Json; using Heimdall.Application.DTOs; @@ -7,15 +6,16 @@ namespace Heimdall.Agent.Services; /// /// Holds the camera assignments the agent must capture. The Central is the /// source of truth: cameras are shipped as flat camera.<id>.name|rtsp|sub_rtsp|enabled -/// keys through the settings pipeline (full reload + live SettingChanged). +/// keys through the settings pipeline as one complete, versioned snapshot. /// A local list from AgentOptions.Cameras serves as a fallback until /// the first Central config is received. /// public sealed class CameraConfigStore { - private ConcurrentDictionary _central = new(); + private sealed record CameraSnapshot(IReadOnlyDictionary Cameras, string Version); + private CameraSnapshot? _central; + private readonly object _updateGate = new(); private IReadOnlyList _localFallback = []; - private volatile bool _centralReceived; /// Raised whenever the effective camera list may have changed. public event EventHandler? Changed; @@ -28,30 +28,24 @@ public sealed class CameraConfigStore } /// - /// Applies a single camera.<id>.<field> setting key received from - /// the Central. Any such key marks the Central list as authoritative. + /// Legacy single-key setter for local callers. Remote updates must use ReplaceCentral. /// public void ApplyCameraSetting(string key, string value) { // camera.. var parts = key.Split('.', 3); + if (!key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)) + return; if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId)) return; - - _centralReceived = true; - - _central.AddOrUpdate( - cameraId, - _ => BuildConfig(cameraId, parts[2], value), - (_, existing) => existing with - { - DetectionProfile = parts[2] == "profile" ? ParseProfile(value) : existing.DetectionProfile, - Name = parts[2] == "name" ? value : existing.Name, - RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl, - SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl, - Enabled = parts[2] == "enabled" ? ParseBool(value) : existing.Enabled, - }); - + lock (_updateGate) + { + var previous = _central?.Cameras ?? new Dictionary(); + var next = new Dictionary(previous); + next[cameraId] = ApplyField(next.GetValueOrDefault(cameraId) ?? + new AgentCameraConfig(cameraId, string.Empty, string.Empty, null, true), parts[2], value); + Volatile.Write(ref _central, new CameraSnapshot(next, string.Empty)); + } RaiseChanged(); } @@ -61,34 +55,47 @@ public sealed class CameraConfigStore /// public void MarkCentralReceived() { - if (_centralReceived) + if (Interlocked.CompareExchange(ref _central, + new CameraSnapshot(new Dictionary(), string.Empty), null) is not null) return; - _centralReceived = true; RaiseChanged(); } /// Atomically replace the authoritative snapshot, including removals. - public void ReplaceCentral(IReadOnlyDictionary settings) + public void ReplaceCentral(IReadOnlyDictionary settings, string? expectedVersion = null) { - var replacement = new CameraConfigStore(); + var version = CameraConfigVersion.Compute(settings); + if (expectedVersion is not null && !string.Equals(expectedVersion, version, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Camera configuration version mismatch", nameof(expectedVersion)); + var replacement = new Dictionary(); foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) - replacement.ApplyCameraSetting(setting.Key, setting.Value); - Interlocked.Exchange(ref _central, replacement._central); - _centralReceived = true; + { + var parts = setting.Key.Split('.', 3); + if (parts.Length != 3 || !Guid.TryParse(parts[1], out var id)) + throw new ArgumentException("Invalid camera setting key", nameof(settings)); + replacement[id] = ApplyField(replacement.GetValueOrDefault(id) ?? + new AgentCameraConfig(id, string.Empty, string.Empty, null, true), parts[2], setting.Value); + } + lock (_updateGate) + Volatile.Write(ref _central, new CameraSnapshot(replacement, version)); RaiseChanged(); } /// Effective camera assignments: Central list, or local fallback before that. public IReadOnlyList Cameras => - _centralReceived ? _central.Values.ToArray() : _localFallback; + Volatile.Read(ref _central)?.Cameras.Values.ToArray() ?? _localFallback; - private static AgentCameraConfig BuildConfig(Guid cameraId, string field, string value) => new( - cameraId, - field == "name" ? value : string.Empty, - field == "rtsp" ? value : string.Empty, - field == "sub_rtsp" ? value : null, - field == "enabled" ? ParseBool(value) : true, - field == "profile" ? ParseProfile(value) : null); + public string? CurrentVersion => Volatile.Read(ref _central)?.Version; + + private static AgentCameraConfig ApplyField(AgentCameraConfig existing, string field, string value) => field switch + { + "name" => existing with { Name = value }, + "rtsp" => existing with { RtspUrl = value }, + "sub_rtsp" => existing with { SubRtspUrl = value }, + "enabled" => existing with { Enabled = ParseBool(value) }, + "profile" => existing with { DetectionProfile = ParseProfile(value) }, + _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field)) + }; private static DetectionProfileDto ParseProfile(string value) { @@ -97,8 +104,13 @@ public sealed class CameraConfigStore return profile; } - private static bool ParseBool(string value) => - bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True"; + private static bool ParseBool(string value) => value switch + { + "1" => true, + "0" => false, + _ when bool.TryParse(value, out var parsed) => parsed, + _ => throw new ArgumentException("Invalid camera enabled value", nameof(value)) + }; private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty); } diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index 8b71f7c..0080958 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -27,7 +27,11 @@ public sealed class CameraStreamService : IDisposable private readonly SystemMetricsProvider _metrics; private readonly AdaptiveSnapshotInterval _snapshotInterval; private readonly ConcurrentDictionary _sessions = new(); + private readonly ConcurrentDictionary _controls = new(); + private readonly object _lifecycleGate = new(); + private readonly ConcurrentDictionary _manualRequests = new(); private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg + private int _disposed; private readonly ConcurrentDictionary _profiles = new(); public void SetDetectionProfile(Guid cameraId, Heimdall.Application.DTOs.DetectionProfileDto profile) => _profiles[cameraId] = profile; @@ -86,13 +90,24 @@ public sealed class CameraStreamService : IDisposable return false; } - if (_sessions.ContainsKey(cameraId)) + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + + var control = _controls.GetOrAdd(cameraId, static _ => new StreamControl()); + int generation; + lock (control.Gate) { - _logger.LogWarning("Stream already active for camera {CameraId}", cameraId); - return false; + if (_sessions.ContainsKey(cameraId)) + { + _logger.LogWarning("Stream already active for camera {CameraId}", cameraId); + return false; + } + generation = control.Generation; } await _throttle.WaitAsync(ct); + Process? process = null; + StreamSession? startedSession = null; + var handedOff = false; try { var psi = new ProcessStartInfo @@ -119,52 +134,80 @@ public sealed class CameraStreamService : IDisposable psi.ArgumentList.Add("1"); psi.ArgumentList.Add("-"); - var process = new Process { StartInfo = psi }; - process.Start(); + lock (control.Gate) + { + lock (_lifecycleGate) + { + if (control.Generation != generation || Volatile.Read(ref _disposed) != 0 || + _sessions.ContainsKey(cameraId)) + { + _throttle.Release(); + return false; + } - var session = new StreamSession(cameraId, rtspUrl, process); - _sessions[cameraId] = session; + process = new Process { StartInfo = psi }; + process.Start(); + var session = new StreamSession(cameraId, rtspUrl, process); + startedSession = session; + _sessions[cameraId] = session; - // FFmpeg can block once its stderr pipe fills. Drain it independently - // from stdout; do not log its contents because diagnostics may include - // the RTSP URL (and credentials). - _ = DrainStandardErrorAsync(cameraId, process); + // Never expose a session before its cleanup task is assigned. + // Do not pass ct to Task.Run: a pre-cancelled task would skip cleanup. + session.ReadTask = Task.Run(() => ReadFramesLoop(cameraId, session, ct), CancellationToken.None); + handedOff = true; + _ = DrainStandardErrorAsync(cameraId, process); + } + } _logger.LogInformation("Stream started for camera {CameraId}", cameraId); - - // Background read loop - _ = Task.Run(() => ReadFramesLoop(cameraId, session, ct), ct); - return true; } catch (Exception ex) { _logger.LogError("Failed to start stream for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); - _throttle.Release(); + if (!handedOff) + { + if (startedSession is not null) + ((ICollection>)_sessions) + .Remove(new KeyValuePair(cameraId, startedSession)); + if (process is not null) + { + try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } + process.Dispose(); + } + _throttle.Release(); + } return false; } } /// Stop streaming from a camera. - public Task StopStreamAsync(Guid cameraId) + public async Task StopStreamAsync(Guid cameraId) { - if (_sessions.TryRemove(cameraId, out var session)) + if (!_controls.TryGetValue(cameraId, out var control)) return; + StreamSession? session; + lock (control.Gate) { - session.Cancel(); - // Mark semaphore as released BEFORE releasing, so CleanupSession's - // finally block does NOT double-release (see SemaphoreReleased flag). - session.SemaphoreReleased = true; - _throttle.Release(); - _logger.LogInformation("Stream stopped for camera {CameraId}", cameraId); + control.Generation++; + _sessions.TryGetValue(cameraId, out session); + session?.Cancel(); } - return Task.CompletedTask; + if (session is null) return; + CancelManualRequest(cameraId, session); + try { if (!session.Process.HasExited) session.Process.Kill(entireProcessTree: true); } + catch (ObjectDisposedException) { } + catch (InvalidOperationException) { } + catch (System.ComponentModel.Win32Exception) { } + if (session.ReadTask is not null) + await session.ReadTask.ConfigureAwait(false); + _logger.LogInformation("Stream stopped for camera {CameraId}", cameraId); } /// Stops every active stream (agent shutdown). public async Task StopAllAsync() { foreach (var cameraId in _sessions.Keys.ToArray()) - await StopStreamAsync(cameraId); + await StopStreamAsync(cameraId).ConfigureAwait(false); } /// Number of currently active streams. @@ -180,16 +223,48 @@ public sealed class CameraStreamService : IDisposable /// Whether a stream is currently active for the given camera. public bool IsStreamActive(Guid cameraId) => _sessions.ContainsKey(cameraId); + /// Waits for the next complete frame from an active stream, bypassing adaptive sampling. + public async Task CaptureNextFrameAsync(Guid cameraId, CancellationToken ct = default) + { + if (!_sessions.TryGetValue(cameraId, out var session) || session.IsCancelled) return null; + var pending = new ManualCaptureRequest(session, + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!_manualRequests.TryAdd(cameraId, pending)) + { + if (DateTime.UtcNow >= deadline || !_sessions.TryGetValue(cameraId, out var active) || + !ReferenceEquals(active, session)) return null; + await Task.Delay(50, ct).ConfigureAwait(false); + } + try + { + if (!_sessions.TryGetValue(cameraId, out var current) || !ReferenceEquals(current, session)) + return null; + var remaining = deadline - DateTime.UtcNow; + return remaining > TimeSpan.Zero + ? await pending.Completion.Task.WaitAsync(remaining, ct).ConfigureAwait(false) + : null; + } + catch (TimeoutException) { return null; } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; } + finally + { + ((ICollection>)_manualRequests) + .Remove(new KeyValuePair(cameraId, pending)); + } + } + private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct) { var buffer = ArrayPool.Shared.Rent(256 * 1024); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, session.StopToken); try { var stream = session.Process.StandardOutput.BaseStream; while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited) { - var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct); + var bytesRead = await stream.ReadAsync(buffer.AsMemory(), linked.Token); if (bytesRead == 0) break; Interlocked.Increment(ref session.FrameCount); @@ -199,6 +274,10 @@ public sealed class CameraStreamService : IDisposable MaybeEmitSnapshot(cameraId, session, frame); } } + catch (OperationCanceledException) when (ct.IsCancellationRequested || session.IsCancelled) + { + // Cancellation is the normal path when the agent stops a stream. + } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning("Frame read loop ended for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); @@ -225,13 +304,19 @@ public sealed class CameraStreamService : IDisposable private void MaybeEmitSnapshot(Guid cameraId, StreamSession session, byte[] frame) { + if (session.IsCancelled) return; var now = DateTime.UtcNow; + if (_sessions.TryGetValue(cameraId, out var current) && ReferenceEquals(current, session) && + _manualRequests.TryGetValue(cameraId, out var pending) && ReferenceEquals(pending.Session, session) && + ((ICollection>)_manualRequests) + .Remove(new KeyValuePair(cameraId, pending))) + pending.Completion.TrySetResult(new Snapshot(cameraId, now, frame)); var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent(), _profiles.GetValueOrDefault(cameraId)); // Update snapshot interval metric (spec 13.1) HeimdallMetrics.SetSnapshotInterval(interval); - if (now - session.LastSnapshotAt < interval) + if (session.IsCancelled || now - session.LastSnapshotAt < interval) return; // sample less often than FFmpeg pushes frames session.LastSnapshotAt = now; @@ -277,38 +362,64 @@ public sealed class CameraStreamService : IDisposable } finally { - if (!session.SemaphoreReleased) - { - session.SemaphoreReleased = true; - _throttle.Release(); - } - _sessions.TryRemove(cameraId, out _); + if (((ICollection>)_sessions) + .Remove(new KeyValuePair(cameraId, session))) + CancelManualRequest(cameraId, session); + session.Dispose(); + _throttle.Release(); } } + private void CancelManualRequest(Guid cameraId, StreamSession? session = null) + { + if (!_manualRequests.TryGetValue(cameraId, out var pending) || + (session is not null && !ReferenceEquals(pending.Session, session))) return; + if (((ICollection>)_manualRequests) + .Remove(new KeyValuePair(cameraId, pending))) + pending.Completion.TrySetCanceled(); + } + public void Dispose() { - foreach (var session in _sessions.Values) + lock (_lifecycleGate) { - session.Cancel(); - session.Process?.Dispose(); + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; } - _sessions.Clear(); + StopAllAsync().GetAwaiter().GetResult(); + foreach (var cameraId in _manualRequests.Keys) + CancelManualRequest(cameraId); SnapshotChannel.Writer.TryComplete(); - _throttle.Dispose(); } - private sealed class StreamSession(Guid cameraId, string rtspUrl, Process process) + private sealed class StreamSession(Guid cameraId, string rtspUrl, Process process) : IDisposable { public Guid CameraId { get; } = cameraId; public string RtspUrl { get; } = rtspUrl; public Process Process { get; } = process; public long FrameCount; - public bool SemaphoreReleased; + public Task? ReadTask; public JpegFrameSplitter Splitter { get; } = new(); public DateTime LastSnapshotAt { get; set; } = DateTime.MinValue; - private volatile bool _cancelled; - public bool IsCancelled => _cancelled; - public void Cancel() => _cancelled = true; + private readonly CancellationTokenSource _stop = new(); + private int _cancelled; + public CancellationToken StopToken => _stop.Token; + public bool IsCancelled => Volatile.Read(ref _cancelled) != 0; + public void Cancel() + { + if (Interlocked.Exchange(ref _cancelled, 1) == 0) + { + try { _stop.Cancel(); } + catch (ObjectDisposedException) { } + } + } + public void Dispose() => _stop.Dispose(); + } + + private sealed record ManualCaptureRequest(StreamSession Session, TaskCompletionSource Completion); + + private sealed class StreamControl + { + public object Gate { get; } = new(); + public int Generation; } } diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index a028e50..9f80ced 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -1,6 +1,7 @@ using System.Net.Http.Json; using Heimdall.Application.DTOs; using Heimdall.Application.Security; +using Heimdall.Domain.Enums; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Options; @@ -21,6 +22,8 @@ public sealed class ConfigReceiverService : BackgroundService private readonly AgentCredentialStore _credentialStore; private readonly RuntimeLogLevel _runtimeLogLevel; private readonly CameraConfigStore _cameraStore; + private readonly CameraStreamService _streams; + private readonly IDetectionReporter _detectionReporter; private readonly AgentUpdateService _updateService; private readonly DockerUpdateService _dockerUpdateService; private readonly ContainerInfoProvider _containerInfo; @@ -52,6 +55,8 @@ public sealed class ConfigReceiverService : BackgroundService AgentCredentialStore credentialStore, RuntimeLogLevel runtimeLogLevel, CameraConfigStore cameraStore, + CameraStreamService streams, + IDetectionReporter detectionReporter, AgentUpdateService updateService, DockerUpdateService dockerUpdateService, ContainerInfoProvider containerInfo) @@ -64,6 +69,8 @@ public sealed class ConfigReceiverService : BackgroundService _credentialStore = credentialStore; _runtimeLogLevel = runtimeLogLevel; _cameraStore = cameraStore; + _streams = streams; + _detectionReporter = detectionReporter; _updateService = updateService; _dockerUpdateService = dockerUpdateService; _containerInfo = containerInfo; @@ -90,6 +97,42 @@ public sealed class ConfigReceiverService : BackgroundService .Build(); _connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger()); + _connection.On("ManualSnapshotRequested", async (cameraId, requestId) => + { + if (requestId == Guid.Empty) return; + try + { + if (!_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled)) + { + await ReportSnapshotFailureAsync(cameraId, requestId, "camera_unavailable", stoppingToken); + return; + } + var snapshot = await _streams.CaptureNextFrameAsync(cameraId, stoppingToken).ConfigureAwait(false); + if (snapshot is null) + { + _logger.LogWarning("Manual snapshot request {RequestId} has no active frame for camera {CameraId}", requestId, cameraId); + await ReportSnapshotFailureAsync(cameraId, requestId, "no_frame", stoppingToken); + return; + } + if (!await _detectionReporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual", + occurredAt: snapshot.TimestampUtc, snapshotJpeg: snapshot.JpegData, + eventId: requestId, ct: stoppingToken).ConfigureAwait(false)) + { + _logger.LogWarning("Manual snapshot request {RequestId} could not be queued", requestId); + await ReportSnapshotFailureAsync(cameraId, requestId, "queue_failed", stoppingToken); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } + catch (Exception ex) + { + _logger.LogWarning(ex, "Manual snapshot request {RequestId} failed", requestId); + try { await ReportSnapshotFailureAsync(cameraId, requestId, "agent_error", stoppingToken); } + catch (Exception reportError) + { + _logger.LogWarning(reportError, "Could not report manual snapshot failure {RequestId}", requestId); + } + } + }); _connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer ? _dockerUpdateService.RequestUpdateAsync(stoppingToken) : _updateService.RequestUpdateAsync(stoppingToken)); @@ -99,7 +142,8 @@ public sealed class ConfigReceiverService : BackgroundService { // Keys may identify secret settings; never log their values. _logger.LogInformation("Config update received: {Key}", key); - if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken); + if (key == "config.invalidated" || key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)) + await FetchFullConfigAsync(stoppingToken); else ApplySetting(key, value); }); @@ -164,6 +208,15 @@ public sealed class ConfigReceiverService : BackgroundService } } + private async Task ReportSnapshotFailureAsync(Guid cameraId, Guid requestId, string code, CancellationToken ct) + { + using var http = _httpClientFactory.CreateClient("Central"); + http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + var url = $"{_options.CentralUrl.TrimEnd('/')}/api/cameras/{cameraId:D}/snapshot/{requestId:D}/failure"; + using var response = await http.PutAsJsonAsync(url, new { code }, ct).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + } + public override async Task StopAsync(CancellationToken cancellationToken) { if (_connection is not null) @@ -176,8 +229,8 @@ public sealed class ConfigReceiverService : BackgroundService private void ApplySetting(string key, string value) { - // Camera assignments are applied live: the capture pipeline resyncs - // on every store change (start new streams, stop removed ones). + // Remote camera keys are applied only through an authoritative versioned + // full snapshot. This branch remains for local callers. if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)) { _cameraStore.ApplyCameraSetting(key, value); @@ -281,7 +334,7 @@ public sealed class ConfigReceiverService : BackgroundService http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}"; - var response = await http.GetAsync(url, ct); + using var response = await http.GetAsync(url, ct); if (!response.IsSuccessStatusCode) { @@ -296,6 +349,20 @@ public sealed class ConfigReceiverService : BackgroundService return; } + var version = response.Headers.TryGetValues("X-Camera-Config-Version", out var values) + ? values.SingleOrDefault() + : null; + if (string.IsNullOrWhiteSpace(version)) + { + _logger.LogWarning("Full camera configuration has no version header"); + return; + } + + // Validate and publish all camera fields together before applying + // independent agent settings. An invalid camera snapshot leaves the + // previously active assignments intact. + _cameraStore.ReplaceCentral(config, version); + _logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count); // Apply every key through the same pipeline as live SettingChanged @@ -303,11 +370,15 @@ public sealed class ConfigReceiverService : BackgroundService // documentation, everything. foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) ApplySetting(kvp.Key, kvp.Value); - _cameraStore.ReplaceCentral(config); - // The Central camera list is authoritative once the full config // arrives — even if it is empty, drop the local fallback. _cameraStore.MarkCentralReceived(); + + using var ack = await http.PostAsJsonAsync( + $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack", + new { version }, ct).ConfigureAwait(false); + if (!ack.IsSuccessStatusCode) + _logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode); } catch (Exception ex) { diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index 64df328..e5083da 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -18,6 +18,7 @@ public interface IDetectionReporter Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, + Guid? eventId = null, CancellationToken ct = default); } @@ -85,15 +86,18 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo public async Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, + Guid? eventId = null, CancellationToken ct = default) { if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return false; + if (eventId == Guid.Empty) return false; + if (type == EventType.ManualSnapshot && snapshotJpeg is null) return false; var key = (cameraId, type); var now = DateTime.UtcNow; var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown; - if (_lastQueued.TryGetValue(key, out var last) && now - last < cooldown) + if (type != EventType.ManualSnapshot && _lastQueued.TryGetValue(key, out var last) && now - last < cooldown) { Interlocked.Increment(ref _suppressedByCooldown); HeimdallMetrics.RecordEventSuppressed("cooldown", type.ToString()); @@ -101,14 +105,14 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo } var request = new CreateCameraEventRequest( - cameraId, type, confidence, label, metadataJson, occurredAt ?? now, Guid.NewGuid()); + cameraId, type, confidence, label, metadataJson, occurredAt ?? now, eventId ?? Guid.NewGuid()); try { var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false); if (!queued) return false; - _lastQueued[key] = now; + if (type != EventType.ManualSnapshot) _lastQueued[key] = now; try { _wake.Release(); } catch (SemaphoreFullException) { } return true; @@ -301,6 +305,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo snapshotJpeg[0] != 0xff || snapshotJpeg[1] != 0xd8 || snapshotJpeg[^2] != 0xff || snapshotJpeg[^1] != 0xd9)) { + if (request.Type == EventType.ManualSnapshot) return false; _logger.LogWarning("Captured JPEG for camera {CameraId} is invalid or exceeds {MaxBytes} bytes; retaining the event without an image", request.CameraId, MaxSnapshotBytes); snapshotJpeg = null; diff --git a/src/Heimdall.Agent/Services/DockerUpdateService.cs b/src/Heimdall.Agent/Services/DockerUpdateService.cs index ebcd939..d345553 100644 --- a/src/Heimdall.Agent/Services/DockerUpdateService.cs +++ b/src/Heimdall.Agent/Services/DockerUpdateService.cs @@ -54,6 +54,12 @@ public sealed class DockerUpdateService : BackgroundService _logger.LogInformation("Checking for agent updates..."); var release = await FetchLatestReleaseAsync(ct).ConfigureAwait(false); if (release is null) { _logger.LogWarning("Could not fetch latest release from Central"); return; } + var signed = ReleaseSignatureVerifier.Verify(release.SignedManifest, release.ManifestSignature, + _options.UpdatePublicKeyPath); + if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal) || + !string.Equals(signed.ContainerImage, release.ContainerImage, StringComparison.Ordinal) || + !string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("Docker image differs from the signed release manifest"); var latest = release.Version; var current = _options.Version; if (!IsNewerVersion(current, latest)) { _logger.LogInformation("Up to date ({V})", current); return; } @@ -77,6 +83,11 @@ public sealed class DockerUpdateService : BackgroundService if (pe != 0) { _logger.LogError("docker pull failed: {O}", po); return; } var cfg = await InspectAsync(cid, ct).ConfigureAwait(false); if (cfg is null) { _logger.LogError("Cannot inspect container"); return; } + if (!IsSha256Digest(cfg.ImageId)) + { + _logger.LogError("Current container has no immutable local image ID; update aborted to preserve rollback"); + return; + } _logger.LogInformation("Stopping current container {Id}...", cid); var (stopExitCode, stopOutput) = await RunDocker(["stop", "--time=30", cid], ct); if (stopExitCode != 0) @@ -87,7 +98,7 @@ public sealed class DockerUpdateService : BackgroundService var runArgs = BuildArgs(cfg, full); _logger.LogInformation("Starting updated container with pinned image {Image}", full); var (re, ro) = await RunDocker(["run", "-d", .. runArgs], ct); - if (re != 0 || string.IsNullOrWhiteSpace(ro)) { _logger.LogError("docker run failed, rolling back"); await Rollback(cfg, image, ct); return; } + if (re != 0 || string.IsNullOrWhiteSpace(ro)) { _logger.LogError("docker run failed, rolling back"); await Rollback(cfg, ct); return; } var nid = ro.Trim(); _logger.LogInformation("New container started: {N}", nid); if (!await WaitForHealthAsync(nid, cfg.Environment, ct)) @@ -95,7 +106,7 @@ public sealed class DockerUpdateService : BackgroundService _logger.LogError("Health check failed, rolling back"); await RunDocker(["stop", "--time=10", nid], ct); await RunDocker(["rm", nid], ct); - await Rollback(cfg, image, ct); + await Rollback(cfg, ct); return; } await RunDocker(["rm", cid], ct); @@ -107,10 +118,10 @@ public sealed class DockerUpdateService : BackgroundService _logger.LogInformation("Update complete: {C} -> {A}", current, latest); } - private async Task Rollback(ContainerConfig cfg, string image, CancellationToken ct) + private async Task Rollback(ContainerConfig cfg, CancellationToken ct) { - var oldImg = cfg.ImageId ?? cfg.Image ?? (image + ":latest"); - var args = BuildArgs(cfg, oldImg); + // The caller has verified this local image ID before stopping the old container. + var args = BuildArgs(cfg, cfg.ImageId!); var (e, _) = await RunDocker(["run", "-d", .. args], ct); if (e != 0) _logger.LogCritical("Rollback FAILED - manual intervention required"); else _logger.LogInformation("Rollback successful"); @@ -247,6 +258,8 @@ public sealed class DockerUpdateService : BackgroundService [JsonPropertyName("version")] public string Version { get; init; } = string.Empty; [JsonPropertyName("containerImage")] public string? ContainerImage { get; init; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; } + [JsonPropertyName("signedManifest")] public string? SignedManifest { get; init; } + [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; init; } } private sealed class DockerInspectResult { diff --git a/src/Heimdall.Agent/Services/NativeAgentPackageInstaller.cs b/src/Heimdall.Agent/Services/NativeAgentPackageInstaller.cs new file mode 100644 index 0000000..3267ecc --- /dev/null +++ b/src/Heimdall.Agent/Services/NativeAgentPackageInstaller.cs @@ -0,0 +1,118 @@ +using System.Formats.Tar; +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; + +namespace Heimdall.Agent.Services; + +/// Stages a signed framework-dependent archive and switches the managed installation. +internal static class NativeAgentPackageInstaller +{ + internal static async Task ActivateAsync(string archive, string installRoot, string version, CancellationToken ct) + { + if (!Path.IsPathFullyQualified(installRoot) || + version.Length is < 1 or > 80 || + version.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '.' and not '-' and not '_')) + throw new InvalidOperationException("Invalid managed agent installation path or version"); + + var root = Path.GetFullPath(installRoot); + var releases = Path.Combine(root, "releases"); + var current = Path.Combine(root, "current"); + if (new DirectoryInfo(root).LinkTarget is not null || + new DirectoryInfo(releases).LinkTarget is not null || + new DirectoryInfo(current).LinkTarget is null) + throw new InvalidOperationException("Managed agent installation layout is invalid"); + var previous = Directory.ResolveLinkTarget(current, returnFinalTarget: true)?.FullName; + if (previous is null) + throw new InvalidOperationException("Active agent release cannot be resolved"); + var relative = Path.GetRelativePath(releases, previous); + if (relative is "." or ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || + Path.IsPathRooted(relative)) + throw new InvalidOperationException("Active agent release is outside the managed root"); + + var destination = Path.Combine(releases, version); + if (Directory.Exists(destination) || File.Exists(destination)) + throw new InvalidOperationException("Agent release version already exists"); + var staging = Path.Combine(releases, ".staging-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(staging); + try + { + await ExtractSafeAsync(archive, staging, ct).ConfigureAwait(false); + if (!File.Exists(Path.Combine(staging, "Heimdall.Agent.dll"))) + throw new InvalidOperationException("Agent archive has no executable assembly"); + Directory.Move(staging, destination); + var rollbackMarker = Path.Combine(root, "pending-update.json"); + if (File.Exists(rollbackMarker)) + throw new InvalidOperationException("Previous agent update has not passed startup verification"); + var markerTemp = Path.Combine(root, ".pending-" + Guid.NewGuid().ToString("N")); + await File.WriteAllTextAsync(markerTemp, + JsonSerializer.Serialize(new { previous, version }), ct).ConfigureAwait(false); + File.Move(markerTemp, rollbackMarker, overwrite: true); + var nextLink = Path.Combine(root, ".current-" + Guid.NewGuid().ToString("N")); + try + { + Directory.CreateSymbolicLink(nextLink, destination); + if (Rename(nextLink, current) != 0) + throw new IOException($"Could not activate agent release (errno {Marshal.GetLastPInvokeError()})"); + } + catch + { + try { File.Delete(nextLink); } catch { } + try { File.Delete(rollbackMarker); } catch { } + throw; + } + } + catch + { + try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { } + try { if (Directory.Exists(destination)) Directory.Delete(destination, recursive: true); } catch { } + throw; + } + } + + private static async Task ExtractSafeAsync(string archive, string destination, CancellationToken ct) + { + await using var file = File.OpenRead(archive); + await using var gzip = new GZipStream(file, CompressionMode.Decompress); + using var reader = new TarReader(gzip, leaveOpen: true); + long totalBytes = 0; + var count = 0; + TarEntry? entry; + while ((entry = reader.GetNextEntry()) is not null) + { + ct.ThrowIfCancellationRequested(); + if (++count > 20_000) throw new InvalidOperationException("Agent archive has too many entries"); + var name = entry.Name.StartsWith("./", StringComparison.Ordinal) ? entry.Name[2..] : entry.Name; + if (entry.EntryType == TarEntryType.Directory) name = name.TrimEnd('/'); + if (name is "" or "." && entry.EntryType == TarEntryType.Directory) continue; + if (string.IsNullOrWhiteSpace(name) || name.Contains('\\') || Path.IsPathRooted(name) || + name.Split('/').Any(part => part is "" or "." or "..")) + throw new InvalidOperationException("Agent archive has an unsafe path"); + var path = Path.GetFullPath(Path.Combine(destination, name)); + if (!path.StartsWith(destination + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + throw new InvalidOperationException("Agent archive escapes its staging directory"); + if (entry.EntryType == TarEntryType.Directory) + { + Directory.CreateDirectory(path); + continue; + } + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile) || + entry.DataStream is null || entry.Length < 0) + throw new InvalidOperationException("Agent archive contains an unsupported entry"); + totalBytes += entry.Length; + if (totalBytes > 2_000_000_000) + throw new InvalidOperationException("Agent archive exceeds the extraction limit"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, + FileShare.None, 64 * 1024, useAsync: true); + await entry.DataStream.CopyToAsync(output, ct).ConfigureAwait(false); + } + } + + private static int Rename(string source, string destination) => RenameRaw( + Encoding.UTF8.GetBytes(source + "\0"), Encoding.UTF8.GetBytes(destination + "\0")); + + [DllImport("libc", EntryPoint = "rename", SetLastError = true)] + private static extern int RenameRaw(byte[] source, byte[] destination); +} diff --git a/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs new file mode 100644 index 0000000..907295f --- /dev/null +++ b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs @@ -0,0 +1,61 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Heimdall.Agent.Services; + +/// Verifies a publisher-signed release independently of Central and the release host. +internal static class ReleaseSignatureVerifier +{ + private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; + + internal static SignedAgentRelease Verify(string? manifestBase64, string? signatureBase64, string? publicKeyPath) + { + if (string.IsNullOrWhiteSpace(publicKeyPath) || !Path.IsPathFullyQualified(publicKeyPath)) + throw new InvalidOperationException("A local release public key path is required for updates"); + if (string.IsNullOrWhiteSpace(manifestBase64) || string.IsNullOrWhiteSpace(signatureBase64)) + throw new InvalidOperationException("Release signature is missing"); + + byte[] manifest; + byte[] signature; + try + { + manifest = Convert.FromBase64String(manifestBase64); + signature = Convert.FromBase64String(signatureBase64); + } + catch (FormatException ex) + { + throw new InvalidOperationException("Release signature has invalid encoding", ex); + } + if (manifest.Length is < 1 or > 1_048_576 || signature.Length is < 1 or > 512) + throw new InvalidOperationException("Release signature payload has invalid size"); + + using var verifier = ECDsa.Create(); + verifier.ImportFromPem(File.ReadAllText(publicKeyPath)); + if (verifier.KeySize != 256 || !verifier.VerifyData(manifest, signature, + HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence)) + throw new InvalidOperationException("Release signature is invalid"); + + var release = JsonSerializer.Deserialize(manifest, Json); + if (release is null || string.IsNullOrWhiteSpace(release.Version) || release.Assets.Count == 0 || + release.Assets.Any(x => string.IsNullOrWhiteSpace(x.Key) || !IsSha256(x.Value)) || + string.IsNullOrWhiteSpace(release.ContainerImage) || + release.ContainerImage.Contains('@') || + !IsImageDigest(release.ContainerImageDigest)) + throw new InvalidOperationException("Signed release manifest is incomplete"); + return release; + } + + internal static bool IsSha256(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit); + + private static bool IsImageDigest(string? value) => value is { Length: 71 } && + value.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase) && IsSha256(value[7..]); +} + +internal sealed class SignedAgentRelease +{ + [JsonPropertyName("version")] public string Version { get; init; } = string.Empty; + [JsonPropertyName("assets")] public Dictionary Assets { get; init; } = []; + [JsonPropertyName("containerImage")] public string? ContainerImage { get; init; } + [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; } +} diff --git a/src/Heimdall.Application/Agents/AgentExtensions.cs b/src/Heimdall.Application/Agents/AgentExtensions.cs index 5cfadc6..ca28612 100644 --- a/src/Heimdall.Application/Agents/AgentExtensions.cs +++ b/src/Heimdall.Application/Agents/AgentExtensions.cs @@ -30,5 +30,6 @@ public static class AgentExtensions // Container info a.ContainerId, a.ContainerImage, // Network & Temperature - a.NetworkInterfacesJson, a.TemperatureJson); + a.NetworkInterfacesJson, a.TemperatureJson, + a.LastAppliedCameraConfigVersion, a.LastAppliedCameraConfigAt); } diff --git a/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs b/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs new file mode 100644 index 0000000..5d3850b --- /dev/null +++ b/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs @@ -0,0 +1,19 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig; + +public sealed record AcknowledgeCameraConfigCommand(Guid AgentId, string Version) : IRequest; + +public sealed class AcknowledgeCameraConfigHandler(IApplicationDbContext db) + : IRequestHandler +{ + public async Task Handle(AcknowledgeCameraConfigCommand request, CancellationToken ct) + { + var agent = await db.Agents.FindAsync([request.AgentId], ct).ConfigureAwait(false); + if (agent is null || agent.IsDeleted) return false; + agent.AcknowledgeCameraConfig(request.Version, DateTime.UtcNow); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + return true; + } +} diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index ba81e2e..0650128 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -18,6 +18,7 @@ public interface IApplicationDbContext DbSet CameraDetectionProfiles { get; } DbSet CameraDiscoveryResults { get; } DbSet CameraEvents { get; } + DbSet ManualSnapshotRequests { get; } DbSet DiscoveredStreams { get; } // Notification entities diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs index b882741..b413c94 100644 --- a/src/Heimdall.Application/Common/IStorageProvider.cs +++ b/src/Heimdall.Application/Common/IStorageProvider.cs @@ -26,6 +26,16 @@ public interface IStorageProvider /// Delete a batch of objects (S3: 1000/appel). Task DeleteBatchAsync(IReadOnlyCollection keys, CancellationToken ct = default); + /// Remove abandoned temporary uploads older than the cutoff. + Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default); + + /// List final objects by key, in pages. Cursor is the last key of the previous page. + Task ListObjectsPageAsync(string prefix, string? cursor, int pageSize, + CancellationToken ct = default); + /// Check reachability/health of the backend. Task HealthCheckAsync(CancellationToken ct = default); } + +public sealed record StorageObjectInfo(string Key, DateTime LastModifiedUtc); +public sealed record StorageObjectPage(IReadOnlyList Objects, string? NextCursor); diff --git a/src/Heimdall.Application/DTOs/AgentDto.cs b/src/Heimdall.Application/DTOs/AgentDto.cs index 29a8314..09febbb 100644 --- a/src/Heimdall.Application/DTOs/AgentDto.cs +++ b/src/Heimdall.Application/DTOs/AgentDto.cs @@ -116,7 +116,9 @@ public record AgentResponse( string? ContainerImage = null, // Network & Temperature (JSON) string? NetworkInterfacesJson = null, - string? TemperatureJson = null) : AgentTelemetryFields( + string? TemperatureJson = null, + string? LastAppliedCameraConfigVersion = null, + DateTime? LastAppliedCameraConfigAt = null) : AgentTelemetryFields( CpuUsagePercent, MemoryUsageBytes, DiskUsagePercent, UptimeSeconds, CpuVendor, CpuModel, CpuArchitecture, PhysicalCores, LogicalCores, ThreadsPerCore, CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit, diff --git a/src/Heimdall.Application/DTOs/CameraConfigVersion.cs b/src/Heimdall.Application/DTOs/CameraConfigVersion.cs new file mode 100644 index 0000000..a2cd420 --- /dev/null +++ b/src/Heimdall.Application/DTOs/CameraConfigVersion.cs @@ -0,0 +1,30 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; + +namespace Heimdall.Application.DTOs; + +/// A stable version of the complete camera portion of an agent configuration. +public static class CameraConfigVersion +{ + public static string Compute(IReadOnlyDictionary settings) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + foreach (var entry in settings.Where(x => x.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)) + .OrderBy(x => x.Key, StringComparer.Ordinal)) + { + Append(entry.Key); + Append(entry.Value); + } + return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + + void Append(string value) + { + var bytes = Encoding.UTF8.GetBytes(value); + Span length = stackalloc byte[sizeof(int)]; + BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length); + hash.AppendData(length); + hash.AppendData(bytes); + } + } +} diff --git a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs index 6eafacb..312a862 100644 --- a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs +++ b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs @@ -1,6 +1,9 @@ +using System.Text.Json.Serialization; + namespace Heimdall.Application.DTOs; /// Version 1 supports COCO object detection and a normalized pixel motion gate. +[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] public sealed record DetectionProfileDto { public int Version { get; init; } = 1; diff --git a/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs b/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs index 0fad0c1..0391a8a 100644 --- a/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs @@ -24,10 +24,12 @@ public class DeleteEventHandler : IRequestHandler().ToArray(), + location, ct).ConfigureAwait(false); } _context.CameraEvents.Remove(ev); diff --git a/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs index 6c9bb09..c3a9994 100644 --- a/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs +++ b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs @@ -25,6 +25,7 @@ public class EventCreatedNotificationHandler : INotificationHandler RequestAgentUpdate(Guid agentId, CancellationToken ct = default); + Task RequestManualSnapshot(Guid agentId, Guid cameraId, Guid requestId, CancellationToken ct = default); Task NotifyAllAgentsReload(CancellationToken ct = default); } diff --git a/src/Heimdall.Domain/Entities/Agent.cs b/src/Heimdall.Domain/Entities/Agent.cs index 6343495..88dd0b6 100644 --- a/src/Heimdall.Domain/Entities/Agent.cs +++ b/src/Heimdall.Domain/Entities/Agent.cs @@ -11,6 +11,8 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable public string Version { get; private set; } = string.Empty; public AgentStatus Status { get; private set; } = AgentStatus.Offline; public DateTime? LastHeartbeat { get; private set; } + public string? LastAppliedCameraConfigVersion { get; private set; } + public DateTime? LastAppliedCameraConfigAt { get; private set; } public string? PublicIp { get; private set; } /// HMACSHA256 hash of the agent's API key. @@ -116,6 +118,16 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable PublicIp = publicIp; } + public void AcknowledgeCameraConfig(string version, DateTime appliedAtUtc) + { + if (version.Length != 64 || !version.All(Uri.IsHexDigit)) + throw new ArgumentException("Invalid camera configuration version", nameof(version)); + if (appliedAtUtc.Kind != DateTimeKind.Utc) + throw new ArgumentException("Acknowledgement time must be UTC", nameof(appliedAtUtc)); + LastAppliedCameraConfigVersion = version.ToLowerInvariant(); + LastAppliedCameraConfigAt = appliedAtUtc; + } + public void UpdateLiveMetrics( double? cpuUsagePercent, long? memoryUsageBytes, diff --git a/src/Heimdall.Domain/Entities/CameraEvent.cs b/src/Heimdall.Domain/Entities/CameraEvent.cs index 8f0677f..5c6c024 100644 --- a/src/Heimdall.Domain/Entities/CameraEvent.cs +++ b/src/Heimdall.Domain/Entities/CameraEvent.cs @@ -17,6 +17,7 @@ public class CameraEvent : Entity, IAuditableEntity public string? SnapshotUrl { get; private set; } // S3 key or URL to snapshot image public string? SnapshotThumbUrl { get; private set; } // Thumbnail S3 key or URL public string? SnapshotObjectKey { get; private set; } + public string? SnapshotThumbObjectKey { get; private set; } public StorageProvider? SnapshotStorageProvider { get; private set; } public string? SnapshotStorageRoot { get; private set; } public string? SnapshotStorageEndpoint { get; private set; } @@ -96,19 +97,20 @@ public class CameraEvent : Entity, IAuditableEntity return location.IsComplete ? location : null; } - public void SetStoredSnapshot(string objectKey, StorageLocation location) + public void SetStoredSnapshot(string objectKey, StorageLocation location, string? thumbObjectKey = null) { if (string.IsNullOrWhiteSpace(objectKey)) throw new ArgumentException("Snapshot object key is required", nameof(objectKey)); ArgumentNullException.ThrowIfNull(location); if (!location.IsComplete) throw new ArgumentException("Snapshot storage location is incomplete", nameof(location)); SnapshotObjectKey = objectKey; + SnapshotThumbObjectKey = thumbObjectKey; SnapshotStorageProvider = location.Provider; SnapshotStorageRoot = location.LocalRoot; SnapshotStorageEndpoint = location.S3Endpoint; SnapshotStorageBucket = location.S3Bucket; SnapshotUrl = $"/api/events/{Id:D}/snapshot/content"; - SnapshotThumbUrl = null; + SnapshotThumbUrl = thumbObjectKey is null ? null : $"/api/events/{Id:D}/snapshot/thumbnail"; } public void SetMetadata(string? label, string? metadataJson) diff --git a/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs b/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs new file mode 100644 index 0000000..e9bcea5 --- /dev/null +++ b/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs @@ -0,0 +1,54 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Domain.Entities; + +/// Durable outcome of a user-requested frame capture. +public sealed class ManualSnapshotRequest +{ + private ManualSnapshotRequest() { } + + public ManualSnapshotRequest(Guid id, Guid cameraId, Guid agentId, DateTime now) + { + if (id == Guid.Empty || cameraId == Guid.Empty || agentId == Guid.Empty) + throw new ArgumentException("Snapshot request identifiers must be set."); + Id = id; + CameraId = cameraId; + AgentId = agentId; + CreatedAt = now; + UpdatedAt = now; + ExpiresAt = now.AddSeconds(30); + } + + public Guid Id { get; private set; } + public Guid CameraId { get; private set; } + public Guid AgentId { get; private set; } + public ManualSnapshotStatus Status { get; private set; } = ManualSnapshotStatus.Pending; + public string? FailureReason { get; private set; } + public DateTime CreatedAt { get; private set; } + public DateTime UpdatedAt { get; private set; } + public DateTime ExpiresAt { get; private set; } + + public void Fail(string reason, DateTime now) + { + if (Status == ManualSnapshotStatus.Completed) return; + Status = ManualSnapshotStatus.Failed; + FailureReason = reason; + UpdatedAt = now; + } + + public void Complete(DateTime now) + { + Status = ManualSnapshotStatus.Completed; + FailureReason = null; + UpdatedAt = now; + } + + public bool TimeoutIfExpired(DateTime now) + { + if (Status != ManualSnapshotStatus.Pending || now < ExpiresAt) return false; + Status = ManualSnapshotStatus.TimedOut; + FailureReason = "La capture n'a pas été livrée dans le délai attendu."; + UpdatedAt = now; + return true; + } +} diff --git a/src/Heimdall.Domain/Enums/EventType.cs b/src/Heimdall.Domain/Enums/EventType.cs index 4510159..4f74f87 100644 --- a/src/Heimdall.Domain/Enums/EventType.cs +++ b/src/Heimdall.Domain/Enums/EventType.cs @@ -9,5 +9,6 @@ public enum EventType FaceRecognized = 4, LicensePlateDetected = 5, CameraOffline = 6, - CameraOnline = 7 + CameraOnline = 7, + ManualSnapshot = 8 } diff --git a/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs b/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs new file mode 100644 index 0000000..edc044e --- /dev/null +++ b/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs @@ -0,0 +1,9 @@ +namespace Heimdall.Domain.Enums; + +public enum ManualSnapshotStatus +{ + Pending, + Completed, + Failed, + TimedOut +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 5a933a4..7c03f73 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -32,6 +32,21 @@ public static class JobSetup job => job.ExecuteAsync(CancellationToken.None), "0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut) + manager.AddOrUpdate( + "storage-staging-cleanup", + job => job.ExecuteAsync(CancellationToken.None), + "30 4 * * *"); + + manager.AddOrUpdate( + "storage-final-orphan-cleanup", + job => job.ExecuteAsync(CancellationToken.None), + "35 4 * * *"); + + manager.AddOrUpdate( + "manual-snapshot-request-cleanup", + job => job.ExecuteAsync(CancellationToken.None), + "45 4 * * *"); + // Maintenance (spec 7.5) — rétention, faces, plaques, DB. manager.AddOrUpdate( "retention-check", diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 0302179..f5e8ee6 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -50,6 +50,7 @@ public class AppDbContext : IdentityDbContext, IApplicat // Event entities public DbSet CameraEvents => Set(); + public DbSet ManualSnapshotRequests => Set(); // Notification entities public DbSet Notifications => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs index 01c9c0b..469b172 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs @@ -44,6 +44,10 @@ public class AgentConfiguration : IEntityTypeConfiguration .HasMaxLength(8) .IsUnicode(false); + builder.Property(a => a.LastAppliedCameraConfigVersion) + .HasMaxLength(64) + .IsUnicode(false); + builder.Property(a => a.GpuType) .HasConversion() .HasMaxLength(20) diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs index dc31da7..bf9c6bd 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs @@ -33,6 +33,7 @@ public class CameraEventConfiguration : IEntityTypeConfiguration .IsUnicode(false); builder.Property(e => e.SnapshotObjectKey).HasMaxLength(2000).IsUnicode(false); + builder.Property(e => e.SnapshotThumbObjectKey).HasMaxLength(2000).IsUnicode(false); builder.Property(e => e.SnapshotStorageProvider).HasConversion().HasMaxLength(20).IsUnicode(false); builder.Property(e => e.SnapshotStorageRoot).HasMaxLength(2000); builder.Property(e => e.SnapshotStorageEndpoint).HasMaxLength(2000); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs new file mode 100644 index 0000000..a3f1e2a --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs @@ -0,0 +1,21 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public sealed class ManualSnapshotRequestConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("manual_snapshot_requests"); + builder.HasKey(x => x.Id); + builder.Property(x => x.Status).HasConversion().HasMaxLength(20).IsRequired(); + builder.Property(x => x.FailureReason).HasMaxLength(200); + builder.Property(x => x.CreatedAt).IsRequired(); + builder.Property(x => x.UpdatedAt).IsRequired(); + builder.Property(x => x.ExpiresAt).IsRequired(); + builder.HasIndex(x => new { x.CameraId, x.CreatedAt }); + builder.HasIndex(x => x.ExpiresAt); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs new file mode 100644 index 0000000..18e9a6d --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs @@ -0,0 +1,30 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// Bounds the history of manual capture commands independently of camera events. +public sealed class ManualSnapshotRequestCleanupJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public ManualSnapshotRequestCleanupJob(IDbContextFactory dbFactory, + ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + var cutoff = DateTime.UtcNow.AddDays(-30); + var count = await db.ManualSnapshotRequests + .Where(r => r.CreatedAt < cutoff) + .ExecuteDeleteAsync(ct).ConfigureAwait(false); + if (count > 0) + _logger.LogInformation("Removed {Count} old manual snapshot requests", count); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs index 98f142e..11a70e9 100644 --- a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs @@ -167,12 +167,14 @@ public class PartitionManagerJob while (true) { var events = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking() - .Where(e => e.OccurredAt >= from && e.OccurredAt < to && e.SnapshotObjectKey != null) + .Where(e => e.OccurredAt >= from && e.OccurredAt < to && + (e.SnapshotObjectKey != null || e.SnapshotThumbObjectKey != null)) .OrderBy(e => e.Id).Skip(offset).Take(batchSize) .Select(e => new { e.Id, e.SnapshotObjectKey, + e.SnapshotThumbObjectKey, e.SnapshotStorageProvider, e.SnapshotStorageRoot, e.SnapshotStorageEndpoint, @@ -181,16 +183,22 @@ public class PartitionManagerJob if (events.Count == 0) break; if (_storage is null) throw new InvalidOperationException("Snapshot storage deletion is unavailable"); - var incomplete = events.FirstOrDefault(e => e.SnapshotStorageProvider is null || - !new StorageLocation(e.SnapshotStorageProvider.Value, e.SnapshotStorageRoot, - e.SnapshotStorageEndpoint, e.SnapshotStorageBucket).IsComplete); - if (incomplete is not null) - throw new InvalidOperationException($"Snapshot destination is incomplete for event {incomplete.Id}"); - - foreach (var group in events.GroupBy(e => new StorageLocation(e.SnapshotStorageProvider!.Value, - e.SnapshotStorageRoot, e.SnapshotStorageEndpoint, e.SnapshotStorageBucket))) - await _storage.DeleteBatchAsync( - group.Select(e => e.SnapshotObjectKey!).ToArray(), group.Key, ct).ConfigureAwait(false); + var objectsByLocation = new Dictionary>(); + foreach (var ev in events) + { + if (ev.SnapshotStorageProvider is null) + throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}"); + var location = new StorageLocation(ev.SnapshotStorageProvider.Value, + ev.SnapshotStorageRoot, ev.SnapshotStorageEndpoint, ev.SnapshotStorageBucket); + if (!location.IsComplete) + throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}"); + if (!objectsByLocation.TryGetValue(location, out var keys)) + objectsByLocation[location] = keys = []; + if (ev.SnapshotObjectKey is { } snapshot) keys.Add(snapshot); + if (ev.SnapshotThumbObjectKey is { } thumb) keys.Add(thumb); + } + foreach (var (location, keys) in objectsByLocation) + await _storage.DeleteBatchAsync(keys, location, ct).ConfigureAwait(false); offset += events.Count; if (events.Count < batchSize) break; diff --git a/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs new file mode 100644 index 0000000..6c83b7c --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs @@ -0,0 +1,144 @@ +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Storage; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// Reconciles final snapshot objects against exact persisted destinations and keys. +public sealed class StorageFinalOrphanCleanupJob( + IDbContextFactory dbFactory, + StorageProviderFactory storage, + ILogger logger) +{ + private const string Prefix = "snapshots/"; + private const int PageSize = 250; + + public async Task ExecuteAsync(CancellationToken ct) + { + // A week leaves ample time for an interrupted upload or delayed database retry. + var cutoff = DateTime.UtcNow.AddDays(-7); + await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false); + var destinations = new HashSet(); + try { destinations.Add(storage.CaptureCurrentLocation()); } + catch (Exception ex) when (ex is not OperationCanceledException) + { logger.LogWarning(ex, "Current snapshot storage destination cannot be inventoried"); } + + var recorded = await db.CameraEvents.AsNoTracking() + .Where(e => (e.SnapshotObjectKey != null || e.SnapshotThumbObjectKey != null) && + e.SnapshotStorageProvider != null) + .Select(e => new + { + e.SnapshotStorageProvider, e.SnapshotStorageRoot, + e.SnapshotStorageEndpoint, e.SnapshotStorageBucket + }) + .Distinct().ToListAsync(ct).ConfigureAwait(false); + foreach (var item in recorded) + { + var location = new StorageLocation(item.SnapshotStorageProvider!.Value, + item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket); + if (location.IsComplete) destinations.Add(location); + } + + foreach (var location in destinations) + { + string? cursor = null; + var deleted = 0; + try + { + do + { + ct.ThrowIfCancellationRequested(); + var page = await storage.ListObjectsPageAsync(Prefix, cursor, PageSize, location, ct) + .ConfigureAwait(false); + var candidates = page.Objects + .Where(item => item.LastModifiedUtc < cutoff && IsManagedSnapshotKey(item.Key)) + .ToArray(); + var referenced = await GetReferencedKeysAsync(db, + candidates.Select(item => item.Key).Distinct(StringComparer.Ordinal).ToArray(), + location, ct).ConfigureAwait(false); + foreach (var item in candidates) + { + if (referenced.Contains(item.Key)) continue; + await storage.DeleteAsync(item.Key, location, ct).ConfigureAwait(false); + deleted++; + } + cursor = page.NextCursor; + } while (cursor is not null); + if (deleted > 0) + logger.LogInformation("Removed {Count} unreferenced final snapshot objects from {Provider}", + deleted, location.Provider); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + logger.LogWarning(ex, "Final snapshot reconciliation failed for {Provider}; remaining objects retained", + location.Provider); + } + } + } + + private static async Task> GetReferencedKeysAsync(AppDbContext db, string[] keys, + StorageLocation candidate, CancellationToken ct) + { + var referenced = new HashSet(StringComparer.Ordinal); + if (keys.Length == 0) return referenced; + var keySet = new HashSet(keys, StringComparer.Ordinal); + var events = await db.CameraEvents.AsNoTracking() + .Where(e => keys.Contains(e.SnapshotObjectKey!) || keys.Contains(e.SnapshotThumbObjectKey!)) + .Select(e => new + { + e.SnapshotObjectKey, e.SnapshotThumbObjectKey, + e.SnapshotStorageProvider, e.SnapshotStorageRoot, + e.SnapshotStorageEndpoint, e.SnapshotStorageBucket + }).ToListAsync(ct).ConfigureAwait(false); + foreach (var item in events) + { + // Missing provenance is historical: its destination cannot be disproved. + var protectsCandidate = item.SnapshotStorageProvider is null; + if (!protectsCandidate) + { + var recorded = new StorageLocation(item.SnapshotStorageProvider!.Value, + item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket); + protectsCandidate = !recorded.IsComplete || recorded == candidate; + } + if (!protectsCandidate) continue; + if (item.SnapshotObjectKey is { } snapshot && keySet.Contains(snapshot)) referenced.Add(snapshot); + if (item.SnapshotThumbObjectKey is { } thumb && keySet.Contains(thumb)) referenced.Add(thumb); + } + + var recordings = await db.Recordings.AsNoTracking() + .Where(r => keys.Contains(r.StoragePath)) + .Select(r => new + { + r.StoragePath, r.StorageLocationCaptured, r.StorageProvider, + r.StorageRoot, r.StorageEndpoint, r.StorageBucket + }).ToListAsync(ct).ConfigureAwait(false); + foreach (var item in recordings) + { + if (!item.StorageLocationCaptured) + { + referenced.Add(item.StoragePath); + continue; + } + var recorded = new StorageLocation(item.StorageProvider, + item.StorageRoot, item.StorageEndpoint, item.StorageBucket); + if (!recorded.IsComplete || recorded == candidate) referenced.Add(item.StoragePath); + } + return referenced; + } + + private static bool IsManagedSnapshotKey(string key) + { + var parts = key.Split('/'); + if (parts.Length != 4 || parts[0] != "snapshots" || + !Guid.TryParseExact(parts[1], "D", out _) || + !Guid.TryParseExact(parts[2], "D", out _)) return false; + var name = parts[3]; + var suffix = name.EndsWith(".thumb.jpg", StringComparison.Ordinal) + ? ".thumb.jpg" : ".jpg"; + return name.EndsWith(suffix, StringComparison.Ordinal) && + Guid.TryParseExact(name[..^suffix.Length], "N", out _); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs new file mode 100644 index 0000000..522666d --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs @@ -0,0 +1,26 @@ +using Heimdall.Infrastructure.Storage; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// Removes temporary uploads left behind by interrupted writes. +public sealed class StorageStagingCleanupJob +{ + private readonly StorageProviderFactory _storage; + private readonly ILogger _logger; + + public StorageStagingCleanupJob(StorageProviderFactory storage, ILogger logger) + { + _storage = storage; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + // A long grace period avoids racing a slow in-flight upload. + var cutoff = DateTime.UtcNow.AddDays(-1); + var count = await _storage.CleanupStagingAsync(cutoff, ct).ConfigureAwait(false); + if (count > 0) + _logger.LogInformation("Removed {Count} abandoned staging objects", count); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs b/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs new file mode 100644 index 0000000..71a1969 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs @@ -0,0 +1,51 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261023010000_AddManualSnapshotRequests")] +public partial class AddManualSnapshotRequests : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "LastAppliedCameraConfigAt", + table: "agents", + type: "timestamp with time zone", + nullable: true); + migrationBuilder.AddColumn( + name: "LastAppliedCameraConfigVersion", + table: "agents", + type: "character varying(64)", + maxLength: 64, + nullable: true); + + migrationBuilder.CreateTable( + name: "manual_snapshot_requests", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + CameraId = table.Column(type: "uuid", nullable: false), + AgentId = table.Column(type: "uuid", nullable: false), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + FailureReason = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresAt = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => table.PrimaryKey("PK_manual_snapshot_requests", x => x.Id)); + migrationBuilder.CreateIndex("IX_manual_snapshot_requests_CameraId_CreatedAt", "manual_snapshot_requests", new[] { "CameraId", "CreatedAt" }); + migrationBuilder.CreateIndex("IX_manual_snapshot_requests_ExpiresAt", "manual_snapshot_requests", "ExpiresAt"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable("manual_snapshot_requests"); + migrationBuilder.DropColumn("LastAppliedCameraConfigAt", "agents"); + migrationBuilder.DropColumn("LastAppliedCameraConfigVersion", "agents"); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261023020000_AddEventSnapshotThumbnails.cs b/src/Heimdall.Infrastructure/Migrations/20261023020000_AddEventSnapshotThumbnails.cs new file mode 100644 index 0000000..870e3ce --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261023020000_AddEventSnapshotThumbnails.cs @@ -0,0 +1,19 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261023020000_AddEventSnapshotThumbnails")] +public partial class AddEventSnapshotThumbnails : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + => migrationBuilder.AddColumn("SnapshotThumbObjectKey", "camera_events", + type: "character varying(2000)", maxLength: 2000, nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) + => migrationBuilder.DropColumn("SnapshotThumbObjectKey", "camera_events"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 5eb0043..cda546b 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -123,6 +123,14 @@ namespace Heimdall.Infrastructure.Migrations b.Property("KernelVersion") .HasColumnType("text"); + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + b.Property("LastHeartbeat") .HasColumnType("timestamp with time zone"); @@ -1152,6 +1160,11 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(2000)"); + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + b.Property("SnapshotStorageProvider") .HasMaxLength(20) .IsUnicode(false) @@ -1456,6 +1469,44 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("login_challenges", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.HasIndex("ExpiresAt"); + + b.ToTable("manual_snapshot_requests", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => { b.Property("Id") diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs index f39d48e..b87bdeb 100644 --- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs @@ -162,13 +162,15 @@ public sealed class CameraEventService : ICameraEventService if (ev is null) return ServiceResult.NotFound("Event not found"); - if (ev.SnapshotObjectKey is not null) + if (ev.SnapshotObjectKey is not null || ev.SnapshotThumbObjectKey is not null) { var location = ev.GetSnapshotLocation(); if (location is null) return ServiceResult.Failure("Snapshot destination is incomplete", 409); using var scope = _serviceProvider.CreateScope(); var storage = scope.ServiceProvider.GetRequiredService(); - await storage.DeleteBatchAsync([ev.SnapshotObjectKey], location, ct).ConfigureAwait(false); + await storage.DeleteBatchAsync( + new[] { ev.SnapshotObjectKey, ev.SnapshotThumbObjectKey }.OfType().ToArray(), + location, ct).ConfigureAwait(false); } db.CameraEvents.Remove(ev); diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs index 941a236..f2153ba 100644 --- a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs @@ -143,6 +143,51 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable } } + public async Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default) + { + if (_client is null) + throw new InvalidOperationException("Alarik/S3 storage is not configured"); + + var deleted = 0; + string? continuationToken = null; + do + { + var page = await _client.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = _bucket, + Prefix = "staging/", + ContinuationToken = continuationToken, + }, ct).ConfigureAwait(false); + var expired = page.S3Objects + .Where(obj => obj.LastModified is DateTime modified && modified.ToUniversalTime() < olderThanUtc) + .Select(obj => obj.Key) + .ToArray(); + await DeleteBatchAsync(expired, ct).ConfigureAwait(false); + deleted += expired.Length; + continuationToken = page.IsTruncated == true ? page.NextContinuationToken : null; + } while (continuationToken is not null); + return deleted; + } + + public async Task ListObjectsPageAsync(string prefix, string? cursor, int pageSize, + CancellationToken ct = default) + { + if (_client is null) throw new InvalidOperationException("Alarik/S3 storage is not configured"); + if (pageSize is < 1 or > 1000) throw new ArgumentOutOfRangeException(nameof(pageSize)); + var page = await _client.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = _bucket, + Prefix = prefix, + StartAfter = cursor, + MaxKeys = pageSize, + }, ct).ConfigureAwait(false); + var objects = page.S3Objects.Select(x => new StorageObjectInfo(x.Key, + x.LastModified is DateTime modified ? modified.ToUniversalTime() : DateTime.MaxValue)) + .ToArray(); + return new StorageObjectPage(objects, + page.IsTruncated == true ? objects.LastOrDefault()?.Key : null); + } + public async Task HealthCheckAsync(CancellationToken ct = default) { if (_client is null) diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs index b4f87dd..2310a9e 100644 --- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -107,6 +107,94 @@ public sealed class LocalStorageProvider : IStorageProvider } } + public Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default) + { + if (!Directory.Exists(_root)) + return Task.FromResult(0); + + EnsureNoLinks(_root); + var deleted = 0; + var pending = new Stack(); + pending.Push(_root); + while (pending.Count > 0) + { + ct.ThrowIfCancellationRequested(); + var directory = pending.Pop(); + EnsureNoLinks(directory); + foreach (var entry in Directory.EnumerateFileSystemEntries(directory)) + { + ct.ThrowIfCancellationRequested(); + // Never follow a link, including a dangling link. + if (new FileInfo(entry).LinkTarget is not null || + (File.GetAttributes(entry) & FileAttributes.ReparsePoint) != 0) + continue; + if (Directory.Exists(entry)) + { + pending.Push(entry); + continue; + } + var name = Path.GetFileName(entry); + var marker = name.LastIndexOf(".tmp-", StringComparison.Ordinal); + if (marker < 1 || name.Length != marker + 5 + 32 || + !Guid.TryParseExact(name[(marker + 5)..], "N", out _)) + continue; + var info = new FileInfo(entry); + if (info.LastWriteTimeUtc >= olderThanUtc) + continue; + EnsureNoLinks(entry); + File.Delete(entry); + deleted++; + } + } + return Task.FromResult(deleted); + } + + public Task ListObjectsPageAsync(string prefix, string? cursor, int pageSize, + CancellationToken ct = default) + { + if (pageSize is < 1 or > 1000) throw new ArgumentOutOfRangeException(nameof(pageSize)); + var directory = ResolvePath(prefix.TrimEnd('/')); + if (!Directory.Exists(directory)) + return Task.FromResult(new StorageObjectPage([], null)); + + // Keep only the smallest pageSize + 1 keys in memory. A key cursor remains + // valid when objects from earlier pages are removed during reconciliation. + var reverse = Comparer.Create((a, b) => StringComparer.Ordinal.Compare(b, a)); + var smallest = new PriorityQueue(reverse); + var pending = new Stack(); + pending.Push(directory); + while (pending.Count > 0) + { + ct.ThrowIfCancellationRequested(); + var current = pending.Pop(); + EnsureNoLinks(current); + foreach (var entry in Directory.EnumerateFileSystemEntries(current)) + { + ct.ThrowIfCancellationRequested(); + if (new FileInfo(entry).LinkTarget is not null || + (File.GetAttributes(entry) & FileAttributes.ReparsePoint) != 0) + continue; + if (Directory.Exists(entry)) { pending.Push(entry); continue; } + var key = Path.GetRelativePath(_root, entry).Replace('\\', '/'); + if (!key.StartsWith(prefix, StringComparison.Ordinal) || + cursor is not null && StringComparer.Ordinal.Compare(key, cursor) <= 0) + continue; + var item = new StorageObjectInfo(key, new FileInfo(entry).LastWriteTimeUtc); + if (smallest.Count < pageSize + 1) smallest.Enqueue(item, key); + else if (StringComparer.Ordinal.Compare(key, smallest.Peek().Key) < 0) + { + smallest.Dequeue(); + smallest.Enqueue(item, key); + } + } + } + var sorted = smallest.UnorderedItems.Select(x => x.Element) + .OrderBy(x => x.Key, StringComparer.Ordinal).ToArray(); + var objects = sorted.Take(pageSize).ToArray(); + return Task.FromResult(new StorageObjectPage(objects, + sorted.Length > pageSize ? objects[^1].Key : null)); + } + public Task HealthCheckAsync(CancellationToken ct = default) { try diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index 74a035f..db782d0 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -209,6 +209,29 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat finally { DisposeProvider(provider); } } + public async Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default) + { + var provider = Resolve(); + try { return await provider.CleanupStagingAsync(olderThanUtc, ct).ConfigureAwait(false); } + finally { DisposeProvider(provider); } + } + + public async Task ListObjectsPageAsync(string prefix, string? cursor, int pageSize, + CancellationToken ct = default) + { + var provider = Resolve(); + try { return await provider.ListObjectsPageAsync(prefix, cursor, pageSize, ct).ConfigureAwait(false); } + finally { DisposeProvider(provider); } + } + + public async Task ListObjectsPageAsync(string prefix, string? cursor, int pageSize, + Heimdall.Domain.Entities.StorageLocation location, CancellationToken ct = default) + { + var provider = Resolve(location); + try { return await provider.ListObjectsPageAsync(prefix, cursor, pageSize, ct).ConfigureAwait(false); } + finally { DisposeProvider(provider); } + } + private static void DisposeProvider(IStorageProvider provider) => (provider as IDisposable)?.Dispose(); private IStorageProvider Resolve(string? providerOverride = null) diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 77d580f..67855ee 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -31,7 +31,7 @@ else if (_camera is null) } else { - @* ─── Live view : snapshot rafraîchi ─── *@ + @* ─── Dernière image événementielle, rafraîchie périodiquement ─── *@
@if (_snapshotLoading) @@ -40,11 +40,13 @@ else } else if (!string.IsNullOrEmpty(_latestSnapshotUrl)) { - Vue live de @_camera.Name - @if (_camera.Status == "Online") + @if (_latestSnapshotAt is DateTime capturedAt) { - + + Dernière image : @capturedAt.ToLocalTime().ToString("g") + } } else @@ -62,7 +64,7 @@ else + OnClick="@TakeSnapshot" /> !string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl)) is { } latest - ? (latest.SnapshotThumbUrl ?? latest.SnapshotUrl) - : null; + var events = await Api.GetRecentEventsAsync(Id, 20); + var latest = events?.FirstOrDefault(e => !string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl)); + _latestSnapshotUrl = latest?.SnapshotThumbUrl ?? latest?.SnapshotUrl; + _latestSnapshotAt = latest?.OccurredAt; } catch { /* flux indisponible */ } finally @@ -301,6 +303,47 @@ else private async Task RefreshSnapshot() => await LoadLatestSnapshotAsync(); + private async Task TakeSnapshot() + { + _snapshotLoading = true; + try + { + var request = await Api.RequestCameraSnapshotAsync(Id); + if (!request.Succeeded || request.Data == Guid.Empty) + { + Snackbar.Add(request.ErrorMessage ?? UiErrors.OperationFailed(), Severity.Error); + return; + } + + Snackbar.Add("Capture demandée à l'agent", Severity.Info); + for (var attempt = 0; attempt < 35 && !_disposed; attempt++) + { + await Task.Delay(TimeSpan.FromSeconds(1)); + var status = await Api.GetCameraSnapshotStatusAsync(Id, request.Data); + if (status?.Status is "Failed" or "TimedOut") + { + Snackbar.Add(status.Reason ?? "La capture a échoué.", Severity.Error); + return; + } + if (status?.Status != "Completed") continue; + var snapshot = await Api.GetEventAsync(request.Data); + if (snapshot is null || string.IsNullOrEmpty(snapshot.SnapshotUrl)) continue; + _latestSnapshotUrl = snapshot.SnapshotThumbUrl ?? snapshot.SnapshotUrl; + _latestSnapshotAt = snapshot.OccurredAt; + await LoadEventsAsync(); + Snackbar.Add("Snapshot disponible", Severity.Success); + return; + } + Snackbar.Add("Le résultat de la capture est encore en attente ; actualisez la page pour le consulter.", Severity.Info); + } + catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } + finally + { + _snapshotLoading = false; + if (!_disposed) await InvokeAsync(StateHasChanged); + } + } + private async Task SaveCamera() { if (string.IsNullOrWhiteSpace(_editName)) { _editError = "Le nom est requis"; return; } @@ -375,6 +418,7 @@ else private static string FormatEventType(string type) => type switch { + "ManualSnapshot" => "Capture manuelle", "MotionDetected" => "Mouvement", "PersonDetected" => "Personne", "VehicleDetected" => "Véhicule", diff --git a/src/Heimdall.Web/Components/Pages/EventsPage.razor b/src/Heimdall.Web/Components/Pages/EventsPage.razor index 91dbbc0..b680afc 100644 --- a/src/Heimdall.Web/Components/Pages/EventsPage.razor +++ b/src/Heimdall.Web/Components/Pages/EventsPage.razor @@ -233,6 +233,7 @@ else private static string FormatEventType(string type) => type switch { + "ManualSnapshot" => "Capture manuelle", "MotionDetected" => "Mouvement", "PersonDetected" => "Personne", "VehicleDetected" => "Véhicule", diff --git a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor index 9a8d1ca..76da153 100644 --- a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor +++ b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor @@ -24,6 +24,7 @@ Plaque détectée Caméra hors ligne Caméra en ligne + Capture manuelle Charger @@ -162,6 +163,7 @@ else private static string FormatEventType(string type) => type switch { + "ManualSnapshot" => "Capture manuelle", "MotionDetected" => "Mouvement", "PersonDetected" => "Personne", "VehicleDetected" => "Véhicule", diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index d883551..cc3e8c8 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -6,11 +6,16 @@ using Heimdall.Application.Cameras.Commands.ToggleCameraStatus; using Heimdall.Application.Cameras.Queries.GetCamera; using Heimdall.Application.Cameras.Queries.GetCamerasBySite; using Heimdall.Application.DTOs; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Api.Controllers; @@ -20,8 +25,88 @@ namespace Heimdall.Api.Controllers; public class CamerasController : ControllerBase { private readonly IMediator _mediator; + private readonly IApplicationDbContext _db; + private readonly IConfigBroadcastService _broadcast; - public CamerasController(IMediator mediator) => _mediator = mediator; + public CamerasController(IMediator mediator, IApplicationDbContext db, IConfigBroadcastService broadcast) + { + _mediator = mediator; + _db = db; + _broadcast = broadcast; + } + + /// Ask the assigned agent to capture a new frame from its active stream. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost("{id:guid}/snapshot")] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task RequestSnapshot(Guid id, CancellationToken ct) + { + var camera = await _db.Cameras.AsNoTracking().Where(c => c.Id == id) + .Select(c => new { c.AgentId, c.Status }).FirstOrDefaultAsync(ct); + if (camera is null) return NotFound(); + if (camera.Status != CameraStatus.Online) return Conflict(new { error = "The camera is not online" }); + if (camera.AgentId is null) return Conflict(new { error = "No agent is assigned to this camera" }); + var requestId = Guid.NewGuid(); + var snapshotRequest = new ManualSnapshotRequest(requestId, id, camera.AgentId.Value, DateTime.UtcNow); + _db.ManualSnapshotRequests.Add(snapshotRequest); + await _db.SaveChangesWithRetryAsync(ct: ct); + if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct)) + { + snapshotRequest.Fail("L'agent affecté est indisponible.", DateTime.UtcNow); + await _db.SaveChangesWithRetryAsync(ct: ct); + return Conflict(new { error = "The assigned agent is offline" }); + } + return Accepted(new { requestId }); + } + + /// Read the durable outcome of a manual capture request. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("{id:guid}/snapshot/{requestId:guid}")] + public async Task GetSnapshotRequest(Guid id, Guid requestId, CancellationToken ct) + { + var request = await _db.ManualSnapshotRequests.AsNoTracking() + .FirstOrDefaultAsync(r => r.Id == requestId && r.CameraId == id, ct); + if (request is null) return NotFound(); + if (request.Status == ManualSnapshotStatus.Pending && request.ExpiresAt <= DateTime.UtcNow) + { + await _db.ManualSnapshotRequests + .Where(r => r.Id == requestId && r.Status == ManualSnapshotStatus.Pending && r.ExpiresAt <= DateTime.UtcNow) + .ExecuteUpdateAsync(setters => setters + .SetProperty(r => r.Status, ManualSnapshotStatus.TimedOut) + .SetProperty(r => r.FailureReason, "La capture n'a pas été livrée dans le délai attendu.") + .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct); + request = await _db.ManualSnapshotRequests.AsNoTracking() + .FirstAsync(r => r.Id == requestId, ct); + } + return Ok(new { requestId = request.Id, status = request.Status.ToString(), + reason = request.FailureReason, updatedAt = request.UpdatedAt }); + } + + /// Record a capture failure reported by the agent assigned when the command was issued. + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("{id:guid}/snapshot/{requestId:guid}/failure")] + public async Task FailSnapshotRequest(Guid id, Guid requestId, + [FromBody] ManualSnapshotFailure failure, CancellationToken ct) + { + var exists = await _db.ManualSnapshotRequests.AnyAsync(r => r.Id == requestId && r.CameraId == id, ct); + if (!exists) return NotFound(); + var reason = failure.Code switch + { + "camera_unavailable" => "La caméra n'est plus affectée ou est désactivée sur l'agent.", + "no_frame" => "Aucune image n'a été reçue du flux de la caméra.", + "queue_failed" => "L'agent n'a pas pu enregistrer la capture pour livraison.", + _ => "La capture a échoué sur l'agent." + }; + await _db.ManualSnapshotRequests + .Where(r => r.Id == requestId && r.CameraId == id && r.Status != ManualSnapshotStatus.Completed) + .ExecuteUpdateAsync(setters => setters + .SetProperty(r => r.Status, ManualSnapshotStatus.Failed) + .SetProperty(r => r.FailureReason, reason) + .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct); + return NoContent(); + } + + public sealed record ManualSnapshotFailure(string Code); /// Create a new camera. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs index fc0d7cc..ca6e9f3 100644 --- a/src/Heimdall.Web/Controllers/EventsController.cs +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -10,6 +10,7 @@ using Heimdall.Application.Events.Queries.GetRecentByCamera; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; using Heimdall.Infrastructure.Storage; +using ImageMagick; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -133,7 +134,11 @@ public class EventsController : ControllerBase var ev = await _db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct); if (ev is null) return NotFound(); - if (ev.SnapshotObjectKey is not null) return Ok(new { url = ev.SnapshotUrl }); + if (ev.SnapshotObjectKey is not null) + { + await CompleteManualSnapshotRequestAsync(ev, ct); + return Ok(new { url = ev.SnapshotUrl }); + } var mediaType = Request.ContentType?.Split(';')[0].Trim(); if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase)) @@ -156,25 +161,70 @@ public class EventsController : ControllerBase bytes[^2] != 0xff || bytes[^1] != 0xd9) return BadRequest(new { error = "A complete JPEG image is required" }); + byte[] thumbnail; + try + { + // Inspect dimensions before decoding pixels: a small compressed JPEG + // can otherwise request an excessive amount of native memory. + var info = new MagickImageInfo(bytes); + if (info.Format != MagickFormat.Jpeg || info.Width > 8192 || info.Height > 8192 || + (long)info.Width * info.Height > 32_000_000) + return BadRequest(new { error = "Image dimensions exceed the allowed limit" }); + using var image = new MagickImage(bytes); + if (image.Width > 8192 || image.Height > 8192 || (long)image.Width * image.Height > 32_000_000) + return BadRequest(new { error = "Image dimensions exceed the allowed limit" }); + image.AutoOrient(); + image.Resize(new MagickGeometry(320, 180)); + image.Strip(); + image.Quality = 75; + thumbnail = image.ToByteArray(MagickFormat.Jpeg); + } + catch (MagickException) + { + return BadRequest(new { error = "A decodable JPEG image is required" }); + } + var location = _storage.CaptureCurrentLocation(); - var key = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}.jpg"; - await using (var content = new MemoryStream(bytes, writable: false)) - await _storage.UploadAsync(key, content, "image/jpeg", location, ct); + var baseKey = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}"; + var key = baseKey + ".jpg"; + var thumbKey = baseKey + ".thumb.jpg"; + var uploaded = new List(2); try { - ev.SetStoredSnapshot(key, location); + await using (var content = new MemoryStream(bytes, writable: false)) + await _storage.UploadAsync(key, content, "image/jpeg", location, ct); + uploaded.Add(key); + await using (var content = new MemoryStream(thumbnail, writable: false)) + await _storage.UploadAsync(thumbKey, content, "image/jpeg", location, ct); + uploaded.Add(thumbKey); + + ev.SetStoredSnapshot(key, location, thumbKey); + var manualRequest = ev.Type == EventType.ManualSnapshot + ? await _db.ManualSnapshotRequests.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct) + : null; + manualRequest?.Complete(DateTime.UtcNow); await _db.SaveChangesWithRetryAsync(ct: ct); } catch { - try { await _storage.DeleteAsync(key, location, CancellationToken.None); } + try { await _storage.DeleteBatchAsync(uploaded, location, CancellationToken.None); } catch (Exception cleanupError) { _logger.LogWarning(cleanupError, "Could not remove unreferenced snapshot for event {EventId}", id); } throw; } return Ok(new { url = ev.SnapshotUrl }); } + private async Task CompleteManualSnapshotRequestAsync(Heimdall.Domain.Entities.CameraEvent ev, CancellationToken ct) + { + if (ev.Type != EventType.ManualSnapshot) return; + var request = await _db.ManualSnapshotRequests + .FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct); + if (request is null || request.Status == ManualSnapshotStatus.Completed) return; + request.Complete(DateTime.UtcNow); + await _db.SaveChangesWithRetryAsync(ct: ct); + } + /// Stream a stored JPEG only to a user allowed to read its camera. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet("{id:guid}/snapshot/content")] @@ -194,6 +244,25 @@ public class EventsController : ControllerBase return File(stream, "image/jpeg"); } + /// Stream a stored JPEG thumbnail under the same camera access check as the original. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("{id:guid}/snapshot/thumbnail")] + public async Task DownloadSnapshotThumbnail(Guid id, CancellationToken ct) + { + var requester = await _access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await _access.EventAsync(requester, id, ct)) return Forbid(); + + var ev = await _db.CameraEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id, ct); + var location = ev?.GetSnapshotLocation(); + if (ev?.SnapshotThumbObjectKey is null || location is null) return NotFound(); + var stream = await _storage.DownloadAsync(ev.SnapshotThumbObjectKey, location, ct); + if (stream is null) return NotFound(); + Response.Headers["Cache-Control"] = "private, no-store"; + Response.Headers["X-Content-Type-Options"] = "nosniff"; + return File(stream, "image/jpeg"); + } + /// Delete an event. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] [HttpDelete("{id:guid}")] diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index 898700e..e3f7472 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Agents.Queries.GetAgent; +using Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; @@ -138,7 +139,7 @@ public class SettingsController : ControllerBase /// /// Get the effective configuration for an agent: global defaults merged with /// per-agent overrides, plus the site's camera credential pool inside an - /// encrypted envelope. Accessible by the agent itself (API key, same site) + /// encrypted envelope. Accessible by the agent itself (API key) /// or by an admin (JWT/Cookie). /// [Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")] @@ -147,10 +148,13 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct) { - // API key callers: the agent may only read its own site's config. + // The API key is bound to exactly one agent. Same-site agents must not + // be able to read each other's RTSP URLs or credential envelopes. var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key"); if (isApiKey) { + if (User.FindFirst("agent_id")?.Value != agentId.ToString()) + return Forbid(); var siteClaim = User.FindFirst("site_id")?.Value; if (!Guid.TryParse(siteClaim, out var apiKeySiteId)) return Forbid(); @@ -167,9 +171,38 @@ public class SettingsController : ControllerBase } var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); + if (!result.IsSuccess || result.Data is null) + return NotFound(new { error = result.Error }); + Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(result.Data); + return Ok(result.Data); + } + + public sealed record CameraConfigAckRequest(string Version); + + /// Acknowledge the exact camera snapshot applied by this agent. + [Authorize(AuthenticationSchemes = "ApiKey")] + [HttpPost("agent/{agentId:guid}/camera-config-ack")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task AcknowledgeCameraConfig(Guid agentId, + [FromBody] CameraConfigAckRequest request, CancellationToken ct) + { + if (User.FindFirst("agent_id")?.Value != agentId.ToString()) + return Forbid(); + if (request.Version?.Length != 64 || !request.Version.All(Uri.IsHexDigit)) + return BadRequest(new { error = "Invalid camera configuration version" }); + + var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct); + if (!result.IsSuccess || result.Data is null) + return NotFound(new { error = result.Error }); + if (!string.Equals(CameraConfigVersion.Compute(result.Data), request.Version, + StringComparison.OrdinalIgnoreCase)) + return Conflict(new { error = "Camera configuration changed before acknowledgement" }); + + if (!await _mediator.Send(new AcknowledgeCameraConfigCommand(agentId, request.Version), ct)) + return NotFound(); + _logger.LogInformation("Agent {AgentId} applied camera configuration {Version}", agentId, request.Version); + return NoContent(); } /// List all setting overrides for a specific agent (Admin only). diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs index 0847dba..84abca3 100644 --- a/src/Heimdall.Web/Controllers/UpdatesController.cs +++ b/src/Heimdall.Web/Controllers/UpdatesController.cs @@ -41,7 +41,7 @@ public class UpdatesController : ControllerBase _configuration = configuration; } - [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [AllowAnonymous] [HttpGet("latest")] [ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)] public async Task GetLatestRelease(CancellationToken ct) @@ -123,6 +123,15 @@ public class UpdatesController : ControllerBase var image = await FetchAgentImageManifestAsync(release.Assets, client, ct); result.ContainerImage = image?.Image; result.ContainerImageDigest = image?.Digest; + var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets, + "agent-update-manifest.json", client, 1_048_576, ct); + var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets, + "agent-update-manifest.sig", client, 512, ct); + if (manifestBytes is not null && signatureBytes is not null) + { + result.SignedManifest = Convert.ToBase64String(manifestBytes); + result.ManifestSignature = Convert.ToBase64String(signatureBytes); + } lock (_cacheLock) { _cache = new LatestReleaseCache(source!, result, DateTime.UtcNow); } return result; } @@ -163,6 +172,36 @@ public class UpdatesController : ControllerBase private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit); + private static async Task FetchBoundedReleaseAssetAsync(List? assets, + string name, HttpClient client, int maxBytes, CancellationToken ct) + { + var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.Ordinal)); + var expected = asset is null ? null : ExtractSha256(asset.Digest); + if (asset is null || !IsSha256Digest(expected)) return null; + try + { + using var response = await client.GetAsync(asset.BrowserDownloadUrl, + HttpCompletionOption.ResponseHeadersRead, ct); + if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes) + return null; + await using var stream = await response.Content.ReadAsStreamAsync(ct); + using var buffer = new MemoryStream(); + var chunk = new byte[8192]; + while (true) + { + var read = await stream.ReadAsync(chunk, ct); + if (read == 0) break; + if (buffer.Length + read > maxBytes) return null; + buffer.Write(chunk, 0, read); + } + var bytes = buffer.ToArray(); + return string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected, + StringComparison.OrdinalIgnoreCase) ? bytes : null; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch { return null; } + } + private static bool IsValidContainerImageRepository(string? image) => image is { Length: > 0 and <= 255 } && char.IsAsciiLetterOrDigit(image[0]) && image.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or ':' or '/' or '-') @@ -197,6 +236,7 @@ public class UpdatesController : ControllerBase if (l.Contains("win-x64") || l.Contains("windows-x64")) return "win-x64"; if (l.Contains("osx-x64") || l.Contains("macos-x64")) return "osx-x64"; if (l.Contains("osx-arm64") || l.Contains("macos-arm64")) return "osx-arm64"; + if (l.Contains("agent-portable-")) return "portable"; return null; } @@ -215,6 +255,8 @@ public class UpdatesController : ControllerBase [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } + [JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; } + [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; } } public class PlatformAsset { diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 02fa911..df6b60c 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -23,6 +23,7 @@ + diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs index f6fdc22..48bf8d2 100644 --- a/src/Heimdall.Web/Hubs/ConfigHub.cs +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -134,6 +134,22 @@ public class ConfigBroadcastService : IConfigBroadcastService return true; } + /// Requests one frame from the assigned agent's active camera stream. + public async Task RequestManualSnapshot(Guid agentId, Guid cameraId, Guid requestId, CancellationToken ct = default) + { + using var scope = _scopeFactory.CreateScope(); + var services = scope.ServiceProvider; + var access = services.GetRequiredService(); + var subscriptions = services.GetRequiredService(); + var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access, + r => access.AgentAsync(r, agentId, ct), ct); + if (recipients.Count == 0) return false; + await _hubContext.Clients.Clients(recipients).SendAsync("ManualSnapshotRequested", cameraId, requestId, ct); + _logger.LogInformation("Requested manual snapshot {RequestId} from agent {AgentId} for camera {CameraId}", + requestId, agentId, cameraId); + return true; + } + /// public async Task NotifyAllAgentsReload(CancellationToken ct = default) { diff --git a/src/Heimdall.Web/Security/ResourceAccessFilter.cs b/src/Heimdall.Web/Security/ResourceAccessFilter.cs index 97e8196..467ae3a 100644 --- a/src/Heimdall.Web/Security/ResourceAccessFilter.cs +++ b/src/Heimdall.Web/Security/ResourceAccessFilter.cs @@ -41,6 +41,10 @@ public sealed class ResourceAccessFilter(ResourceAccess access, IApplicationDbCo { "Create" => await Site(Id("SiteId")), "ListBySite" => true, // camera query is filtered before pagination + "FailSnapshotRequest" => r.Kind == RequesterKind.Agent && Id("requestId") is Guid snapshotRequestId && + Id("id") is Guid snapshotCameraId && + await db.ManualSnapshotRequests.AnyAsync(s => s.Id == snapshotRequestId && + s.CameraId == snapshotCameraId && s.AgentId == r.Id, ct), _ => await Camera(Id("id")) }; break; diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index cf8ce66..7a5e7d9 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -444,6 +444,25 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } + public async Task> RequestCameraSnapshotAsync(Guid id) + { + var client = CreateClient(); + using var response = await client.PostAsync($"api/cameras/{id}/snapshot", null); + if (!response.IsSuccessStatusCode) + return ApiResult.Failure(await ReadErrorMessageAsync(response)); + var request = await response.Content.ReadFromJsonAsync(Json); + return request is null || request.RequestId == Guid.Empty + ? ApiResult.Failure(InvalidServerResponse) + : ApiResult.Success(request.RequestId); + } + + public async Task GetCameraSnapshotStatusAsync(Guid cameraId, Guid requestId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync( + $"api/cameras/{cameraId:D}/snapshot/{requestId:D}", Json); + } + public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status, string? manufacturer = null, string? model = null) { @@ -1202,6 +1221,15 @@ public record SetAgentSettingRequest( [property: JsonPropertyName("value")] string Value ); +public record ManualSnapshotRequestResult( + [property: JsonPropertyName("requestId")] Guid RequestId); + +public record ManualSnapshotStatusItem( + [property: JsonPropertyName("requestId")] Guid RequestId, + [property: JsonPropertyName("status")] string Status, + [property: JsonPropertyName("reason")] string? Reason, + [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt); + public record EventItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("cameraId")] Guid CameraId, diff --git a/src/Heimdall.Web/packages.lock.json b/src/Heimdall.Web/packages.lock.json index af7c812..0d0ecbc 100644 --- a/src/Heimdall.Web/packages.lock.json +++ b/src/Heimdall.Web/packages.lock.json @@ -33,6 +33,15 @@ "Npgsql": "6.0.11" } }, + "Magick.NET-Q16-AnyCPU": { + "type": "Direct", + "requested": "[14.16.0, )", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, "Microsoft.AspNetCore.App.Internal.Assets": { "type": "Direct", "requested": "[10.0.13, )", @@ -222,6 +231,11 @@ "resolved": "10.0.1", "contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg==" }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, "MediatR": { "type": "Transitive", "resolved": "12.5.0", diff --git a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs index fa92f43..4705263 100644 --- a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs @@ -203,6 +203,30 @@ public class CameraStreamServiceTests } } + [Fact] + public async Task CaptureNextFrameAsync_ReturnsFreshFrameFromActiveStream() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return; + var scriptPath = Path.Combine(Path.GetTempPath(), $"heimdall-frame-test-{Guid.NewGuid():N}.sh"); + await File.WriteAllTextAsync(scriptPath, + "#!/bin/sh\ni=0\nwhile [ \"$i\" -lt 20 ]; do printf '\\377\\330\\377\\331'; sleep 0.2; i=$((i+1)); done\n"); + File.SetUnixFileMode(scriptPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + try + { + using var service = new CameraStreamService(Substitute.For>(), scriptPath); + var cameraId = Guid.NewGuid(); + (await service.StartStreamAsync(cameraId, "rtsp://camera/test")).ShouldBeTrue(); + + var frame = await service.CaptureNextFrameAsync(cameraId); + + frame.ShouldNotBeNull(); + frame.CameraId.ShouldBe(cameraId); + frame.JpegData.ShouldBe(new byte[] { 0xff, 0xd8, 0xff, 0xd9 }); + await service.StopStreamAsync(cameraId); + } + finally { File.Delete(scriptPath); } + } + [Fact] public void Constructor_WithSceneDependencies_DoesNotThrow() { diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index c094fd7..4331e7a 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -1,7 +1,9 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using System.Reflection; +using System.Text.Json; using Heimdall.Agent.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Security; @@ -37,7 +39,10 @@ public class ConfigReceiverServiceTests Substitute.For>(), new ContainerInfoProvider()); var dockerUpdateService = new DockerUpdateService(options, state, new ContainerInfoProvider(), httpFactory, Substitute.For>()); - return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore(), updateService, dockerUpdateService, new ContainerInfoProvider()); + return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), + runtimeLogLevel, cameraStore ?? new CameraConfigStore(), + new CameraStreamService(Substitute.For>()), + Substitute.For(), updateService, dockerUpdateService, new ContainerInfoProvider()); } /// @@ -72,7 +77,13 @@ public class ConfigReceiverServiceTests builder.Services.AddSignalR(); await using var app = builder.Build(); app.MapHub("/hubs/config"); - app.MapGet("/api/settings/agent/{id}", () => Volatile.Read(ref config)); + app.MapGet("/api/settings/agent/{id}", (HttpContext context) => + { + var snapshot = Volatile.Read(ref config); + context.Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(snapshot); + return Results.Json(snapshot); + }); + app.MapPost("/api/settings/agent/{id}/camera-config-ack", () => Results.NoContent()); await app.StartAsync(); var factory = Substitute.For(); factory.CreateClient("Central").Returns(_ => new HttpClient()); @@ -501,7 +512,7 @@ public class ConfigReceiverServiceTests await service.StopAsync(CancellationToken.None); } - /// Returns a fixed JSON body for any request (used to stub the Central config API). + /// Returns the versioned Central config and accepts its acknowledgement. private sealed class StubHttpMessageHandler : HttpMessageHandler { private readonly string _json; @@ -511,10 +522,14 @@ public class ConfigReceiverServiceTests protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.Method == HttpMethod.Post) + return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent)); var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json") }; + var settings = JsonSerializer.Deserialize>(_json)!; + response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(settings)); return Task.FromResult(response); } } diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs index 59d2408..46c1c7c 100644 --- a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs @@ -82,4 +82,39 @@ public class DetectionReporterServiceTests if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); } } + + [Fact] + public async Task ManualSnapshots_KeepRequestIds_WithoutCooldown() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-manual-outbox-{Guid.NewGuid():N}"); + try + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" }; + using var reporter = new DetectionReporterService(state, + Substitute.For(), Substitute.For>(), + Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory })); + var cameraId = Guid.NewGuid(); + var firstId = Guid.NewGuid(); + var secondId = Guid.NewGuid(); + var jpeg = new byte[] { 0xff, 0xd8, 0xff, 0xd9 }; + + (await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual", + snapshotJpeg: jpeg, eventId: firstId)).ShouldBeTrue(); + (await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual", + snapshotJpeg: jpeg, eventId: secondId)).ShouldBeTrue(); + + await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-events.db")}"); + await db.OpenAsync(); + await using var command = db.CreateCommand(); + command.CommandText = "SELECT event_id FROM pending_detection_events ORDER BY event_id;"; + await using var reader = await command.ExecuteReaderAsync(); + var ids = new List(); + while (await reader.ReadAsync()) ids.Add(Guid.Parse(reader.GetString(0))); + ids.OrderBy(id => id).ShouldBe(new[] { firstId, secondId }.OrderBy(id => id)); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } } diff --git a/tests/Heimdall.Api.Tests/packages.lock.json b/tests/Heimdall.Api.Tests/packages.lock.json index ec7c5e7..20e3083 100644 --- a/tests/Heimdall.Api.Tests/packages.lock.json +++ b/tests/Heimdall.Api.Tests/packages.lock.json @@ -203,6 +203,19 @@ "resolved": "10.0.1", "contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg==" }, + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, "MediatR": { "type": "Transitive", "resolved": "12.5.0", @@ -1074,6 +1087,7 @@ "Heimdall.Application": "[1.0.0, )", "Heimdall.Contracts": "[1.0.0, )", "Heimdall.Infrastructure": "[1.0.0, )", + "Magick.NET-Q16-AnyCPU": "[14.16.0, )", "Microsoft.AspNetCore.OpenApi": "[10.0.13, )", "Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )", "MudBlazor": "[9.8.0, )", diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs new file mode 100644 index 0000000..cb82105 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs @@ -0,0 +1,27 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Events.Notifications; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class ManualSnapshotNotificationTests +{ + [Fact] + public async Task ManualSnapshot_BroadcastsEventWithoutDetectionAlert() + { + var broadcast = Substitute.For(); + var access = Substitute.For(); + var notifications = Substitute.For(); + var handler = new EventCreatedNotificationHandler(broadcast, access, notifications); + var cameraEvent = new CameraEventResponse(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), + null, null, EventType.ManualSnapshot, 1, "manual", null, null, null, + DateTime.UtcNow, DateTime.UtcNow); + + await handler.Handle(new EventCreatedNotification(cameraEvent), CancellationToken.None); + + await broadcast.Received(1).NotifyEventCreated(cameraEvent, Arg.Any()); + await access.DidNotReceiveWithAnyArgs().GetUserIdsWithCameraAccessAsync(default); + } +} diff --git a/tests/Heimdall.E2E.Tests/packages.lock.json b/tests/Heimdall.E2E.Tests/packages.lock.json index b78fdaf..024e173 100644 --- a/tests/Heimdall.E2E.Tests/packages.lock.json +++ b/tests/Heimdall.E2E.Tests/packages.lock.json @@ -287,6 +287,19 @@ "resolved": "10.0.1", "contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg==" }, + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, "MediatR": { "type": "Transitive", "resolved": "12.5.0", @@ -1378,6 +1391,7 @@ "Heimdall.Application": "[1.0.0, )", "Heimdall.Contracts": "[1.0.0, )", "Heimdall.Infrastructure": "[1.0.0, )", + "Magick.NET-Q16-AnyCPU": "[14.16.0, )", "Microsoft.AspNetCore.OpenApi": "[10.0.13, )", "Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )", "MudBlazor": "[9.8.0, )", diff --git a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs index bb5f698..4b105b5 100644 --- a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs @@ -59,22 +59,23 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres) #pragma warning disable EF1002 // Test DDL identifiers generated exclusively from dates. await db.Database.ExecuteSqlRawAsync($""" CREATE TABLE camera_events ( - "Id" uuid NOT NULL, + "Id" uuid NOT NULL DEFAULT gen_random_uuid(), "OccurredAt" timestamptz NOT NULL, - "SnapshotObjectKey" text, - "SnapshotStorageProvider" text, - "SnapshotStorageRoot" text, - "SnapshotStorageEndpoint" text, - "SnapshotStorageBucket" text + "SnapshotObjectKey" text NULL, + "SnapshotThumbObjectKey" text NULL, + "SnapshotStorageProvider" text NULL, + "SnapshotStorageRoot" text NULL, + "SnapshotStorageEndpoint" text NULL, + "SnapshotStorageBucket" text NULL ) PARTITION BY RANGE ("OccurredAt"); CREATE TABLE "{expiredName}" PARTITION OF camera_events FOR VALUES FROM ('{old:yyyy-MM-dd}') TO ('{old.AddMonths(1):yyyy-MM-dd}'); CREATE TABLE "{boundaryName}" PARTITION OF camera_events FOR VALUES FROM ('{boundary:yyyy-MM-dd}') TO ('{boundary.AddMonths(1):yyyy-MM-dd}'); CREATE TABLE camera_events_bad PARTITION OF camera_events DEFAULT; CREATE TABLE "{unrelatedName}" (id int); - INSERT INTO camera_events ("Id", "OccurredAt", "SnapshotObjectKey", + INSERT INTO camera_events ("Id", "OccurredAt", "SnapshotObjectKey", "SnapshotThumbObjectKey", "SnapshotStorageProvider", "SnapshotStorageRoot") VALUES ('00000000-0000-0000-0000-000000000001', '{old:yyyy-MM-dd}', - 'snapshots/old.jpg', 'Local', '/tmp/heimdall-snapshots'); + 'snapshots/old.jpg', 'snapshots/old-thumb.jpg', 'Local', '/tmp/heimdall-snapshots'); """); #pragma warning restore EF1002 var storage = Substitute.For(); @@ -82,7 +83,8 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres) // A second execution must be harmless. await new PartitionManagerJob(factory, NullLogger.Instance, storage).ExecuteAsync(CancellationToken.None); await storage.Received(1).DeleteBatchAsync( - Arg.Is>(keys => keys != null && keys.Contains("snapshots/old.jpg")), + Arg.Is>(keys => keys != null && + keys.Contains("snapshots/old.jpg") && keys.Contains("snapshots/old-thumb.jpg")), Arg.Is(location => location != null && location.Provider == StorageProvider.Local && location.LocalRoot == "/tmp/heimdall-snapshots"), Arg.Any()); await using var conn = new NpgsqlConnection(builder.ConnectionString); diff --git a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs index 65c59f4..8354960 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs @@ -87,4 +87,30 @@ public class CamerasControllerTests : PostgresTestBase var response = await client.PostAsync($"api/cameras/{Guid.NewGuid()}/toggle-status", null); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); } + + [Fact] + public async Task ManualSnapshot_RequiresOnlineCameraAndAssignedAgent() + { + var client = await Factory.CreateAdminClientAsync(); + var siteResponse = await client.PostAsJsonAsync("api/sites", new + { + name = $"Manual Snapshot {Guid.NewGuid():N}", + timezone = "UTC" + }); + var siteId = (await siteResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + var createResponse = await client.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Manual Snapshot Camera", + rtspUrl = "rtsp://192.168.1.100:554/stream1" + }); + var cameraId = (await createResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + + (await client.PostAsync($"api/cameras/{cameraId}/snapshot", null)) + .StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict); + (await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null)) + .StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + (await client.PostAsync($"api/cameras/{cameraId}/snapshot", null)) + .StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict); + } } diff --git a/tests/Heimdall.IntegrationTests/packages.lock.json b/tests/Heimdall.IntegrationTests/packages.lock.json index 10f1710..affef04 100644 --- a/tests/Heimdall.IntegrationTests/packages.lock.json +++ b/tests/Heimdall.IntegrationTests/packages.lock.json @@ -280,6 +280,19 @@ "resolved": "10.0.1", "contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg==" }, + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, "MediatR": { "type": "Transitive", "resolved": "12.5.0", @@ -1338,6 +1351,7 @@ "Heimdall.Application": "[1.0.0, )", "Heimdall.Contracts": "[1.0.0, )", "Heimdall.Infrastructure": "[1.0.0, )", + "Magick.NET-Q16-AnyCPU": "[14.16.0, )", "Microsoft.AspNetCore.OpenApi": "[10.0.13, )", "Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )", "MudBlazor": "[9.8.0, )", diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index 4ded1f7..ab3cc9d 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -88,7 +88,7 @@ public class CameraDetailTests : PageTestBase cut.WaitForAssertion(() => { cut.Markup.ShouldContain("http://alarik/thumbs/live.jpg"); - cut.Markup.ShouldContain("Vue live de Caméra Entrée"); + cut.Markup.ShouldContain("Dernière image de Caméra Entrée"); }); } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs index 3cc6b57..351797b 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs @@ -193,7 +193,7 @@ public class PersonDetailPageTests : PageTestBase } [Fact] - public void PersonDetail_HistoriqueFiltreParNom() + public void PersonDetail_HistoriqueFiltreParPersonId() { Handler.OnGet($"api/persons/{PersonId}/faces", new List()); Handler.OnGet("api/vehicles", new List()); @@ -207,8 +207,7 @@ public class PersonDetailPageTests : PageTestBase { cut.Markup.ShouldContain("Alice Dupont"); cut.Markup.ShouldNotContain("Bob Martin"); - Handler.Requests.ShouldContain(request => request.RequestUri != null && request.RequestUri.AbsolutePath == "/api/events" - && request.RequestUri.Query.Contains($"personId={PersonId}", StringComparison.Ordinal)); + Handler.Requests.ShouldContain(r => r.RequestUri!.PathAndQuery.Contains($"personId={PersonId}", StringComparison.OrdinalIgnoreCase)); }); } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs index c5a26e9..e9abc13 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs @@ -44,14 +44,10 @@ public class SiteDetailTests : PageTestBase [Fact] public void SiteDetail_GenererToken_AfficheDockerCompose() { + Handler.OnGet("api/updates/latest", AgentRelease()); Handler.OnGet("api/sites/", new SiteItem( SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10))); Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24))); - Handler.OnGet("api/updates/latest", new LatestReleaseInfo - { - ContainerImage = "registry.example/heimdall-agent", - ContainerImageDigest = "sha256:" + new string('a', 64) - }); LoginAs(); var cut = RenderPage(p => p.Add(x => x.Id, SiteId)); @@ -71,14 +67,10 @@ public class SiteDetailTests : PageTestBase [Fact] public void SiteDetail_CopierDockerCompose_AppellePressePapier() { + Handler.OnGet("api/updates/latest", AgentRelease()); Handler.OnGet("api/sites/", new SiteItem( SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10))); Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24))); - Handler.OnGet("api/updates/latest", new LatestReleaseInfo - { - ContainerImage = "registry.example/heimdall-agent", - ContainerImageDigest = "sha256:" + new string('a', 64) - }); JSInterop.SetupVoid("navigator.clipboard.writeText", _ => true).SetVoidResult(); LoginAs(); @@ -127,6 +119,13 @@ public class SiteDetailTests : PageTestBase LastUsedAt = lastUsed, }; + private static LatestReleaseInfo AgentRelease() => new() + { + Version = "1.0.0", + ContainerImage = "registry.example/heimdall-agent", + ContainerImageDigest = "sha256:" + new string('a', 64) + }; + [Fact] public void SiteDetail_AucunIdentifiant_AfficheMessage() { diff --git a/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs index fc2a234..3696a57 100644 --- a/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs +++ b/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs @@ -3,6 +3,7 @@ using Heimdall.Api.Controllers; using Heimdall.Application.Cameras.Commands.ToggleCameraStatus; using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -21,7 +22,7 @@ public class CamerasControllerTests .Returns(ServiceResult.NotFound("Camera not found")); var actorId = Guid.NewGuid(); var cameraId = Guid.NewGuid(); - var controller = new CamerasController(mediator) + var controller = new CamerasController(mediator, Substitute.For(), Substitute.For()) { ControllerContext = new ControllerContext { @@ -47,7 +48,7 @@ public class CamerasControllerTests public async Task ToggleStatus_rejects_missing_actor_claim() { var mediator = Substitute.For(); - var controller = new CamerasController(mediator) + var controller = new CamerasController(mediator, Substitute.For(), Substitute.For()) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; diff --git a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs index 14f789e..c3db57a 100644 --- a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs +++ b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using NSubstitute; using Shouldly; namespace Heimdall.Web.Tests.Security; @@ -37,6 +38,7 @@ public sealed class HttpIsolationTests builder.Services.AddSingleton(f.Db); builder.Services.AddSingleton(f.Db); builder.Services.AddSingleton(f.Cameras); + builder.Services.AddSingleton(Substitute.For()); builder.Services.AddScoped(); builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining()); builder.Services.AddControllers(o => o.Filters.Add()).AddApplicationPart(typeof(CamerasController).Assembly); diff --git a/tests/Heimdall.Web.Tests/packages.lock.json b/tests/Heimdall.Web.Tests/packages.lock.json index 6955949..f56b00e 100644 --- a/tests/Heimdall.Web.Tests/packages.lock.json +++ b/tests/Heimdall.Web.Tests/packages.lock.json @@ -272,6 +272,19 @@ "resolved": "10.0.1", "contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg==" }, + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, "MediatR": { "type": "Transitive", "resolved": "12.5.0", @@ -1228,6 +1241,7 @@ "Heimdall.Application": "[1.0.0, )", "Heimdall.Contracts": "[1.0.0, )", "Heimdall.Infrastructure": "[1.0.0, )", + "Magick.NET-Q16-AnyCPU": "[14.16.0, )", "Microsoft.AspNetCore.OpenApi": "[10.0.13, )", "Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )", "MudBlazor": "[9.8.0, )",