PIPE-09 et AGENT-06 : miniatures, orphelins et releases signées #58

Merged
arnaud.dartois merged 3 commits from fix/pipe09-thumbnails into main 2026-10-23 18:59:53 +02:00
39 changed files with 1070 additions and 108 deletions

No files matched your search

+1
View File
@@ -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
+38
View File
@@ -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.
+11 -8
View File
@@ -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 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 23 octobre, `main` inclut les PR #2–#56, dont la capture manuelle corrélée. 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; la CI #176 échoue 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.
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. La branche en cours ajoute la purge quotidienne des objets staging âgés de plus de 24 h sur la destination active. Les références anciennes, les destinations antérieures, les objets finaux orphelins 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 branche en cours ajoute un statut persistant pour les commandes et leur échec; miniatures et validation sur caméra réelle restent ouverts. |
| 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 (miniatures, état d'échec 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. 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, 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.
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é
+83
View File
@@ -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)
+61 -14
View File
@@ -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]
+2
View File
@@ -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 |
|---------|-------|-----------|
+37 -1
View File
@@ -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
+6
View File
@@ -104,6 +104,12 @@ public sealed class AgentOptions
public string DockerSocketPath { get; init; } = "/var/run/docker.sock";
public bool AutoUpdateEnabled { get; set; }
/// <summary>Locally provisioned publisher public key; Central cannot change this setting.</summary>
public string? UpdatePublicKeyPath { get; init; }
/// <summary>Locally installed agent release root containing current and releases.</summary>
public string? UpdateInstallRoot { get; init; }
private static string? ReadSystemdCredential(string name)
{
var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
@@ -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<LatestReleaseResponse?> 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<string, AssetDto> Assets { get; set; } = [];
[JsonPropertyName("signedManifest")]
public string? SignedManifest { get; set; }
[JsonPropertyName("manifestSignature")]
public string? ManifestSignature { get; set; }
}
private sealed class AssetDto
@@ -27,8 +27,11 @@ public sealed class CameraStreamService : IDisposable
private readonly SystemMetricsProvider _metrics;
private readonly AdaptiveSnapshotInterval _snapshotInterval;
private readonly ConcurrentDictionary<Guid, StreamSession> _sessions = new();
private readonly ConcurrentDictionary<Guid, StreamControl> _controls = new();
private readonly object _lifecycleGate = new();
private readonly ConcurrentDictionary<Guid, ManualCaptureRequest> _manualRequests = new();
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
private int _disposed;
private readonly ConcurrentDictionary<Guid, Heimdall.Application.DTOs.DetectionProfileDto> _profiles = new();
public void SetDetectionProfile(Guid cameraId, Heimdall.Application.DTOs.DetectionProfileDto profile) => _profiles[cameraId] = profile;
@@ -87,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
@@ -120,53 +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<KeyValuePair<Guid, StreamSession>>)_sessions)
.Remove(new KeyValuePair<Guid, StreamSession>(cameraId, startedSession));
if (process is not null)
{
try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { }
process.Dispose();
}
_throttle.Release();
}
return false;
}
}
/// <summary>Stop streaming from a camera.</summary>
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)
{
CancelManualRequest(cameraId, session);
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);
}
/// <summary>Stops every active stream (agent shutdown).</summary>
public async Task StopAllAsync()
{
foreach (var cameraId in _sessions.Keys.ToArray())
await StopStreamAsync(cameraId);
await StopStreamAsync(cameraId).ConfigureAwait(false);
}
/// <summary>Number of currently active streams.</summary>
@@ -216,13 +257,14 @@ public sealed class CameraStreamService : IDisposable
private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
{
var buffer = ArrayPool<byte>.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);
@@ -232,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);
@@ -258,6 +304,7 @@ 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) &&
@@ -269,7 +316,7 @@ public sealed class CameraStreamService : IDisposable
// 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;
@@ -315,14 +362,11 @@ public sealed class CameraStreamService : IDisposable
}
finally
{
if (!session.SemaphoreReleased)
{
session.SemaphoreReleased = true;
_throttle.Release();
}
if (((ICollection<KeyValuePair<Guid, StreamSession>>)_sessions)
.Remove(new KeyValuePair<Guid, StreamSession>(cameraId, session)))
CancelManualRequest(cameraId, session);
session.Dispose();
_throttle.Release();
}
}
@@ -337,31 +381,45 @@ public sealed class CameraStreamService : IDisposable
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<Snapshot> Completion);
private sealed class StreamControl
{
public object Gate { get; } = new();
public int Generation;
}
}
@@ -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
{
@@ -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;
/// <summary>Stages a signed framework-dependent archive and switches the managed installation.</summary>
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);
}
@@ -0,0 +1,61 @@
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Heimdall.Agent.Services;
/// <summary>Verifies a publisher-signed release independently of Central and the release host.</summary>
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<SignedAgentRelease>(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<string, string> Assets { get; init; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; init; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; }
}
@@ -29,6 +29,13 @@ public interface IStorageProvider
/// <summary>Remove abandoned temporary uploads older than the cutoff.</summary>
Task<int> CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default);
/// <summary>List final objects by key, in pages. Cursor is the last key of the previous page.</summary>
Task<StorageObjectPage> ListObjectsPageAsync(string prefix, string? cursor, int pageSize,
CancellationToken ct = default);
/// <summary>Check reachability/health of the backend.</summary>
Task<bool> HealthCheckAsync(CancellationToken ct = default);
}
public sealed record StorageObjectInfo(string Key, DateTime LastModifiedUtc);
public sealed record StorageObjectPage(IReadOnlyList<StorageObjectInfo> Objects, string? NextCursor);
@@ -24,10 +24,12 @@ public class DeleteEventHandler : IRequestHandler<DeleteEventCommand, ServiceRes
return ServiceResult.NotFound("Event not found");
var location = ev.GetSnapshotLocation();
if (ev.SnapshotObjectKey is not null)
if (ev.SnapshotObjectKey is not null || ev.SnapshotThumbObjectKey is not null)
{
if (location is null) return ServiceResult.Failure("Snapshot destination is incomplete", 409);
await _storage.DeleteBatchAsync([ev.SnapshotObjectKey], location, ct).ConfigureAwait(false);
await _storage.DeleteBatchAsync(
new[] { ev.SnapshotObjectKey, ev.SnapshotThumbObjectKey }.OfType<string>().ToArray(),
location, ct).ConfigureAwait(false);
}
_context.CameraEvents.Remove(ev);
+4 -2
View File
@@ -17,6 +17,7 @@ public class CameraEvent : Entity<Guid>, 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<Guid>, 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)
@@ -37,6 +37,11 @@ public static class JobSetup
job => job.ExecuteAsync(CancellationToken.None),
"30 4 * * *");
manager.AddOrUpdate<StorageFinalOrphanCleanupJob>(
"storage-final-orphan-cleanup",
job => job.ExecuteAsync(CancellationToken.None),
"35 4 * * *");
manager.AddOrUpdate<ManualSnapshotRequestCleanupJob>(
"manual-snapshot-request-cleanup",
job => job.ExecuteAsync(CancellationToken.None),
@@ -33,6 +33,7 @@ public class CameraEventConfiguration : IEntityTypeConfiguration<CameraEvent>
.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<string>().HasMaxLength(20).IsUnicode(false);
builder.Property(e => e.SnapshotStorageRoot).HasMaxLength(2000);
builder.Property(e => e.SnapshotStorageEndpoint).HasMaxLength(2000);
@@ -1,5 +1,6 @@
using System.Globalization;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -166,18 +167,34 @@ public class PartitionManagerJob
while (true)
{
var events = await db.CameraEvents.AsNoTracking()
.Where(e => e.OccurredAt >= from && e.OccurredAt < to && e.SnapshotObjectKey != null)
.OrderBy(e => e.Id).Skip(offset).Take(batchSize).ToListAsync(ct).ConfigureAwait(false);
.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, e.SnapshotStorageBucket
}).ToListAsync(ct).ConfigureAwait(false);
if (events.Count == 0) break;
if (_storage is null) throw new InvalidOperationException("Snapshot storage deletion is unavailable");
var incomplete = events.FirstOrDefault(e => e.GetSnapshotLocation() is null);
if (incomplete is not null)
throw new InvalidOperationException($"Snapshot destination is incomplete for event {incomplete.Id}");
foreach (var group in events.GroupBy(e => e.GetSnapshotLocation()!))
await _storage.DeleteBatchAsync(
group.Select(e => e.SnapshotObjectKey!).ToArray(), group.Key, ct).ConfigureAwait(false);
var objectsByLocation = new Dictionary<StorageLocation, List<string>>();
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;
@@ -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;
/// <summary>Reconciles final snapshot objects against exact persisted destinations and keys.</summary>
public sealed class StorageFinalOrphanCleanupJob(
IDbContextFactory<AppDbContext> dbFactory,
StorageProviderFactory storage,
ILogger<StorageFinalOrphanCleanupJob> 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<StorageLocation>();
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<HashSet<string>> GetReferencedKeysAsync(AppDbContext db, string[] keys,
StorageLocation candidate, CancellationToken ct)
{
var referenced = new HashSet<string>(StringComparer.Ordinal);
if (keys.Length == 0) return referenced;
var keySet = new HashSet<string>(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 _);
}
}
@@ -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<string>("SnapshotThumbObjectKey", "camera_events",
type: "character varying(2000)", maxLength: 2000, nullable: true);
protected override void Down(MigrationBuilder migrationBuilder)
=> migrationBuilder.DropColumn("SnapshotThumbObjectKey", "camera_events");
}
@@ -1160,6 +1160,11 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotThumbObjectKey")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotStorageProvider")
.HasMaxLength(20)
.IsUnicode(false)
@@ -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<IStorageObjectDeletion>();
await storage.DeleteBatchAsync([ev.SnapshotObjectKey], location, ct).ConfigureAwait(false);
await storage.DeleteBatchAsync(
new[] { ev.SnapshotObjectKey, ev.SnapshotThumbObjectKey }.OfType<string>().ToArray(),
location, ct).ConfigureAwait(false);
}
db.CameraEvents.Remove(ev);
@@ -169,6 +169,25 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable
return deleted;
}
public async Task<StorageObjectPage> 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<bool> HealthCheckAsync(CancellationToken ct = default)
{
if (_client is null)
@@ -149,6 +149,52 @@ public sealed class LocalStorageProvider : IStorageProvider
return Task.FromResult(deleted);
}
public Task<StorageObjectPage> 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<string>.Create((a, b) => StringComparer.Ordinal.Compare(b, a));
var smallest = new PriorityQueue<StorageObjectInfo, string>(reverse);
var pending = new Stack<string>();
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<bool> HealthCheckAsync(CancellationToken ct = default)
{
try
@@ -216,6 +216,22 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat
finally { DisposeProvider(provider); }
}
public async Task<StorageObjectPage> 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<StorageObjectPage> 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)
@@ -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;
@@ -160,14 +161,45 @@ 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<string>(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;
@@ -176,7 +208,7 @@ public class EventsController : ControllerBase
}
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;
}
@@ -212,6 +244,25 @@ public class EventsController : ControllerBase
return File(stream, "image/jpeg");
}
/// <summary>Stream a stored JPEG thumbnail under the same camera access check as the original.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}/snapshot/thumbnail")]
public async Task<IActionResult> 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");
}
/// <summary>Delete an event.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
@@ -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<IActionResult> 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<byte[]?> FetchBoundedReleaseAssetAsync(List<ForgejoAsset>? 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<string, PlatformAsset> 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
{
+1
View File
@@ -23,6 +23,7 @@
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.17" />
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" />
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.17.0-beta.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
+14
View File
@@ -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",
@@ -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;
@@ -75,7 +77,13 @@ public class ConfigReceiverServiceTests
builder.Services.AddSignalR();
await using var app = builder.Build();
app.MapHub<ReconnectFixtureHub>("/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<IHttpClientFactory>();
factory.CreateClient("Central").Returns(_ => new HttpClient());
@@ -504,7 +512,7 @@ public class ConfigReceiverServiceTests
await service.StopAsync(CancellationToken.None);
}
/// <summary>Returns a fixed JSON body for any request (used to stub the Central config API).</summary>
/// <summary>Returns the versioned Central config and accepts its acknowledgement.</summary>
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly string _json;
@@ -514,10 +522,14 @@ public class ConfigReceiverServiceTests
protected override Task<HttpResponseMessage> 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<Dictionary<string, string>>(_json)!;
response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(settings));
return Task.FromResult(response);
}
}
@@ -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, )",
@@ -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, )",
@@ -54,7 +54,16 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres)
var unrelatedName = $"camera_events_{old.AddMonths(-2):yyyy_MM}";
#pragma warning disable EF1002 // Test DDL identifiers generated exclusively from dates.
await db.Database.ExecuteSqlRawAsync($"""
CREATE TABLE camera_events (occurred_at timestamptz NOT NULL) PARTITION BY RANGE (occurred_at);
CREATE TABLE camera_events (
"Id" uuid NOT NULL DEFAULT gen_random_uuid(),
"OccurredAt" timestamptz NOT NULL,
"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;
@@ -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, )",
@@ -193,12 +193,11 @@ public class PersonDetailPageTests : PageTestBase
}
[Fact]
public void PersonDetail_HistoriqueFiltreParNom()
public void PersonDetail_HistoriqueFiltreParPersonId()
{
Handler.OnGet($"api/persons/{PersonId}/faces", new List<KnownFaceClientItem>());
Handler.OnGet("api/vehicles", new List<VehicleClientItem>());
Handler.OnGet("api/events",
new EventPageResult([Ev("Alice Dupont"), Ev("Bob Martin")], 2, 1, 50));
Handler.OnGet("api/events", new EventPageResult([Ev("Alice Dupont")], 1, 1, 50));
Handler.OnGet("api/persons/", Person());
LoginAs();
@@ -208,6 +207,7 @@ public class PersonDetailPageTests : PageTestBase
{
cut.Markup.ShouldContain("Alice Dupont");
cut.Markup.ShouldNotContain("Bob Martin");
Handler.Requests.ShouldContain(r => r.RequestUri!.PathAndQuery.Contains($"personId={PersonId}", StringComparison.OrdinalIgnoreCase));
});
}
@@ -44,6 +44,7 @@ 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)));
@@ -66,6 +67,7 @@ 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)));
@@ -117,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()
{
@@ -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<IApplicationDbContext>(f.Db);
builder.Services.AddSingleton(f.Db);
builder.Services.AddSingleton<ICameraAccessService>(f.Cameras);
builder.Services.AddSingleton(Substitute.For<IConfigBroadcastService>());
builder.Services.AddScoped<ResourceAccess>();
builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining<GetCameraQuery>());
builder.Services.AddControllers(o => o.Filters.Add<ResourceAccessFilter>()).AddApplicationPart(typeof(CamerasController).Assembly);
@@ -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, )",