29 Commits
Author SHA1 Message Date
arnaud.dartois 383205b9fc Fix signed release metadata and Linux Agent deployment (#415)
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 38m21s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 22m18s
Heimdall Gitea / Build and scan server image (push) Successful in 8m54s
Heimdall Gitea / Build and scan agent image (push) Successful in 6m40s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 3s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-14 11:59:38 +01:00
arnaud.dartois 0e6371483d security: redact authentication data from Sentry events (#412)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 18m7s
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 5m6s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
## Problème et résultat
Les callbacks Sentry Web `SetBeforeSend` et `SetBeforeSendTransaction` expurgent les données sensibles des requêtes et réponses, y compris `Env` et `Other`, contextes, extras, breadcrumbs, tags et spans. Les cartes structurées sont filtrées récursivement; tableaux, collections et objets opaques sont supprimés au lieu d’être sérialisés sans inspection.

Refs #411

## Vérification
- `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SentryTelemetryPrivacyTests --no-restore --verbosity minimal` : 4/4 réussis.
- `skills/sentry-telemetry-privacy/acceptance.sh` : 4/4 réussis dans le projet Compose jetable `heimdall-sentry-privacy-20261113131621-cad401a7ee`, restore verrouillé; conteneurs, volumes et réseau vérifiés absents. Aucune image locale construite; image SDK amont conservée.
- `bash -n skills/sentry-telemetry-privacy/acceptance.sh` et `git diff --check` réussis.
- Tests uniquement avec sentinelles synthétiques. Aucun événement n’a été envoyé à GlitchTip, aucun credential externe n’a été modifié; provenance/rotation de l’ancienne valeur reste une action opérateur suivie dans #411.

## Livraison

- Le skill couvre maintenant les requêtes `Env`/`Other`, les tags d’événements et les structures imbriquées opaques.

### Release assessment
**Release required; proposed version 1.0.8 (PATCH).** Correction de sécurité rétrocompatible qui doit être reçue par les opérateurs. Base stable locale actuelle : 1.0.7; recalculer après merge si `main` ou les tags ont évolué. Aucun tag n’est créé avant merge et succès des contrôles.

Reviewed-on: #412
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 15:23:45 +01:00
arnaud.dartois 04b3279d1f docs: qualify optional Ollama integration status (#410)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:47:01 +01:00
arnaud.dartois 0cc41235c7 docs: clarify health check contracts in spec (#408)
Heimdall Gitea / Detect CI scope (push) Successful in 24s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 8s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:42:42 +01:00
arnaud.dartois 32d68595d5 docs: sync documentation index with current guides (#406)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:36:04 +01:00
arnaud.dartois 8df487002e docs: align GPU and inference claims in technical spec (#404)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:28:52 +01:00
arnaud.dartois f1894a26d6 docs: align domain model summary with current entities (#402)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 8s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:21:21 +01:00
arnaud.dartois d1dcd903d7 docs: remove stale UI page count from technical spec (#400)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:16:47 +01:00
arnaud.dartois 068dd44304 docs: align notification summary in technical spec (#398)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:11:14 +01:00
arnaud.dartois 91816fbf29 docs: align specification role summaries with identity (#396)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:07:01 +01:00
arnaud.dartois 4898d8343d docs: mark the implementation plan as historical (#394)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 12:00:22 +01:00
arnaud.dartois b78c3deea2 docs: clarify optional Coturn live-view integration (#392)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 16m26s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:50:21 +01:00
arnaud.dartois bf13b70a53 docs: scope historical notification design (#390)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:22:23 +01:00
arnaud.dartois b4d24c3345 docs: replace stale auth UI examples (#388)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:13:37 +01:00
arnaud.dartois 8f3d75680d docs: align auth model example with Identity layers (#386)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:09:20 +01:00
arnaud.dartois 1e84000749 docs: align auth index with three roles (#384)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:06:37 +01:00
arnaud.dartois 02cd37a1cb docs: distinguish optional GPU Agent image (#382)
Heimdall Gitea / Detect CI scope (push) Successful in 10s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:04:24 +01:00
arnaud.dartois e2a73431b5 docs: align auth guide with three-role model (#380)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 11:01:34 +01:00
arnaud.dartois 333036aa36 docs: align notification index summaries (#378)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:57:52 +01:00
arnaud.dartois 53bb5e8b06 docs: distinguish shipped notification channels (#376)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:55:21 +01:00
arnaud.dartois 79b4b86177 docs: remove retired admin route example (#374)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:47:30 +01:00
arnaud.dartois c065b44578 docs: mark retired admin page route as removed (#372)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:44:10 +01:00
arnaud.dartois 021bdecab3 docs: align Hangfire dashboard guide with route (#370)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:38:44 +01:00
arnaud.dartois f20ec93f6f docs: align auth guide with current camera access (#368)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:34:53 +01:00
arnaud.dartois 1a570a31e3 docs: align camera live route and role policy (#366)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:24:10 +01:00
arnaud.dartois cd8536ac65 docs: align master spec with shipped live view (#364)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:19:14 +01:00
arnaud.dartois f18df60b42 docs: reconcile Prometheus implementation status (#362)
Heimdall Gitea / Detect CI scope (push) Successful in 23s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Heimdall Gitea / Build and scan server image (push) Skipped
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:05:01 +01:00
arnaud.dartois af7a1b9585 docs: describe scheduled S3 mirror client (#360)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 17m6s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:01:35 +01:00
arnaud.dartois bdffcf4732 docs: align recording, relay, and PWA status (#357)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Correct delivered feature status and distinguish implementation from external validation.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 02:26:35 +01:00
64 changed files with 1574 additions and 1809 deletions

No files matched your search

+15 -4
View File
@@ -6,11 +6,17 @@ Sauvegarde automatisée de PostgreSQL (quotidien) et RustFS/S3 (hebdomadaire) av
| Composant | Fréquence | Script | Rétention |
|---|---|---|---|
| PostgreSQL `pg_dump` | Quotidien 02:00 UTC | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
| RustFS `mc mirror` | Hebdo dimanche 03:00 UTC | `docker/scripts/backup-rustfs.sh` | 12 semaines |
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15 UTC | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
| PostgreSQL `pg_dump` | Quotidien 02:00, heure du conteneur | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
| Miroir RustFS/S3 (`aws s3 sync` dans le Compose livré) | Dimanche 03:00, heure du conteneur | `docker/scripts/backup-rustfs.sh` | 12 semaines |
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15, heure du conteneur | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
| Test de restauration | Manuel / CI | `docker/scripts/test-backup-restore.sh` | — |
Le Compose backup définit `TZ` à `Europe/Paris` par défaut; ces horaires
s'appliquent donc à l'heure locale de Paris, avec les changements saisonniers.
Définir `TZ` avec un identifiant de fuseau IANA pour choisir un autre fuseau.
Les scripts horodatent leurs archives en UTC; l'heure du nom d'archive peut donc
différer de l'heure locale d'exécution.
## Activation
### Compose facultatif séparé
@@ -25,6 +31,10 @@ rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils
de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload
RustFS/S3 est facultatif.
Le service fourni installe AWS CLI, pas MinIO Client : `backup-rustfs.sh`
utilise donc `aws s3 sync` avec l'endpoint configuré. Le script conserve un
chemin de compatibilité `mc mirror` si `mc` est déjà présent dans une image ou
un environnement personnalisé; il ne télécharge ni n'installe ce binaire.
Le service monte aussi le volume `heimdall_data` du Compose Central : les
objets stockés localement et les clés Data Protection sont archivés ensemble.
Le nom par défaut est `docker_heimdall_data`, pour le projet Compose du dépôt.
@@ -50,6 +60,7 @@ configurés. Garder l’application Central arrêtée pendant une restauration.
| `BACKUP_RETENTION_DAYS` | `30` | Rétention jours (PostgreSQL) |
| `BACKUP_RETENTION_WEEKS` | `12` | Rétention semaines (RustFS) |
| `BACKUP_LOCAL_DIR` | `/backups` | Répertoire local dans le conteneur |
| `TZ` | `Europe/Paris` | Fuseau utilisé par le planning cron du conteneur |
## Structure des backups
@@ -321,6 +332,6 @@ docker compose -f docker/docker-compose.backup.yml exec backup ls -la /var/log/b
- **pg_dump --format=custom** nécessite `pg_restore` pour la restauration (pas `psql`)
- Le conteneur backup utilise `postgres:17-alpine` pour avoir `pg_dump` et `pg_restore`
- mc (MinIO Client) est installé au démarrage du conteneur (curl depuis dl.min.io)
- Le Compose livré installe `aws-cli`, Bash et GNU coreutils; il n'installe pas MinIO Client. Le script de miroir préfère `mc` s'il est déjà fourni, sinon utilise AWS CLI `s3 sync`.
- Si S3 n'est pas configuré, le backup est local uniquement (volume Docker)
- La restauration DROP la base existante — toujours vérifier le `--dry-run` d'abord
+3 -1
View File
@@ -1,4 +1,6 @@
# Optional TURN relay, used only by a future/externally integrated WebRTC setup.
# Optional TURN relay for live view; Central uses its URL and shared secret to
# issue short-lived browser credentials. Public reachability needs deployment
# firewall/NAT validation.
services:
coturn:
image: coturn/coturn:4.6
+137 -134
View File
@@ -1,8 +1,9 @@
# Heimdall — Master Specification Technique
> **Version :** 2.0 | **Date :** 2026-07-16
> **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC
> **Status :** SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts
> **Stack de la baseline :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents)
> **Statut :** baseline de conception historique datée du 2026-07-16; ce document n'est pas la source de vérité sur l'implémentation livrée.
> **État livré :** voir [spécifications actuelles](specs.md), [hubs SignalR mappés](signalr-usage.md), [déploiement Compose et live view](docker-compose.md), et [skill live-view](../skills/webrtc-live/SKILL.md).
>
> **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`,
> `auth-roles.md`, `pwa.md`, `hangfire-usage.md`, `ui-pages.md`
@@ -16,7 +17,7 @@
### D1 — Accès mobile via la PWA du serveur
Le client natif est retiré. L’application Blazor devient la cible mobile installable ; la première version conserve Interactive Server avec une page hors connexion et Web Push. La consultation métier hors ligne nécessitera une couche cliente autonome. Voir [l’audit PWA](pwa.md).
Le client natif est retiré. L’application Blazor est la cible mobile installable. Le socle livré conserve Interactive Server et fournit une page statique hors connexion; Web Push et la consultation métier hors ligne restent des objectifs non implémentés. Voir [l’état livré et l’audit PWA](pwa.md).
### D2 — Topologie : API + Web fusionnés (1 conteneur)
@@ -27,29 +28,29 @@ Le client natif est retiré. L’application Blazor devient la cible mobile inst
**Exception** : En scaling horizontal, on peut séparer les conteneurs avec un Redis backplane.
### D3 — TURN/Coturn obligatoire (pas optionnel)
### D3 — TURN selon la connectivité du réseau (ancienne décision obligatoire retirée)
| Choix | Raison |
|---|---|
| **Coturn REQUIS** | CGNAT (4G/5G), pare-feu entreprises, Starlink — toute installation derrière NAT |
| Optionnel rejeté | WebRTC échoue silencieusement sans TURN → support impossible |
| **TURN est une option de déploiement** | Les connexions ICE directes peuvent suffire; déployer et configurer TURN lorsque le NAT ou le pare-feu empêche la connectivité directe. |
| Pas de TURN universellement requis | La présence du Compose Coturn ne prouve ni sa configuration Central, ni son accessibilité publique; ces vérifications restent propres au déploiement. |
### D4 — Agents : Installation Docker uniquement
| Choix | Raison |
|---|---|
| **Docker uniquement** | FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes |
| **Docker uniquement** | FFmpeg et ONNX Runtime ont des dépendances natives et des besoins de cycle de vie qu'il faut distribuer avec l'Agent |
| Installation manuelle rejetée | Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation |
**Conséquence** : L'Agent est distribué exclusivement via `eltruncho/heimdall-agent` sur Docker Hub.
Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par `docker pull` + redémarrage.
### D6 — SFU (MediaMTX) différé à v2
### D6 — Chemin live-view livré : relay Agent vers MediaMTX, lecture WHEP/WebRTC
| Choix | Raison |
|---|---|
| **P2P uniquement en v1** (1 viewer/caméra max) | Complexité de transition P2P→SFU sous-estimée |
| SFU repoussé à v2 | Renégociation SDP pendant flux actif = perte d'images, protocole non spécifié |
| **L'Agent publie le flux RTSP(S) vers MediaMTX; le navigateur lit par WHEP/WebRTC** | Ce chemin est implémenté dans le relay Agent et l'API/session Central. Il ne repose pas sur une PeerConnection SIPSorcery dans l'Agent. |
| La capacité et la connectivité restent à valider par environnement | Les limites de sessions, codecs, NAT/TURN et latence dépendent du déploiement; voir `docs/docker-compose.md` et l'issue #161 pour la validation externe. |
### D7 — CQRS avec MediatR in-process (pas de message broker)
@@ -73,6 +74,11 @@ Contrôleur → IMediator.Send(Command/Query) → [ValidationBehavior]
## PARTIE 1 : Architecture Globale
> **Schémas historiques (2026-07-16), non descriptifs du runtime actuel.** Les
> schémas de conteneurs et les diagrammes détaillés ci-dessous gardent la
> proposition d'origine; pour les composants livrés, suivre les liens d'état
> courant dans l'en-tête.
### 1.1 Vision
Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, multi-site.
@@ -85,11 +91,15 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
| **Privacy First** | IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud |
| **Multi-site** | 1 serveur Central + N Agents distants (sites physiques séparés) |
| **Clean Architecture / CQRS** | Domain → Application → Infrastructure → Api/Web |
| **Temps réel** | SignalR (5 hubs), WebRTC P2P < 500ms (LAN) |
| **Temps réel** | SignalR (5 hubs mappés : Config, Events, Monitoring, Notifications, Admin); vidéo en direct : Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC, sans seuil de latence revendiqué |
| **IA locale** | YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker |
### 1.3 Architecture Logique
> **Diagramme de conception historique (2026-07-16), pas le chemin vidéo livré.**
> Il représente l'ancienne proposition SIPSorcery/P2P. Le chemin live actuel est
> résumé en D6 et détaillé dans le [guide live-view](docker-compose.md).
```
┌────────────────────────────────────────────────────────────────────────┐
│ HEIMDALL CENTRAL (1 container) │
@@ -126,6 +136,10 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
### 1.4 Conteneurs Docker
> **Exemple de topologie historique, non équivalent aux Compose actuels.**
> Coturn n'est pas obligatoire pour chaque installation; voir
> [les services Compose maintenus](docker-compose.md).
```yaml
services:
heimdall-central: # Api + Web + Workers fusionnés (1 conteneur)
@@ -144,6 +158,11 @@ services:
### 2.1 Définitions
> **Schéma de conception historique (2026-07-16).** Les champs de
> notification ci-dessous, dont `GotifyEnabled` et `NotificationTemplate`, ne
> sont pas l’inventaire du modèle livré. Voir le [guide actuel des
> notifications](notifications.md) et le [modèle d’identité courant](auth-roles.md).
```
Site Agent Camera
├── Id (Guid) PK ├── Id (Guid) PK ├── Id (Guid) PK
@@ -288,12 +307,15 @@ CREATE INDEX idx_license_plate ON license_plates USING GIN
### 3.1 Problème : Objets Stationnaires
> **Estimation théorique historique**, pas une mesure ni une description des
> canaux livrés.
**Sans dédoublonnage** : une personne immobile 10 minutes génère :
- 3000 snapshots (200ms × 600s)
- 3000 inférences YOLOv8 nano
- 3000 analyses IA (ONNX local ou via broker)
- 3000 événements en base
- 3000 notifications (email + gotify + in-app)
- 3000 notifications dans ce scénario théorique
**Solution** : Architecture de dédoublonnage à 4 niveaux.
@@ -440,6 +462,10 @@ public class CameraDetectionProfile
## PARTIE 4 : Authentification, Rôles et Sécurité
> **Conception historique.** Les exemples ci-dessous incluent un `StreamingHub`
> proposé qui n'est pas mappé. Les hubs et routes actuels sont listés dans
> [le guide SignalR](signalr-usage.md).
### 4.1 Architecture Auth
```
@@ -571,7 +597,10 @@ Agent se connecte à SignalR avec API Key
---
## PARTIE 5 : SignalR — 5 Hubs Détaillés
## PARTIE 5 : Conception SignalR historique — 5 hubs projetés
> Cette proposition datée inclut `/hubs/streaming`, qui n'est pas livré. Voir
> [les cinq routes actuellement mappées](signalr-usage.md).
### 5.1 Hubs
@@ -648,7 +677,12 @@ builder.Services.AddSignalR()
---
## PARTIE 6 : WebRTC et Pipeline Vidéo
## PARTIE 6 : Conception historique P2P/SIPSorcery — remplacée pour le live view
> Les sections ci-dessous conservent l'ancienne proposition P2P/SIPSorcery et
> ses objectifs de latence, pas le comportement livré. Le chemin actuel est
> Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC; voir le
> [guide Compose](docker-compose.md) et le [skill live-view](../skills/webrtc-live/SKILL.md).
### 6.1 Stack
@@ -815,6 +849,10 @@ await storageProvider.DeleteBatchAsync(storagePaths, ct);
### 7.4 Hangfire Configuration
> **Exemple de queues historique.** Les queues `email`/`gotify` du bloc
> suivant ne décrivent pas les jobs actuels; voir le [guide Hangfire](hangfire-usage.md)
> et le [guide des notifications livrées](notifications.md).
```csharp
// Central — with schema isolation
builder.Services.AddHangfire(config =>
@@ -826,7 +864,7 @@ builder.Services.AddHangfire(config =>
});
});
// Queue isolation
// Queue isolation (conception historique)
[Queue("email")]
public class SendNotificationEmailJob { ... }
@@ -846,6 +884,10 @@ builder.Services.AddHangfireServer(options =>
### 7.5 Jobs Hangfire — Tous
> **Inventaire historique (2026-07-16), pas la liste des jobs actuellement
> enregistrés.** Consulter le [guide Hangfire actuel](hangfire-usage.md) pour
> les jobs et queues livrés.
**Central (PostgreSQL)**
| Job | Schedule | Queue | Description |
@@ -872,66 +914,19 @@ builder.Services.AddHangfireServer(options =>
## PARTIE 8 : Notifications
### 8.1 Canaux
> **Conception historique non livrée.** Les canaux Gotify, l’éditeur de
> templates Scriban et les événements de ces tableaux ne décrivent pas le
> produit actuel. Pour les canaux, réglages et jobs livrés, voir
> [Notifications](notifications.md).
| Canal | Usage | Priorité | Queue Hangfire |
|---|---|---|---|
| **Email (SMTP)** | Importants + résumés | P0 | `email` |
| **Gotify** | Alertes temps réel | P0 | `gotify` |
| **In-app (SignalR)** | Badge UI | P0 | Direct (pas Hangfire) |
### 8.2 Types d'Événements Notifiables
| EventType | Email | Gotify | In-App | Cooldown (secondes) |
|---|---|---|---|---|
| `PersonDetected` | ✅ | ✅ | ✅ | 30 |
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | 300 (5 min) |
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | 30 |
| `VehicleDetected` | ✅ | ✅ | ✅ | 60 |
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | 60 |
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | 10 |
| `CameraOffline` | ✅ | ✅ | ✅ | 600 (10 min) |
| `CameraOnline` | 🟡 | 🟡 | ✅ | 600 |
| `DailySummary` | ✅ | ❌ | ❌ | N/A |
| `WeeklySummary` | ✅ | ❌ | ❌ | N/A |
### 8.3 Rate Limiting Notifications
```csharp
public class NotificationRateLimiter
{
private readonly IMemoryCache _cache;
public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId)
{
var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}";
var count = _cache.GetOrCreate(key, entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(1);
return 0;
});
if (count >= 20) return false; // Max 20 events/min/camera/type
_cache.Set(key, count + 1, TimeSpan.FromMinutes(1));
return true;
}
}
```
### 8.4 Templates
- Moteur : Scriban (Markdown → HTML pour email)
- Stockés en DB (table `NotificationTemplate`)
- Éditables depuis l'UI Admin
- Fallback : fr → en → template par défaut hardcodé
- Signature : `[Heimdall]` dans le sujet
Le détail historique de cette partie a été retiré pour éviter de confondre
les propositions de 2026-07-16 avec les fonctions livrées.
---
## PARTIE 9 : Application web installable (PWA)
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans la première étape.
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. À ce jour, le manifeste, le worker borné et la page statique hors connexion sont livrés; Web Push et la consultation métier hors ligne restent à implémenter. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans le socle actuel.
Spécification actuelle : [audit et plan PWA](pwa.md).
@@ -939,8 +934,15 @@ Spécification actuelle : [audit et plan PWA](pwa.md).
## PARTIE 10 : Plan d'Implémentation Optimisé
> **Plan historique daté du 2026-07-16, pas un état d'avancement.** Les phases,
> livrables et scénarios vidéo ci-dessous décrivent la proposition d'origine;
> consulter les guides actuels liés en tête avant d'inférer ce qui est livré.
### 10.1 7 Étapes Incrémentales
> Chaque phase et son encadré « Fonctionnel à la fin » ci-dessous décrivent le
> plan du 2026-07-16, pas un état vérifié de l'implémentation actuelle.
Le plan est structuré en **7 étapes**, chacune produisant un logiciel fonctionnel et testable.
| Étape | Phases | Nom | Livrable |
@@ -1011,6 +1013,9 @@ Phase 3 — CI/CD
└──────────────────────────────────────────────────────────────────┘
Phase 4 — Domain Model (entités multi-site uniquement)
> **Inventaire du plan historique.** `NotificationTemplate` existe comme
> entité, mais cette entrée ne décrit pas un éditeur livré ni une intégration
> Gotify; voir le [guide des notifications actuelles](notifications.md).
├── Entités CŒUR : Site, Agent (avec ApiKeyHash, ApiKeyPrefix)
├── Entités AUTH : User, Role (Identity), UserSite, ApiKey, AuditLog
├── Entités MÉTIER (définies mais migrations seules, pas de logique) :
@@ -1390,6 +1395,10 @@ Phase 13 — API Caméras + ONVIF
│ • Soft delete : caméra dans la corbeille, pas vraiment supprimée
│ • Découverte ONVIF réseau : scan automatique des caméras
> **Phases 14 et 15 ci-dessous : plan historique, pas état de livraison.**
> Le `StreamingHub` et le signaling SDP/ICE décrits ici ne sont pas mappés;
> voir les [cinq routes SignalR actuelles](signalr-usage.md).
Phase 14 — SignalR Hubs (temps réel)
├── 5 hubs : Events, Streaming, Monitoring, Notifications, Admin
├── EventsHub :
@@ -1448,6 +1457,9 @@ Phase 14 — SignalR Hubs (temps réel)
│ • User voit UNIQUEMENT ses sites assignés
│ • Le signaling WebRTC est prêt pour l'Étape 3
> **Scénarios de phase historiques, pas des contrats ou preuves d'exécution.**
> Les exemples de `StreamingHub`, SDP/ICE, groupes et latence ne décrivent pas
> les routes ni le transport vidéo livrés.
═══════════════════════════════════════════════════════════════════════
ÉTAPE 3 — VIDÉO + IA
@@ -1455,6 +1467,10 @@ Phase 14 — SignalR Hubs (temps réel)
═══════════════════════════════════════════════════════════════════════
Phase 15 — Agent Vidéo (capture + streaming)
> **Scénario vidéo historique, non implémenté tel que décrit.** P2P SIPSorcery,
> Coturn obligatoire et objectifs de latence ci-dessous ne sont pas des
> comportements ni des mesures livrés. Le chemin actuel est décrit en D6.
├── FFmpeg capture (passthrough H264, zerolatency)
│ ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0 \
│ -i rtsp://... -g 1 -tune zerolatency \
@@ -1710,68 +1726,14 @@ Phase 17 — API Events + Persons + Vehicles
│ • Tout est filtré par site-scope (User voit ses sites)
│ • Données accessibles via API pour l'UI (Étape 5)
Phase 18 — Notifications
├── SendNotificationEmailJob (SMTP, queue=email, retry 3x)
├── SendNotificationGotifyJob (queue=gotify)
├── NotificationRateLimiter (IMemoryCache, max 20 events/min/camera)
├── DetectionCooldownService (cooldown par type d'événement)
├── Scriban templates (DB + fallback hardcodé fr → en)
├── Hiérarchie des notifications :
│ ├── "PersonDetected" → Email + Gotify (si configuré)
│ ├── "UnknownPerson" → Email + Gotify + In-app (badge rouge)
│ ├── "VehicleDetected" → Email (si config) + Gotify
│ ├── "CameraOffline" → Email + Gotify (alerte admin)
│ └── "MotionDetected" → SILENCIEUX (in-app sans notif)
├── Verify: notifications flows green
│
✅ Fonctionnel à la fin de cette phase :
│
│ ┌─ SCÉNARIO NOTIFICATION ──────────────────────────────────────┐
│ │ │
│ │ 1. Personne détectée devant la caméra "Entrée" │
│ │ → Événement créé (Phase 16) │
│ │ │
│ │ 2. Central envoie SendNotificationJob à Hangfire │
│ │ → Queue "email" : SendNotificationEmailJob │
│ │ → Queue "gotify" : SendNotificationGotifyJob │
│ │ │
│ │ 3. SendNotificationEmailJob : │
│ │ → Render template Scriban : "Personne détectée" │
│ │ → Sujet : "[Heimdall] Personne détectée — Entrée" │
│ │ → Corps : snapshot incluse (embed) + heure + lieu │
│ │ → SMTP : envoi à tous les users configurés │
│ │ │
│ │ 4. SendNotificationGotifyJob : │
│ │ → POST Gotify API : "Personne détectée - Entrée" │
│ │ → Priorité : 5 (haute) │
│ │ │
│ │ 5. SignalR NotificationsHub envoie NewNotification │
│ │ → Groupe "notif-{userId}" │
│ │ → Badge dans l'UI : "3 notifications non lues" │
│ │ │
│ │ 6. RateLimiter : max 20 notifs/min/camera │
│ │ → Si seuil atteint → pas de nouvelle notification │
│ │ → Log "Rate limit atteint pour camera guid-cam-1" │
│ │ │
│ └──────────────────────────────────────────────────────────────┘
│
│ ┌─ CONFIGURER SES NOTIFICATIONS ───────────────────────────────┐
│ │ PUT /api/auth/profile │
│ │ { │
│ │ "notificationConfig": { │
│ │ "emailEnabled": true, │
│ │ "gotifyEnabled": true, │
│ │ "subscribedEvents": ["personDetected", "unknownPerson", │
│ │ "vehicleDetected", "cameraOffline"],│
│ │ "dailyDigest": true │
│ │ } │
│ │ } │
│ └──────────────────────────────────────────────────────────────┘
│
│ • 3 canaux : Email, Gotify, In-app (SignalR)
│ • Rate limiting : pas de spam même en rafale
│ • Templates personnalisables par l'Admin
│ • Chaque user choisit ses types d'événements
> **Phase 18 — scénario historique (non état livré).** La conception initiale
> Gotify/Scriban ci-dessous a été retirée; voir [l’état courant des
> notifications](notifications.md).
Phase 18 — Notifications (historique)
> Détails de cette proposition retirés : ils ne décrivent pas les services,
> queues ni contrats actuellement livrés.
Phase 19 — Jobs Métier (retention, cleanup)
├── RetentionCheckJob (quotidien 3h, queue=maintenance)
@@ -1918,6 +1880,11 @@ Phase 21 — Blazor UI Dashboard + Sites
│ └──────────────────────────────────────────────────────────────┘
Phase 22 — Blazor UI Events + Persons + Live
> **Maquette de conception historique, pas le routage ou les mesures actuels.**
> La vidéo est intégrée à la page détail caméra; les estimations de latence et
> le plafond P2P ci-dessous n'ont pas été validés et ne décrivent pas le relay
> MediaMTX livré.
├── Events list (Route: /events)
│ ├── Table paginée (50/page) avec filtres :
│ │ Site (MudSelect), Type (MudSelect), Date (MudDateRangePicker)
@@ -1942,6 +1909,10 @@ Phase 22 — Blazor UI Events + Persons + Live
│ └── Timeline : barre des 30 dernières minutes
├── Verify: Playwright events+live green
│
> **Maquette illustrative historique.** La route, les contrôles qualité,
> snapshots/timeline, reconnexion et chiffres de latence ci-dessous ne sont
> pas des affirmations sur l'UI ou les performances livrées.
✅ Fonctionnel à la fin de cette phase :
│
│ ┌─ LIVE VIDÉO ─────────────────────────────────────────────────┐
@@ -1968,6 +1939,11 @@ Phase 22 — Blazor UI Events + Persons + Live
│ └──────────────────────────────────────────────────────────────┘
Phase 23 — Blazor UI Admin
> **Maquette historique, pas l’interface livrée.** Le dashboard/configuration
> consolidés et le réglage Gotify ci-dessous ne sont pas des routes ou écrans
> actuels. Consulter [`ui-pages.md`](ui-pages.md), [`auth-roles.md`](auth-roles.md)
> et [les réglages de notification livrés](notifications.md).
├── Users management (tab Utilisateurs)
│ ├── Liste des users avec rôle, email, 2FA status
│ ├── [Modifier le rôle], [Reset 2FA], [Supprimer]
@@ -2011,6 +1987,11 @@ Phase 23 — Blazor UI Admin
═══════════════════════════════════════════════════════════════════════
Phase 24 — Production Hardening
> **Critères et scénarios historiques, pas des résultats d'acceptance.** Les
> capacités, objectifs k6, seuils de latence, exemples de backup et assertions
> « fonctionnel » ci-dessous ne prouvent pas l'implémentation actuelle, un
> déploiement, ni un résultat de test.
├── Rate limiting (AspNetCoreRateLimit)
│ ├── Auth : 5 tentatives/15min par IP
│ ├── API : 100 requêtes/min par client
@@ -2042,6 +2023,10 @@ Phase 24 — Production Hardening
│ └── Pas de perte de snapshots sous charge normale
├── Verify: k6 green, backup restore test OK
│
> **Résultats attendus de conception, jamais preuve de test/déploiement.** Les
> valeurs k6 ci-dessus sont des objectifs; le scénario backup ci-dessous
> précède le client réellement décrit dans `docker/backup/README.md`.
✅ Fonctionnel à la fin de cette phase :
│
│ ┌─ HEALTH CHECKS ──────────────────────────────────────────────┐
@@ -2063,6 +2048,9 @@ Phase 24 — Production Hardening
│ │ "message": "Analyse IA unavailable"} │
│ └──────────────────────────────────────────────────────────────┘
│
> **Exemple de backup historique, pas procédure actuelle ni résultat de restore.**
> Voir le [guide backup livré](../docker/backup/README.md).
│ ┌─ BACKUP ─────────────────────────────────────────────────────┐
│ │ Quotidien 2h : pg_dump → RustFS backup/heimdall_YYYY-MM-DD.sql.gz │
│ │ Hebdomadaire dimanche 3h : mc mirror → backup/ (versionné) │
@@ -2075,6 +2063,9 @@ Phase 24 — Production Hardening
│ │ 5. Vérifier les sites, agents, events toujours présents │
│ └──────────────────────────────────────────────────────────────┘
│
> **Objectifs de charge non mesurés et non validés.** Aucun seuil ci-dessous
> n'est un SLO ou un résultat de production.
│ ┌─ LOAD TEST (k6) ─────────────────────────────────────────────┐
│ │ objectif : 10 agents, 50 caméras, 20 viewers simultanés │
│ │ │
@@ -2133,6 +2124,10 @@ CPU; l'inférence GPU nécessite encore une image et un runtime dédiés.
## PARTIE 12 : Tests
> **Scénarios de test historiques (2026-07-16), pas résultats ni couverture
> actuelle.** La référence `gotify` ci-dessous décrit une ancienne conception
> de queue; voir [les canaux livrés](notifications.md) et [les jobs actuels](hangfire-usage.md).
### 12.1 Stack de Test
| Niveau | Technologie | Couverture |
@@ -2233,10 +2228,13 @@ AnalysisWorker: concurrent requests from multiple cameras
---
## PARTIE 14 : Correctifs Applicables aux Documents Sources
## PARTIE 14 : Historique de consolidation des documents sources
Les documents suivants contiennent des informations obsolètes ou erronées.
**Ce document (`MASTER_SPECIFICATION.md`) fait foi.**
Cette section conserve l'état éditorial de la consolidation du 2026-07-16.
Le tableau décrit les observations faites à cette date sur les documents sources;
il ne constitue pas un inventaire de leurs défauts actuels ni une liste de
travail ouverte. Pour le comportement livré, utiliser les sources courantes
liées dans l'en-tête de ce document.
| Document source | Statut | Corrections nécessaires |
|---|---|---|
@@ -2253,6 +2251,11 @@ Les documents suivants contiennent des informations obsolètes ou erronées.
## Annexe A : Résumé des 36 Issues Critiques Résolues
> **Annexe historique de la baseline 2026-07-16**; ses résolutions et noms de
> composants ne constituent pas une validation du runtime actuel. Pour les
> notifications et queues livrées, voir le [guide notifications](notifications.md)
> et le [guide Hangfire](hangfire-usage.md).
| # | Issue | Source | Résolution |
|---|---|---|---|
| C2 | Agent Registration ne retourne pas d'API Key | council-agent | ApiKey ajoutée à la réponse |
+15 -14
View File
@@ -1,7 +1,8 @@
# Heimdall — Documentation
Bienvenue dans la documentation technique de Heimdall, plateforme de
vidéosurveillance IA locale, multi-site, auto-hébergée.
vidéosurveillance multi-site auto-hébergée. L'analyse ONNX est locale par
défaut sur l'Agent; un mode broker distant est configurable.
---
@@ -11,7 +12,7 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|---|---|
| **Vue d'ensemble** du projet | `docs/specs.md` (Vision, Architecture, Stack) |
| **État réel et travaux restants** | [Issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues) |
| **Plan d'implémentation historique** (MVP juillet 2026) | `docs/implementation.md` |
| **Archive historique de l'implémentation** (MVP juillet 2026) | `docs/implementation.md` |
| **Maquettes UI Blazor** détaillées | `docs/ui-pages.md` |
| **Application web installable (PWA)** | [Audit et plan PWA](pwa.md) |
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) |
@@ -20,25 +21,25 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
| Domaine | Document | Contenu |
|---|---|---|
| **Sites & Agents** | `docs/specs.md` (§11-12) | Sites, tokens, registration, heartbeat, bootstrap |
| **Caméras & IA** | `docs/specs.md` (§14-19) | ONVIF, Imou, FFmpeg, GPU, AI Pipeline, détection |
| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | Architecture cible; consulter l'audit pour l'état livré |
| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | Stockage cible; le pipeline d'enregistrement vidéo reste à raccorder |
| **Événements** | `docs/specs.md` (§16-19) | Personnes, véhicules, plaques, notifications |
| **Notifications** | `docs/notifications.md` | Email SMTP, Gotify, templates Markdown i18n |
| **Sites & Agents** | [`docs/specs.md`](specs.md) (§5), [`docs/auth-roles.md`](auth-roles.md) | Création du site, enrôlement et heartbeat Agent |
| **Caméras & IA** | [`docs/specs.md`](specs.md) (§5), [`docs/gpu-runtime.md`](gpu-runtime.md) | Découverte, analyse ONNX locale par défaut, CUDA NVIDIA optionnel et état de validation matérielle |
| **Streaming live** | [`docs/specs.md`](specs.md) (§5), [`docs/ui-pages.md`](ui-pages.md), [`docs/signalr-usage.md`](signalr-usage.md) | Relay Agent vers MediaMTX en RTSP(S), lecture WHEP/WebRTC; validation caméra/réseau réelle suivie dans #161 et #341 |
| **Enregistrements** | [`docs/ui-pages.md`](ui-pages.md), API `RecordingsController` | L’Agent segmente le flux principal, envoie les segments terminés au Central, qui les conserve dans le stockage configuré; lecture protégée dans la fiche caméra. Pas de validation caméra réelle revendiquée |
| **Événements** | [`docs/specs.md`](specs.md) (§4), [`docs/ui-pages.md`](ui-pages.md), [`docs/notifications.md`](notifications.md) | Modèle d’événement caméra, pages événements et notifications |
| **Notifications** | `docs/notifications.md` | Email SMTP, ntfy, centre in-app et préférences utilisateur |
## 🔧 Domaines techniques
| Domaine | Document | Contenu |
|---|---|---|
| **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope |
| **IA (ONNX)** | `docs/specs.md` | Architecture cible; consulter l'audit pour distinguer les capacités livrées |
| **IA (ONNX)** | [`docs/gpu-runtime.md`](gpu-runtime.md), [`docs/specs.md`](specs.md) (§5) | CPU par défaut, image CUDA NVIDIA optionnelle, limites d’inventaire et validation matérielle |
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Configuration actuelle et jobs présents; vérifier l'état des parcours dans l'audit |
| **Métriques et alertes** | [Métriques Prometheus](metrics.md) | Endpoints Web/Agent et signaux de santé exportés |
| **SignalR (temps réel)** | `docs/signalr-usage.md` | Hubs et contrats documentés; état du streaming live dans l'audit |
| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose |
| **Déploiement Docker** | [`docs/specs.md`](specs.md) (§6), [`docs/docker-compose.md`](docker-compose.md) | Services requis et optionnels; l’inférence GPU NVIDIA est une variante Agent optionnelle |
| **Docker Compose** | [Déploiement séparé](docker-compose.md) | Central + PostgreSQL requis; Agent et logiciels optionnels séparés |
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Profils facultatifs; l'inférence ONNX publiée reste CPU |
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Image CPU par défaut; image NVIDIA/CUDA amd64 optionnelle publiée avec manifeste signé; exécution CUDA physique à valider sur matériel |
## 📐 Structure du projet
@@ -65,9 +66,9 @@ Heimdall/
| `implementation.md` | Plan historique du MVP (juillet 2026); statuts non représentatifs de l'état actuel |
| `docker-compose.md` | Déploiement Central, Agents autonomes et logiciels facultatifs |
| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états |
| `pwa.md` | Audit PWA du serveur Blazor, architecture cible et plan de réalisation |
| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility |
| `notifications.md` | Email (SMTP), Gotify, templates Markdown i18n, hangfile queue |
| `pwa.md` | État livré de la PWA, limites hors ligne et feuille de route Web Push |
| `auth-roles.md` | Auth : rôles Admin/Supervisor/Viewer, permissions et accès par site/caméra |
| `notifications.md` | Canaux SMTP/ntfy, centre in-app, préférences et résumés planifiés |
| `hangfire-usage.md` | Description des jobs Hangfire présents au Central et à l’Agent |
| `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites |
| `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées |
+5 -3
View File
@@ -30,16 +30,18 @@ Central affiche une commande Bash ou PowerShell qui télécharge et exécute l
```sh
sudo bash install/install-agent.sh \
--central-url https://central.example.org \
--site-token 'JETON_DE_SITE' \
--central-url-file /chemin/protege/central-url \
--site-token-file /chemin/protege/site-token \
--update-public-key /chemin/local/agent-release-public.pem
```
Les deux fichiers d’enrôlement doivent être réguliers, non-symlinks et en mode `0600` ou plus restrictif; placez-les dans un répertoire privé. N’inscrivez jamais l’URL ou le jeton dans les arguments de processus.
L’installateur Linux est servi par Central avec son superviseur. Il installe la release sous `/opt/heimdall/agent/releases/`; le service systemd utilise le lien `current`. Après téléchargement vérifié, 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.
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM installent le dépôt d’image avec le tag `latest`; Compose et `docker run` vérifient le registre au démarrage. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM épinglent l’image CPU ou GPU au digest vérifié du manifeste signé (`repository@sha256:digest`). Compose et `docker run` récupèrent cette référence immuable au démarrage (`pull_policy: always` et `--pull always`). Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
## Rotation
+120 -211
View File
@@ -8,61 +8,68 @@
---
## 1. Types d'utilisateurs
## 1. Rôles disponibles
### Admin
Heimdall définit trois rôles (`Admin`, `Supervisor`, `Viewer`), listés dans
[`AppRoles.All`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs) et
[`UserRole`](../src/Heimdall.Domain/Enums/UserRole.cs). Les permissions par
défaut viennent de [`AppPermissions.RolePermissions`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs); les
permissions des rôles non-Admin peuvent être ajustées par un administrateur.
Le rôle détermine les capacités, tandis que l’accès effectif aux sites et aux
caméras est vérifié séparément par les services d’accès aux ressources.
| Propriété | Valeur |
| Rôle | Capacités par défaut |
|---|---|
| Accès | **Tous les sites** sans restriction |
| Configuration | Peut tout configurer (sites, caméras, IA, stockage, notifications) |
| Administration | Gère les users, les rôles, les clés API, les jobs Hangfire |
| Visibilité UI | **Toutes les pages** (y compris Admin) |
| Permissions | Toutes les permissions automatiquement |
| Sites | Non restreint — voit tous les sites, toutes les caméras |
| **Admin** | Toutes les permissions, y compris l’administration globale. |
| **Supervisor** | Lecture des sites, caméras, événements, personnes et véhicules; live, enregistrement et snapshots caméra; écriture caméra/personne/véhicule. Aucun droit `Admin.*` par défaut. |
| **Viewer** | Lecture des sites, caméras, live, événements, personnes et véhicules. Aucun droit d’écriture, d’enregistrement, de snapshot ni `Admin.*` par défaut. |
### User
| Propriété | Valeur |
|---|---|
| Accès | **1 ou N sites** assignés par l'Admin |
| Configuration | Aucune — lecture seule ou actions limitées |
| Administration | Aucun accès |
| Visibilité UI | Pages selon ses permissions + uniquement ses sites |
| Permissions | Définies par rôle + site |
| Scope | Restreint aux sites qui lui sont assignés |
Les rôles Supervisor et Viewer n’impliquent pas l’accès à tous les sites : les
endpoints et handlers appliquent les affectations et contrôles de ressource via
[`ICameraAccessService`](../src/Heimdall.Application/Services/ICameraAccessService.cs).
Voir la matrice de permissions et la section sur `ICameraAccessService` ci-dessous.
---
## 2. Modèle de données
```csharp
// IdentityUser de base — pas de modification
public class User : IdentityUser<Guid>
// Infrastructure/Identity/IdentityAppUser.cs
// La classe Identity et ses dépendances restent dans Infrastructure.
public sealed class IdentityAppUser : IdentityUser<Guid>
{
public string DisplayName { get; set; } = string.Empty;
public ThemeMode Theme { get; set; } = ThemeMode.Auto;
public string? Theme { get; set; } = "Auto";
public string Language { get; set; } = "fr";
public bool TwoFactorEnabled { get; set; } = false; // TOTP
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool MustChangePassword { get; set; }
}
// Relation User → Sites (N-N)
// Domain/Entities/UserSite.cs — aucune navigation vers le type Identity.
public class UserSite
{
public Guid UserId { get; set; }
public User User { get; set; } = null!;
public Guid UserId { get; private set; }
public Guid SiteId { get; private set; }
public Site Site { get; private set; } = null!;
public Guid SiteId { get; set; }
public Site Site { get; set; } = null!;
private UserSite() { } // EF Core
public UserSite(Guid userId, Guid siteId)
{
UserId = userId;
SiteId = siteId;
}
}
// Infrastructure/Data/Configurations/UserSiteConfiguration.cs — relation seulement.
builder.HasOne<IdentityAppUser>().WithMany().HasForeignKey(us => us.UserId);
// Rôles prédéfinis
public static class AppRoles
{
public const string Admin = "Admin";
public const string Superviseur = "Superviseur"; // peut voir + agir
public const string Viewer = "Viewer"; // lecture seule
public const string Supervisor = "Supervisor"; // libellé UI français : Superviseur
public const string Viewer = "Viewer"; // lecture seule
}
```
@@ -91,19 +98,20 @@ public static class AppPermissions
public const string EventRead = "Event.Read";
public const string PersonRead = "Person.Read";
public const string PersonWrite = "Person.Write";
public const string VehicleRead = "Vehicle.Read";
public const string VehicleWrite = "Vehicle.Write";
// Administration
public const string AdminManage = "Administration.Manage";
public const string AdminUsers = "Administration.Users";
public const string AdminApiKeys = "Administration.ApiKeys";
public const string AdminJobs = "Administration.Jobs"; // Hangfire dashboard
public const string AdminNotifications = "Administration.Notifications"; // templates
public const string AdminManage = "Admin.Manage";
public const string AdminUsers = "Admin.Users";
public const string AdminApiKeys = "Admin.ApiKeys";
public const string AdminJobs = "Admin.Jobs"; // Hangfire dashboard
}
```
### Mapping Rôle → Permissions
| Permission | Admin | Superviseur | Viewer |
| Permission | Admin | Supervisor | Viewer |
|---|---|---|---|
| Site.Read | ✅ | ✅ | ✅ |
| Site.Write | ✅ | ❌ | ❌ |
@@ -116,11 +124,12 @@ public static class AppPermissions
| Event.Read | ✅ | ✅ | ✅ |
| Person.Read | ✅ | ✅ | ✅ |
| Person.Write | ✅ | ✅ | ❌ |
| Vehicle.Read | ✅ | ✅ | ✅ |
| Vehicle.Write | ✅ | ✅ | ❌ |
| Admin.Manage | ✅ | ❌ | ❌ |
| Admin.Users | ✅ | ❌ | ❌ |
| Admin.ApiKeys | ✅ | ❌ | ❌ |
| Admin.Jobs | ✅ | ❌ | ❌ |
| Admin.Notifications | ✅ | ❌ | ❌ |
---
@@ -129,68 +138,30 @@ public static class AppPermissions
### Enregistrement
```csharp
// Program.cs
builder.Services.AddAuthorization(options =>
// Heimdall.Web/Program.cs — ConfigureAuthorizationPolicies
builder.Services.AddAuthorizationCore(options =>
{
// Permission directe
foreach (var permission in typeof(AppPermissions).GetFields(
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(f => f.IsLiteral && !f.IsInitOnly)
.Select(f => f.GetRawConstantValue() as string)
.Where(v => v != null))
{
options.AddPolicy(permission!, policy =>
var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct();
foreach (var permission in allPermissions)
options.AddPolicy(permission, policy =>
policy.RequireClaim("permission", permission));
}
// Admin a toutes les permissions automatiquement
options.AddPolicy("AdminOnly", policy =>
// Legacy role-based policy retained for administrative endpoints.
options.AddPolicy("AdminUsers", policy =>
policy.RequireRole(AppRoles.Admin));
});
```
### Vérification site-scope
### Vérification site et caméra
Pour les Users non-Admin, chaque requête sur un site doit vérifier
que l'User a accès à ce site :
```csharp
public class SiteAuthorizationHandler : AuthorizationHandler<SiteRequirement, Guid>
{
private readonly ApplicationDbContext _db;
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,
SiteRequirement requirement,
Guid siteId)
{
if (context.User.IsInRole(AppRoles.Admin))
{
context.Succeed(requirement);
return;
}
var userId = context.User.GetUserId();
var hasAccess = await _db.UserSites
.AnyAsync(us => us.UserId == userId && us.SiteId == siteId);
if (hasAccess) context.Succeed(requirement);
}
}
public record SiteRequirement : IAuthorizationRequirement;
// Usage dans un endpoint :
[HttpGet("/api/sites/{siteId}/cameras")]
public async Task<IActionResult> GetCameras(
Guid siteId,
[FromServices] IAuthorizationService auth)
{
var authResult = await auth.AuthorizeAsync(User, siteId, "SiteAccess");
if (!authResult.Succeeded) return Forbid();
// ...
}
```
Les endpoints déclarent une policy comme `Camera.Read`, puis transmettent
l'identité utilisateur aux queries ou à `ResourceAccess` pour filtrer la
ressource demandée. Par exemple, `GET /api/cameras/by-site/{siteId}` est mappé
par `CamerasController.ListBySite`; il crée un `GetCamerasBySiteQuery` avec le
`userId`. Le handler appelle `ICameraAccessService` et ne retourne que les
caméras auxquelles cet utilisateur a accès. Il n'existe pas de route
`/api/sites/{siteId}/cameras` dans ce contrôleur ni de handler générique
`SiteAuthorizationHandler`.
---
@@ -204,147 +175,85 @@ public async Task<IActionResult> GetCameras(
| Dashboard | `/` | ✅ Tous sites | ✅ Ses sites | ✅ Ses sites |
| Sites liste | `/sites` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
| Site détail | `/sites/{id}` | ✅ | ✅ (si assigné) | ✅ (si assigné) |
| Caméra live | `/cameras/{id}/live` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
| Détail caméra (live-view intégré) | `/cameras/{id}` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
| Events | `/events` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
| Persons | `/persons` | ✅ | ✅ | ✅ |
| Admin | `/admin` | ✅ | ❌ Redirection | ❌ Redirection |
| Admin Users | `/admin/users` | ✅ | ❌ | ❌ |
| Admin API Keys | `/admin/api-keys` | ✅ | ❌ | ❌ |
| Admin Hangfire | `/admin/jobs` | ✅ | ❌ | ❌ |
| Admin Notifications | `/admin/notifications` | ✅ | ❌ | ❌ |
| Paramètres (dont notifications) | `/settings` | ✅ Admin.Manage | ❌ | ❌ |
| Utilisateurs | `/users` | ✅ Admin.Users | ❌ | ❌ |
| Rôles | `/admin/roles` | ✅ Admin.Users | ❌ | ❌ |
| Groupes | `/admin/groups` | ✅ Admin.Users | ❌ | ❌ |
| Agents | `/admin/agents` | ✅ Admin.Users | ❌ | ❌ |
| Clés API | `/admin/api-keys` | ✅ Admin.ApiKeys | ❌ | ❌ |
| Claims | `/admin/claims` | ✅ Admin.Manage | ❌ | ❌ |
| Journaux d'audit | `/audit-logs` | ✅ Admin.Manage | ❌ | ❌ |
| Hangfire | `/hangfire` | ✅ Admin.Jobs | ❌ | ❌ |
La page détail caméra requiert une session authentifiée; les API de données et
de live-view appliquent `Camera.Read` et vérifient aussi l'accès effectif à la
caméra et à son site. La session live utilise
`POST /api/live-media/cameras/{cameraId}/session` et
`DELETE /api/live-media/cameras/{cameraId}/session/{sessionId}`. `Camera.Live`
reste dans le catalogue des permissions attribuées aux rôles, mais n'est pas la
policy appliquée à ces deux endpoints dans le contrôleur actuel.
### Implementation Blazor
```csharp
// Layout — masquer le menu Admin si pas Admin
@if (await AuthorizeService.HasPermissionAsync(AppPermissions.AdminManage))
// MainLayout — le groupe Administration apparaît avec l’une de ces permissions.
@if (Auth.HasPermission("Admin.Users") || Auth.HasPermission("Admin.Manage"))
{
<MudNavLink Href="/admin">⚙️ Administration</MudNavLink>
}
<MudText Typo="Typo.overline">Administration</MudText>
// Page Events — filtrer par site si User non-Admin
@code {
protected override async Task OnInitializedAsync()
@if (Auth.HasPermission("Admin.Users"))
{
if (await AuthorizeService.IsAdminAsync())
{
_sites = await SiteService.GetAllAsync();
}
else
{
_sites = await SiteService.GetMySitesAsync();
}
<MudNavLink Href="/users">Utilisateurs</MudNavLink>
<MudNavLink Href="/admin/groups">Groupes</MudNavLink>
<MudNavLink Href="/admin/roles">Rôles</MudNavLink>
}
@if (Auth.HasPermission("Admin.Manage"))
{
<MudNavLink Href="/admin/claims">Claims</MudNavLink>
}
}
```
### AuthorizeView
```razor
<AuthorizeView Policy="@AppPermissions.CameraLive">
<Authorized>
<button @onclick="StartLiveView">📷 Live</button>
</Authorized>
<NotAuthorized>
<MudTooltip Text="Accès non autorisé">
<button disabled>📷 Live</button>
</MudTooltip>
</NotAuthorized>
</AuthorizeView>
```
Les pages authentifiées sont enveloppées par `AuthorizeRouteView` dans
[`Routes.razor`](../src/Heimdall.Web/Components/Routes.razor); par exemple,
[`EventsPage.razor`](../src/Heimdall.Web/Components/Pages/EventsPage.razor)
déclare `[Authorize]` et charge les données via `HeimdallApiClient`. Les listes
et détails site/caméra ne filtrent pas les ressources selon un `IsAdminAsync`
local : les endpoints et queries appliquent les permissions puis
[`ResourceAccess`](../src/Heimdall.Web/Security/ResourceAccess.cs) et les
services d’accès aux ressources. Les endpoints de session live et la distinction
`Camera.Read`/`Camera.Live` sont décrits ci-dessus.
---
## 6. API — middleware de scope
## 6. API — filtrage des accès caméra
Un middleware applique le scope site automatiquement sur les requêtes API :
```csharp
public class SiteScopeMiddleware
{
public async Task InvokeAsync(HttpContext context)
{
if (context.User.Identity?.IsAuthenticated != true) return;
// Admin bypass
if (context.User.IsInRole(AppRoles.Admin))
{
context.Items["AllowedSiteIds"] = null; // all
return;
}
// User scope
var userId = context.User.GetUserId();
var siteIds = await _db.UserSites
.Where(us => us.UserId == userId)
.Select(us => us.SiteId)
.ToListAsync();
context.Items["AllowedSiteIds"] = siteIds;
}
}
```
Puis dans les repositories/query handlers, filtrer par `AllowedSiteIds` :
```csharp
public class GetEventsQueryHandler : IRequestHandler<GetEventsQuery, PagedResult<EventDto>>
{
public async Task<PagedResult<EventDto>> Handle(GetEventsQuery request, CancellationToken ct)
{
var query = _db.Events.AsQueryable();
// Scope site
if (request.AllowedSiteIds != null)
query = query.Where(e => request.AllowedSiteIds.Contains(e.SiteId));
// Si siteId spécifique fourni, vérifier qu'il est dans les allowed
if (request.SiteId.HasValue)
{
if (request.AllowedSiteIds != null &&
!request.AllowedSiteIds.Contains(request.SiteId.Value))
return new PagedResult<EventDto>(); // vide
query = query.Where(e => e.SiteId == request.SiteId.Value);
}
// ... pagination, filtres ...
}
}
```
Le runtime n'utilise pas de `SiteScopeMiddleware` global ni de liste
`AllowedSiteIds` placée dans `HttpContext`. Les endpoints appliquent leurs
policies d'authentification et les queries/services partagés résolvent les
droits de ressource à partir des accès courants. Pour les caméras, ce modèle
est centralisé dans `ICameraAccessService`/`CameraAccessService`; pour une
ressource précise, `ResourceAccess` effectue le contrôle demandé par le
contrôleur. Cela inclut les accès directs, les accès de site, les anciennes
affectations et les groupes caméra. Voir
[`skills/camera-access-groups/SKILL.md`](../skills/camera-access-groups/SKILL.md)
pour maintenir cette union sans la réimplémenter dans un contrôleur.
---
## 7. JWT Claims
```csharp
// À la génération du token JWT
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Name, user.DisplayName),
new(ClaimTypes.Role, role), // "Admin"
};
// Ajouter toutes les permissions du rôle
foreach (var permission in GetPermissionsForRole(role))
claims.Add(new Claim("permission", permission));
// Ajouter les sites accessibles (si non-Admin)
if (role != AppRoles.Admin)
{
var siteIds = await _db.UserSites
.Where(us => us.UserId == user.Id)
.Select(us => us.SiteId.ToString())
.ToListAsync();
foreach (var siteId in siteIds)
claims.Add(new Claim("site", siteId));
}
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddHours(8),
signingCredentials: credentials);
```
`JwtService.GenerateAccessToken` émet le sujet utilisateur, l'email, le nom,
les métadonnées de session, les rôles et les permissions. Il n'embarque pas de
liste d'IDs de site ou de caméra. Les droits de ressource restent résolus côté
serveur depuis les affectations courantes via `CameraAccessService` et
`ResourceAccess`, afin qu'une modification d'accès ne dépende pas d'une liste
de sites figée dans un JWT.
---
@@ -360,4 +269,4 @@ API respects site scope for non-admin users
JWT token contains permissions claims
UserSite assignment works correctly
Removing user from site revokes access immediately
```
```
+4 -4
View File
@@ -134,10 +134,10 @@ in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-ac
## Agent
Prefer the Compose shown in the Central UI's site installation panel. It uses
the Agent image's `latest` tag and includes the site token, public Central URL,
Agent name and release public key. Compose uses `pull_policy: always` so an
explicit `docker compose up` checks for the latest image. Save it as
Prefer the Compose shown in the Central UI's site installation panel. It pins
the CPU or GPU Agent image to the signed `repository@sha256:digest` and includes
the site token, public Central URL, Agent name and release public key. Compose
uses `pull_policy: always` to fetch that exact digest. Save it as
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
contains the pinned trust key; no separate PEM file is required. Updates
dispatched later by Central continue to verify the digest in the signed release
+10 -17
View File
@@ -15,7 +15,7 @@
│ │
│ Hangfire Server │
│ ├── Storage: PostgreSQL (Hangfire.PostgreSql) │
│ ├── Dashboard: /admin/jobs (authentifié, Admin only) │
│ ├── Dashboard: /hangfire (AdminJobs ou rôle Admin) │
│ └── Jobs: │
│ ├── RetentionCheck (Recurring, daily) │
│ ├── S3Cleanup (Recurring, daily) │
@@ -467,27 +467,20 @@ public class HangfireInitializer : IHostedService
Intégré à l'UI Admin, authentifié, pas exposé publiquement :
La route Central est mappée par `MapHangfireDashboard("/hangfire", ...)` dans
`src/Heimdall.Web/Program.cs`. `HangfireAdminAuthorizationFilter` autorise les
requêtes authentifiées portant `Admin.Jobs` ou le rôle `Admin`. Le dashboard
n'est pas mappé dans l'environnement `Testing`.
```csharp
// Heimdall.Api / Program.cs
app.UseHangfireDashboard("/admin/jobs", new DashboardOptions
// Heimdall.Web/Program.cs
app.MapHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization =
[
new HangfireAuthorizationFilter() // vérifie AppPermissions.AdminJobs
new HangfireAdminAuthorizationFilter()
],
StatsPollingInterval = 3000, // 3s
DisplayStorageConnectionString = false,
DashboardTitle = "Heimdall — Jobs",
});
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
return httpContext.User?.IsInRole(AppRoles.Admin) == true;
}
}
```
---
@@ -529,4 +522,4 @@ Hangfire dashboard is accessible only to Admin
Hangfire dashboard returns 403 for non-Admin
Agent jobs are recreated after agent restart
Agent InMemory storage does not persist across restarts
```
```
+33 -18
View File
@@ -1,9 +1,24 @@
# Heimdall — Plan d'implémentation
# Heimdall — Archive historique du plan d'implémentation (MVP, juillet 2026)
> **Document historique (MVP — juillet 2026).** Les statuts de phases ci-dessous ne reflètent pas l’état courant du dépôt. Pour le suivi à jour, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
> **Archive historique, pas une description de l’état actuel ni un guide à suivre.** Tout le contenu ci-dessous — architecture, chemins, statuts, commandes, endpoints, décomptes de tests et travaux « à faire » — reflète un instantané du MVP rédigé en juillet 2026. Ces informations ne décrivent pas le dépôt courant et ne constituent pas des instructions d’exploitation. Pour l’implémentation actuelle, utiliser les références ci-dessous; pour l’avancement et les travaux ouverts, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
**Principe :** On implémente d'abord le **plus simple et le plus important**.
La **vidéo live** arrive en dernier dans l'IHM.
## Références actuelles
| Sujet | Source actuelle |
|---|---|
| Installation Central, Compose et services optionnels | [Guide Docker Compose](docker-compose.md), [skill d’acceptation du déploiement](../skills/deployment-guide-acceptance/SKILL.md) |
| CI, builds et publication | [CI Gitea et images](gitea-builds.md), [signatures des mises à jour Agent](agent-release-signing.md) |
| Authentification, rôles et permissions | [Guide rôles et permissions](auth-roles.md) |
| Pages, routes et navigation UI | [Inventaire des pages UI](ui-pages.md) |
| Hubs SignalR et Hangfire | [Guide SignalR](signalr-usage.md), [Guide Hangfire](hangfire-usage.md) |
| Vidéo live, caméra et capacités livrées | [État produit courant](specs.md), [guide live view](../skills/webrtc-live/SKILL.md) |
| Notifications | [Guide notifications](notifications.md) |
| Métriques et alertes | [Guide Prometheus](metrics.md) |
| PWA et validation appareils/déploiement | [Audit PWA](pwa.md) |
| Backup et restauration | [Guide backup](../docker/backup/README.md) |
**Principe directeur du plan MVP de juillet 2026 (historique) :** implémenter d'abord le **plus simple et le plus important**.
La **vidéo live** était alors prévue en dernier dans l'IHM; cette priorité appartient au plan ancien et ne décrit pas la feuille de route actuelle.
## Statut d'avancement (MVP — Juillet 2026)
@@ -157,14 +172,14 @@ Chaque commit build et push les images Docker.
push → restore → build → unit tests → integration tests → docker build
```
## Implémentation actuelle
## État déclaré dans le plan historique (juillet 2026)
- **Forgejo Actions** (`./forgejo/workflows/ci.yml`) ✅
- Build + Test sur push (branches main, develop) ✅
- Docker build (central + agent) sur main ✅
- PostgreSQL service pour les tests ✅
## À faire (v2)
## Travaux à faire dans le plan historique (v2, juillet 2026)
- [ ] multi-arch Docker (linux/amd64 + arm64)
- [ ] Push vers registry Docker
@@ -231,7 +246,7 @@ UserRole { Admin, Supervisor, Viewer } ✅
Interfaces, DTOs, validateurs.
## Implémentation actuelle
## État déclaré dans le plan historique (juillet 2026)
| Composant | Approche | Status |
|-----------|----------|--------|
@@ -266,7 +281,7 @@ La migration vers CQRS avec MediatR est prévue en v2 si le besoin se fait senti
Authentification AVANT d'exposer l'API.
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Fonctionnalité | Priorité | Status |
|---|---|---|
@@ -299,7 +314,7 @@ Authentification AVANT d'exposer l'API.
# Phase 7 — API Sites + Agent Tokens
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Méthode | Route | Auth | Status |
|---|---|---|---|
@@ -319,7 +334,7 @@ Le token d'enregistrement est :
# Phase 8 — Agent Registration + Heartbeat
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
### Côté Central
@@ -358,7 +373,7 @@ Reporté après le MVP logiciel.
# Phase 10 — Camera Management API
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Méthode | Route | Auth | Status |
|---|---|---|---|
@@ -390,7 +405,7 @@ Reportées en v2.
# Phase 15 — Hangfire Central
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Composant | Status |
|-----------|--------|
@@ -424,7 +439,7 @@ Reportées en v2.
# Phase 18 — Blazor UI
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Page | Route | Auth | Status |
|------|-------|------|--------|
@@ -479,7 +494,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
# Phase 22 — Dashboard KPI
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
| Widget | Source | Status |
|--------|--------|--------|
@@ -494,7 +509,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
# Phase 23 — Production Hardening
## Implémenté
## État déclaré comme implémenté dans le plan historique (juillet 2026)
- [x] Health checks (/healthz, /readyz)
- [x] Rate limiting (Auth: 10/min, API: 200/min)
@@ -503,10 +518,10 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
- [x] Documentation API (Scalar UI)
- [x] README avec architecture + setup
## À faire
## Travaux ouverts dans le plan historique (juillet 2026)
- [ ] Serilog + Seq/GlitchTip
- [ ] Métriques Prometheus
- [x] Export des métriques Prometheus Central/Agent (`/metrics`); le scraping externe et les seuils d'alerte en exploitation restent à configurer et valider par l'opérateur.
- [ ] Backup PostgreSQL automatisé
- [ ] Backup RustFS (S3 → S3)
- [ ] Tests de charge (k6)
@@ -514,7 +529,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
---
## Résumé — Stats MVP
## Résumé historique — Stats MVP (juillet 2026)
| Métrique | Valeur |
|----------|--------|
+34 -464
View File
@@ -1,464 +1,34 @@
# Heimdall — Notifications (Email + Gotify + Templates)
**Stack :** `FluentEmail.Smtp`, `Gotify.NET`, `RazorTemplating` / `Scriban` (Markdown → HTML)
---
## 1. Canaux de notification
| Canal | Usage | Priorité | Bibliothèque |
|---|---|---|---|
| **Email** (SMTP) | Notifications importantes, résumés | 🔴 Requis | `FluentEmail.Smtp` + `FluentEmail.Razor` |
| **Gotify** (push) | Alertes temps réel, notifications rapides | 🟠 Recommandé | `Gotify.NET` |
| **In-app** (SignalR) | Notifications silencieuses dans l'UI | 🟢 Requis | SignalR (intégré) |
---
## 2. SMTP — Configuration
Configurable depuis l'UI Admin :
```csharp
public class SmtpConfig
{
public string Host { get; set; } = "smtp.example.com";
public int Port { get; set; } = 587;
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; // chiffré
public bool UseSsl { get; set; } = true;
public string FromAddress { get; set; } = "heimdall@example.com";
public string FromName { get; set; } = "Heimdall";
}
```
Stockée en base (table `AppConfig`), champ `Password` chiffré avec `IDataProtector`.
Test depuis l'UI : "Envoyer un email de test".
### Librairies NuGet
```
dotnet add package FluentEmail.Smtp
dotnet add package FluentEmail.Razor // templates Razor → HTML
// ou
dotnet add package Scriban // templates Markdown alternatif
```
---
## 3. Gotify — Configuration
Gotify est un serveur de notification push self-hosted (Docker).
### Dépendances
```
dotnet add package Gotify.NET
```
### Configuration
```csharp
public class GotifyConfig
{
public string ServerUrl { get; set; } = "http://gotify:8080";
public string AppToken { get; set; } = string.Empty; // chiffré
public int Priority { get; set; } = 5; // 0-10
}
```
### UI Admin
```text
┌──────────────────────────────────────────────┐
│ Notifications │
│ │
│ ┌──── Email (SMTP) ───────────────────────┐ │
│ │ Serveur: [smtp.example.com ] │ │
│ │ Port: [587 ] │ │
│ │ SSL: [x] │ │
│ │ Utilisateur: [notifications@... ] │ │
│ │ Mot de passe: [******** ] │ │
│ │ De: [heimdall@example.com ] │ │
│ │ │ │
│ │ [Tester la connexion] │ │
│ └───────────────────────────────────────────┘ │
│ │
│ ┌──── Gotify ──────────────────────────────┐ │
│ │ Serveur: [http://gotify:8080 ] │ │
│ │ Token: [******** ] │ │
│ │ Priorité: [5 ▼] │ │
│ │ │ │
│ │ [Tester la connexion] │ │
│ └───────────────────────────────────────────┘ │
│ │
│ ┌──── Templates ───────────────────────────┐ │
│ │ [Modifier les templates ▼] │ │
│ └───────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘
```
---
## 4. Templates de notification (Markdown)
### Architecture
```text
Base de données
└── NotificationTemplate
├── EventType (enum)
├── Language ("fr", "en", "de"...)
├── Channel ("email", "gotify", "inapp")
├── Subject (string, avec variables)
└── Body (string, Markdown avec variables)
```
### Template Entity
```csharp
public class NotificationTemplate
{
public Guid Id { get; set; }
public EventType EventType { get; set; } // PersonDetected, etc.
public string Language { get; set; } = "fr"; // "fr", "en", "de"
public string Channel { get; set; } = "email"; // "email", "gotify", "inapp"
public string Subject { get; set; } = string.Empty;
public string BodyMarkdown { get; set; } = string.Empty;
public bool IsDefault { get; set; } // template par défaut
}
```
### Variables disponibles dans les templates
| Variable | Description | Exemple |
|---|---|---|
| `{{SiteName}}` | Nom du site | "Entrepôt A" |
| `{{CameraName}}` | Nom de la caméra | "Entrée principale" |
| `{{EventType}}` | Type d'événement | "PersonDetected" |
| `{{EventTime}}` | Horodatage | "14/07/2026 14:23:05" |
| `{{EventTimeAgo}}` | Relatif | "il y a 2 minutes" |
| `{{PersonName}}` | Nom de la personne | "Jean Dupont" |
| `{{PersonPhotoUrl}}` | Lien photo | `https://heimdall/...` |
| `{{VehiclePlate}}` | Plaque | "AA-123-XX" |
| `{{VehicleModel}}` | Modèle | "Renault Clio" |
| `{{SnapshotUrl}}` | Lien snapshot | `https://heimdall/...` |
| `{{EventUrl}}` | Lien vers l'événement | `https://heimdall/events/...` |
| `{{SiteUrl}}` | URL du Central | `https://heimdall.example.com` |
| `{{AlertCount}}` | Nombre d'alertes (résumé) | "12" |
### Templates par défaut (fr)
```markdown
=== PersonDetected — email — fr ===
Subject: [Heimdall] Personne détectée — {{CameraName}}
Body:
**🔴 Alerte — Personne détectée**
| | |
|---|---|
| **Site** | {{SiteName}} |
| **Caméra** | {{CameraName}} |
| **Date** | {{EventTime}} |
| **Personne** | {{PersonName}} |
Voir l'événement : [{{EventUrl}}]({{EventUrl}})
---
=== PersonDetected — email — en ===
Subject: [Heimdall] Person detected — {{CameraName}}
Body:
**🔴 Alert — Person detected**
| | |
|---|---|
| **Site** | {{SiteName}} |
| **Camera** | {{CameraName}} |
| **Time** | {{EventTime}} |
| **Person** | {{PersonName}} |
View event: [{{EventUrl}}]({{EventUrl}})
---
=== UnknownPerson — gotify — fr ===
Subject: Visage inconnu — {{CameraName}}
Body:
Visage inconnu détecté sur {{CameraName}} ({{SiteName}})
à {{EventTime}}.
---
=== DailySummary — email — fr ===
Subject: [Heimdall] Résumé quotidien — {{SiteName}} — {{EventTime}}
Body:
**📊 Résumé quotidien — {{SiteName}}**
Période: {{DateStart}} → {{DateEnd}}
| Type | Nombre |
|---|---|
| Personnes détectées | {{PersonCount}} |
| Dont connues | {{KnownPersonCount}} |
| Dont inconnues | {{UnknownPersonCount}} |
| Véhicules détectés | {{VehicleCount}} |
| Événements total | {{TotalEventCount}} |
[Voir le tableau de bord]({{SiteUrl}})
```
### Rendu du template
```csharp
public class NotificationService : INotificationService
{
private readonly ScribanTemplateEngine _scriban;
private readonly IRepository<NotificationTemplate> _templates;
public async Task<string> RenderAsync(
EventType eventType,
string language,
string channel,
Dictionary<string, object> variables)
{
// 1. Chercher template spécifique (eventType + language + channel)
var template = await _templates.FirstOrDefaultAsync(t =>
t.EventType == eventType &&
t.Language == language &&
t.Channel == channel);
// 2. Fallback : template par défaut de cette langue
template ??= await _templates.FirstOrDefaultAsync(t =>
t.EventType == eventType &&
t.Language == language &&
t.IsDefault);
// 3. Fallback : template anglais
template ??= await _templates.FirstOrDefaultAsync(t =>
t.EventType == eventType &&
t.Language == "en" &&
t.IsDefault);
if (template == null) return string.Empty;
// 4. Rendre avec Scriban
var parsed = Template.Parse(template.BodyMarkdown);
var result = await parsed.RenderAsync(variables);
return result;
}
}
```
### UI d'édition des templates
```text
┌──────────────────────────────────────────────────────┐
│ Templates de notification [Langue: français ▼]
│ │
│ Événement: [Personne détectée ▼] Canal: [Email ▼] │
│ │
│ Sujet: │
│ ┌──────────────────────────────────────────────────┐ │
│ │ [Heimdall] Personne détectée — {{CameraName}} │ │
│ └──────────────────────────────────────────────────┘ │
│ │
│ Corps (Markdown): │
│ ┌──────────────────────────────────────────────────┐ │
│ │ **🔴 Alerte — Personne détectée** │ │
│ │ │ │
│ │ | | | │ │
│ │ |---|---| │ │
│ │ | **Site** | {{SiteName}} | │ │
│ │ | **Caméra** | {{CameraName}} | │ │
│ │ │ │
│ │ Voir : [{{EventUrl}}]({{EventUrl}}) │ │
│ └──────────────────────────────────────────────────┘ │
│ │
│ [Aperçu] [Réinitialiser] [Enregistrer] │
│ │
│ ── Aperçu ────────────────────────────────────────── │
│ De: heimdall@example.com │
│ À: test@example.com │
│ Sujet: [Heimdall] Personne détectée — Entrée │
│ ──────────────────────────────────────────────────── │
│ 🔴 Alerte — Personne détectée │
│ Site: Entrepôt A | Caméra: Entrée | Date: 14/07... │
└──────────────────────────────────────────────────────┘
```
### Librairies
```
dotnet add package Scriban # Moteur de templates Markdown
dotnet add package Scriban.Signed # (si besoin strong name)
// ou
dotnet add package FluentEmail.Razor # Alternative Razor → HTML
dotnet add package FluentEmail.Smtp # Envoi SMTP
dotnet add package Gotify.NET # Gotify push
```
---
## 5. Types d'événements notifiables
| EventType | Email | Gotify | In-App (SignalR) | Template dispo |
|---|---|---|---|---|
| `PersonDetected` | ✅ | ✅ | ✅ | Oui |
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | Oui |
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | Oui |
| `VehicleDetected` | ✅ | ✅ | ✅ | Oui |
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | Oui |
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | Non |
| `CameraOffline` | ✅ | ✅ | ✅ | Oui |
| `CameraOnline` | 🟡 | 🟡 | ✅ | Oui |
| `DailySummary` | ✅ | ❌ | ❌ | Oui |
| `WeeklySummary` | ✅ | ❌ | ❌ | Oui |
---
## 6. File d'attente des notifications (Hangfire)
Toutes les notifications passent par Hangfire pour :
1. Fiabilité (retry si échec SMTP)
2. File d'attente (ne pas bloquer le thread de détection)
3. Rate limiting (max N emails/min)
```csharp
public class SendNotificationJob
{
[AutomaticRetry(Attempts = 3, DelaysInSeconds = [60, 300, 900])]
public async Task ExecuteAsync(
Guid eventId,
string channel, // "email", "gotify", "inapp"
string language,
CancellationToken ct)
{
var event = await _db.Events.FindAsync(new object[] { eventId }, ct);
var variables = await BuildVariablesAsync(event, ct);
var rendered = await _notificationService.RenderAsync(
event.Type, language, channel, variables);
await channel switch
{
"email" => await SendEmailAsync(event, rendered, ct),
"gotify" => await SendGotifyAsync(event, rendered, ct),
"inapp" => await SendInAppAsync(event, rendered, ct),
_ => Task.CompletedTask
};
}
}
```
### Déclenchement depuis le pipeline IA
```csharp
// Dans le handler de détection
if (shouldNotify)
{
BackgroundJob.Enqueue<SendNotificationJob>(j =>
j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None));
BackgroundJob.Enqueue<SendNotificationJob>(j =>
j.ExecuteAsync(event.Id, "gotify", user.Language, CancellationToken.None));
}
// Notification in-app = temps réel via SignalR (pas Hangfire)
await _signalrHub.SendEventAsync(event);
```
---
## 7. Configuration par User
Chaque utilisateur peut configurer ses notifications :
```csharp
public class UserNotificationConfig
{
public Guid UserId { get; set; }
public bool EmailEnabled { get; set; } = true;
public bool GotifyEnabled { get; set; } = false;
public string EmailAddress { get; set; } = string.Empty;
public List<EventType> SubscribedEvents { get; set; } = new();
public string Language { get; set; } = "fr";
public bool DailyDigest { get; set; } = true;
public bool WeeklyDigest { get; set; } = false;
}
```
UI User :
```text
┌──────────────────────────────────────────────┐
│ Mes notifications │
│ │
│ Recevoir les notifications par : │
│ [✅] Email : jean@example.com │
│ [ ] Gotify │
│ │
│ M'alerter pour : │
│ [✅] Personnes détectées │
│ [✅] Visages inconnus │
│ [ ] Véhicules │
│ [✅] Caméra hors ligne │
│ [ ] Mouvement seul │
│ │
│ Résumés : │
│ [✅] Résumé quotidien │
│ [ ] Résumé hebdomadaire │
│ │
│ Langue des notifications : [Français ▼] │
└──────────────────────────────────────────────┘
```
---
## 8. Résumés quotidiens/hebdomadaires (Hangfire)
```csharp
// Planifié dans Hangfire
RecurringJob.AddOrUpdate<DailyDigestJob>(
"daily-digest",
j => j.ExecuteAsync(CancellationToken.None),
Cron.Daily(8)); // 8h00
public class DailyDigestJob
{
public async Task ExecuteAsync(CancellationToken ct)
{
var users = await _db.Users
.Where(u => u.NotificationConfig.DailyDigest)
.ToListAsync(ct);
foreach (var user in users)
{
var stats = await BuildDailyStatsAsync(user.Id, ct);
BackgroundJob.Enqueue<SendNotificationJob>(j =>
j.ExecuteAsync(stats, "email", user.NotificationConfig.Language, ct));
}
}
}
```
---
## 9. Tests
```
Notification is sent when person detected
SMTP failure retries 3 times via Hangfire
Gotify notification is sent correctly
User can disable email notifications
Template rendering replaces all variables
Missing variable does not crash (Scriban safe)
Template editing in UI saves correctly
Template preview shows correct rendering
Fallback to default template works
Fallback to English template works
Daily digest is generated at configured hour
User language changes template language
Admin can test SMTP connection from UI
Admin can test Gotify connection from UI
```
# Heimdall — Notifications
## État livré vérifié dans le dépôt
Les canaux externes déclarés par `NotificationChannel` sont `Email` et `Ntfy`;
les notifications in-app sont consultables séparément dans le centre
`/notifications`. L’interface utilise les endpoints authentifiés
`/api/notifications` et le hub `/hubs/notifications` pour le compteur non lu.
Voir [`signalr-usage.md`](signalr-usage.md) pour le contrat du hub.
Les réglages administrateur se trouvent dans `/settings` (policy
`Admin.Manage`) : configuration et test SMTP, configuration et test ntfy. Les
préférences de l’utilisateur, dont l’adresse email, l’activation ntfy, le topic,
les événements abonnés et les options de résumé, sont éditées dans `/profile`.
La livraison email utilise `EmailService`; les notifications push utilisent
`NtfyService` et Hangfire. `DailyDigestJob` envoie le résumé quotidien à 8 h;
`WeeklyDigestJob` envoie le résumé hebdomadaire le lundi à 8 h, selon les
expressions cron enregistrées dans `JobSetup`.
Ces constats sont une vérification statique des sources, pas une validation de
serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces
services dépend de l’opérateur.
Sources principales :
- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs)
- [`NotificationSettingsSection`](../src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor)
- [`NotificationsPage`](../src/Heimdall.Web/Components/Pages/NotificationsPage.razor)
- [`NotificationsController`](../src/Heimdall.Web/Controllers/NotificationsController.cs)
- [`NtfyService`](../src/Heimdall.Infrastructure/Services/NtfyService.cs)
- [`EmailService`](../src/Heimdall.Infrastructure/Services/EmailService.cs)
- [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs)
- [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs)
- [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs)
+56 -66
View File
@@ -1,17 +1,18 @@
# Heimdall — Spécification technique
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Local AI
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Agent-local AI par défaut
---
# 1. Vision
Heimdall is a modern self-hosted intelligent video surveillance platform.
100% local AI, no cloud dependency, multi-site distributed architecture.
Agent inference runs locally by default; a remote analysis broker is configurable.
The default deployment does not require a managed cloud service.
## Pourquoi Heimdall ?
- **Privacy first** — tout l'IA tourne en local (ONNX Runtime sur agents + Ollama)
- **Privacy first** — l'analyse ONNX est locale par défaut sur l'Agent; le mode broker distant est une option de déploiement distincte
- **Multi-site** — un Central + N Agents distants
- **Économique** — pas d'abonnement cloud, hardware standard
- **Pérenne** — .NET 10, Clean Architecture, open source
@@ -23,13 +24,13 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
- Clean Architecture / CQRS / MédiatR
- Multi-site : 1 serveur Central + N Agents Docker distants
- Live vidéo : relais RTSP de l’Agent vers MediaMTX, lecture navigateur WHEP/WebRTC; mesurer la latence avant d’annoncer une cible
- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés)
- Espace utilisateur : Admin (global) + User (site-scope)
- Analyse ONNX sur l'Agent : CPU par défaut, CUDA NVIDIA optionnel; AMD/Intel détectés pour l'inventaire ne signifient pas une inférence accélérée. Le mode broker distant est configurable, sans validation inter-sites revendiquée.
- Rôles humains : Admin, Supervisor et Viewer; permissions par rôle, avec contrôle distinct du périmètre site/caméra sur chaque ressource
- Stockage : RustFS/S3 centralisé
- Temps réel : SignalR (5 hubs)
- Jobs planifiés : Hangfire (Central PGSQL + Agent InMemory)
- Stack : .NET 10, Blazor MudBlazor, PostgreSQL
- Pas de cloud, pas de dépendance externe
- Déploiement auto-hébergé; aucun service cloud géré n'est requis par défaut
---
@@ -40,8 +41,8 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
│ HEIMDALL CENTRAL │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ API │ │ Web │ │ Workers │ │ MediaMTX / IA │ │
│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama / RustFS │ │
│ │ API │ │ Web │ │ Workers │ │ MediaMTX │ │
│ │ REST + │ │ Blazor │ │ Hangfire │ │ RustFS │ │
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ Live media │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │
│ │ │ │ │
@@ -74,32 +75,20 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
# 4. Domain Model — Entités principales
```
Site Agent Camera
├── Id (Guid) ├── Id (Guid) ├── Id (Guid)
├── Name ├── SiteId (FK) ├── SiteId (FK)
├── Address ├── Name ├── Name
├── Timezone ├── Hostname ├── Manufacturer
├── Enabled ├── Version ├── Model
└── Registration ├── Status ├── RtspUrl
Token (hash) │ (Online/Offline/Err) ├── Status
TokenPlain ├── LastHeartbeat ├── Capabilities
TokenExpiresAt ├── PublicIp │ (Ptz, Audio, Motion)
└── Capabilities ├── Credentials (encrypted)
HasGpu, CpuCores └── StoragePolicyId
Résumé des principaux types et propriétés représentatives; les noms suivent
les entités actuelles dans `Heimdall.Domain` et ne remplacent pas leur modèle
complet.
Person Vehicle Event
├── Id ├── Id ├── Id
├── Name ├── LicensePlate ├── SiteId
├── Photo ├── PersonId (FK) ├── CameraId
├── IsUnknown ├── Make ├── Type (enum)
├── FaceSamples ├── Model ├── Timestamp
└── Notes └── Color ├── SnapshotPath
└── Metadata (jsonb)
| Type | Propriétés et relations principales |
|---|---|
| `Site` | `Name`, `Address`, `Timezone`, `Enabled`, `RegistrationTokenHash`, `TokenExpiresAt`. Seul le hash du jeton d’enrôlement est persisté; la valeur brute est renvoyée lors de la création ou régénération. |
| `Agent` | `SiteId`, `Name`, `Hostname`, `Version`, `Status`, `LastHeartbeat`, `ApiKeyHash`, `ApiKeyPrefix`; inclut aussi les relevés d’inventaire matériel et système. |
| `Camera` | `SiteId`, `AgentId`, `Name`, `RtspUrl`, `SubRtspUrl`, `Status`, `Capabilities`, `StoragePolicyId`; les credentials résident dans l’entité liée `CameraCredentials`. |
| `Person` / `KnownFace` | `Person.DisplayName`, `PhotoUrl`, `Category`, `IsWatchlisted`; les embeddings appartiennent aux entités liées `KnownFace`. |
| `Vehicle` | `LicensePlate`, `PersonId`, `Make`, `Model`, `Color`. |
| `CameraEvent` | `CameraId`, `AgentId`, `Type`, `Confidence`, `OccurredAt`, références de snapshot/stockage, `MetadataJson`; peut référencer une personne, un véhicule et un enregistrement. |
Enum: CameraStatus, AgentStatus, EventType, StorageProvider
Enum: GpuAcceleration, ThemeMode
```
Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/Heimdall.Domain/Entities/Agent.cs), [`Camera`](../src/Heimdall.Domain/Entities/Camera.cs), [`Person` et `KnownFace`](../src/Heimdall.Domain/Entities/Person.cs), [`Vehicle`](../src/Heimdall.Domain/Entities/Vehicle.cs), [`CameraEvent`](../src/Heimdall.Domain/Entities/CameraEvent.cs).
---
@@ -117,10 +106,10 @@ Enum: GpuAcceleration, ThemeMode
## Authentification — `docs/auth-roles.md`
- 2 types d'utilisateurs : Admin (tout) + User (N sites)
- 3 rôles : Admin, Supervisor et Viewer; les permissions viennent du rôle et l'accès aux sites/caméras est vérifié séparément selon la ressource
- ASP.NET Core Identity + JWT + Refresh tokens
- Permissions par Policy : Camera.Read, Admin.Manage...
- Scope site : un User ne voit que ses sites assignés
- Accès aux ressources : les services d’accès vérifient le périmètre site/caméra pour chaque opération; voir `docs/auth-roles.md`
- Visibilité UI adaptée au rôle (menus, boutons)
- Voir `docs/auth-roles.md` pour le détail complet
@@ -128,8 +117,8 @@ Enum: GpuAcceleration, ThemeMode
- ONVIF WS-Discovery (même VLAN) + discovery manuelle (IP)
- Protocole Imou : activation RTSP manuelle requise
- FFmpeg capture : RTSP → H264, GPU auto-détection (NVENC/QSV/VAAPI/CPU)
- AI Pipeline : Agent CPU (YOLOv8 nano) → analyse IA sur agents GPU (ONNX Runtime, local ou via broker inter-sites)
- Analyse d'images : YOLO/ONNX sur Agent, CPU par défaut; CUDA NVIDIA optionnel avec fallback CPU. Les détections de matériel AMD/Intel alimentent l'inventaire et ne prouvent pas une inférence accélérée.
- Mode d'analyse distant : configurable avec un broker et repli local si celui-ci est inaccessible; aucun déploiement inter-sites n'est validé par cette configuration seule.
- Détection : objets, visages, plaques (LPR), véhicules
- Stockage credentials caméras chiffré (IDataProtector)
@@ -144,8 +133,10 @@ l’installation. La négociation synthétique dispose d’une preuve séparée,
cela ne valide ni une caméra physique, ni l’accès depuis un réseau externe, ni
une latence cible en déploiement; voir #161 et #341.
Un changement d’URL source pour le même CameraId peut conserver l’ancien relay
jusqu’au renouvellement; cette limite Agent est suivie dans #355.
Le relay compare la source RTSP effective (sous-flux s’il est configuré, sinon
flux principal) et redémarre le processus après un changement de source pour le
même CameraId. Ce comportement est couvert par les tests Agent et l’acceptance
locale de #355; aucune caméra réelle ni réseau externe n’a été validé.
## Temps réel (SignalR) — `docs/signalr-usage.md`
@@ -174,17 +165,18 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
## Notifications — `docs/notifications.md`
- Email SMTP (FluentEmail), Gotify push
- Templates Markdown avec Scriban, variables, fallback i18n
- Templates éditables depuis l'UI Admin
- File Hangfire avec retry (3 tentatives)
- Résumés quotidiens/hebdomadaires planifiés
- Voir `docs/notifications.md` pour le détail complet
Les notifications in-app sont consultables dans `/notifications`. Les canaux
externes livrés sont l’email SMTP et ntfy; les administrateurs configurent et
testent ces services dans `/settings`, tandis que les préférences individuelles
et les options de résumé se règlent dans `/profile`. Les digests quotidien et
hebdomadaire sont planifiés par les jobs Hangfire actuels. Voir
[`docs/notifications.md`](notifications.md) pour les endpoints, les contrôles
d’accès, la cadence et les limites de validation SMTP/ntfy.
## Stockage & Rétention — `docs/hangfire-usage.md`
- RustFS (par défaut), S3-compatible (AWS S3, MinIO), Local (fallback)
- L'Agent écrit les segments directement sur S3
- L'Agent découpe le flux RTSP principal en segments MP4 dans son spool local, puis envoie les segments terminés au Central via l'API; le Central les écrit dans le fournisseur de stockage configuré
- Retention configurable par caméra (7-90 jours)
- Hangfire purge les fichiers expirés
- Voir `docs/hangfire-usage.md` §2 pour les jobs
@@ -192,15 +184,18 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
## Interface Web (Blazor) — `docs/ui-pages.md`
- MudBlazor, Interactive Server Rendering
- 8 pages : Login, Dashboard, Sites, Cameras, Persons, Events, Admin, Alertes
- Parcours documentés : authentification, dashboard, sites/caméras, personnes,
événements, alertes/notifications, profil et administration. Les routes et
pages détaillées sont recensées dans [`docs/ui-pages.md`](ui-pages.md);
l’administration est répartie entre pages protégées et ne correspond pas à
une route unique `/admin`.
- Live vidéo depuis le détail caméra : publication RTSP Agent→MediaMTX et lecture WHEP/WebRTC via `live-view.js`
- Thème Light/Dark/Auto, localisation française
- Voir `docs/ui-pages.md` pour les maquettes ASCII complètes
## Application web installable — PWA
Le client natif est retiré. La cible est le serveur Blazor accessible sur mobile et installable depuis le navigateur.
Installation, page hors connexion, reprise de session et Web Push doivent être implémentés ; le rendu Interactive Server nécessite une connexion pour les fonctions métier.
Le client natif est retiré. Le socle PWA livré comprend le manifeste, le service worker borné et la page d’information hors connexion. Les écrans métier restent dépendants d’une connexion Interactive Server; Web Push et consultation métier hors ligne ne sont pas implémentés. Les validations appareils/déploiement restent à faire.
Voir [l’audit et le plan PWA](pwa.md) pour les écarts, critères de réception et l’option de consultation hors ligne ultérieure.
---
@@ -217,28 +212,23 @@ services:
heimdall-agent: # Agent .NET + FFmpeg relay (Hangfire InMemory)
postgresql: # Base de données
rustfs: # Stockage S3 (enregistrements)
# IA lourde (détection, visages, LPR) : agents GPU ONNX Runtime — pas de service central
ollama: # LLM local (résumés)
# Analyse ONNX exécutée par l'Agent (CPU par défaut, CUDA NVIDIA optionnel); voir docs/gpu-runtime.md
ollama: # service optionnel; URL configurable et disponibilité sondée, aucune génération LLM livrée
mediamtx: # Serveur média RTSP/WHEP (optionnel, live vidéo)
coturn: # TURN relay (optionnel, double NAT)
```
## GPU Passthrough
## GPU et inférence
| Conteneur | GPU | Docker |
|---|---|---|
| `heimdall-agent` (GPU) | NVIDIA/AMD/Intel | profiles compose GPU : nvidia / rocm (/dev/kfd,/dev/dri) / vaapi (/dev/dri) |
| `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `--device /dev/dri:/dev/dri` |
| `ollama` | NVIDIA (opt) | `--gpus all` |
Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
## Estimation capacité CPU (Intel i5-10gen)
| Mode | 720p | 1080p | 4K |
|---|---|---|---|
| CPU (libx264) | 8 flux | 4 flux | 1 flux |
| GPU (NVENC/QSV) | 20+ flux | 12+ flux | 4+ flux |
L'image et le chemin Agent par défaut utilisent `CPUExecutionProvider`. Une
image amd64 NVIDIA/CUDA signée est proposée en option; si CUDA ne peut pas
initialiser une session, l'Agent revient au CPU. L'inventaire peut détecter du
matériel NVIDIA, AMD et Intel, mais les overlays AMD/Intel ne fournissent pas
de backend ONNX correspondant. La détection de capacités d'encodage dans
l'inventaire n'implique pas leur utilisation par les parcours vidéo. Voir
[`docs/gpu-runtime.md`](gpu-runtime.md) pour les variantes et les preuves
disponibles. L'exécution CUDA sur matériel réel et les performances par flux
restent à mesurer; aucune capacité chiffrée n'est annoncée ici.
---
@@ -248,7 +238,7 @@ Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
- Serilog (structure logging)
- OpenTelemetry ready
- Sentry SDK compatible GlitchTip
- Healthchecks (API, Agent, DB, RustFS, Broker IA, Ollama)
- Health checks Central : `/healthz` est une liveness toujours `200`; `/readyz` vérifie PostgreSQL et le stockage actif (`200` si healthy, sinon `503`); `/health/live` vérifie PostgreSQL plus le backend IA configuré (CodeProject.AI ou Ollama; l'absence de backend IA est valide) et renvoie `503` si un check n'est pas healthy. Côté Agent, `/healthz` agrège `agent_health` et `live` (`Degraded` → `200`, `Unhealthy` → `503`); `/health/live` expose la dégradation du pipeline IA (`200` healthy, sinon `503`). Aucun health check Central distinct du broker distant n'est enregistré; voir [`HealthController`](../src/Heimdall.Web/Controllers/HealthController.cs), [`AiHealthCheck`](../src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs) et [`Agent Program`](../src/Heimdall.Agent/Program.cs).
- Tests : xUnit + Shouldly + NSubstitute + bUnit + Testcontainers
---
+13 -37
View File
@@ -242,7 +242,7 @@ Dashboard shows agent offline state
│ │ Commandes │ │
│ │ Installer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
│ │ │ demander URL/token puis installer [⧉]│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ Lancer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
@@ -273,7 +273,7 @@ Configuration (Docker uniquement si l'image GPU est publiée)
Commandes
Installer
┌──────────────────────────────────────────────┐
│ commande/script [⧉]│
│ demande URL et token masqué, puis installe [⧉]│
└──────────────────────────────────────────────┘
Lancer
┌──────────────────────────────────────────────┐
@@ -281,7 +281,9 @@ Lancer
└──────────────────────────────────────────────┘
```
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige les métadonnées d'image vérifiées de la release et épingle l'image CPU ou GPU sur son digest signé (`repository@sha256:digest`). Compose utilise `pull_policy: always` pour récupérer exactement ce digest; Docker Run utilise `--pull always`. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
La commande Linux ne contient ni l'URL Central ni le token du site. À son exécution, elle demande l'URL HTTPS puis le token sans afficher sa saisie, place les valeurs dans des fichiers temporaires protégés et télécharge les scripts par HTTPS avant leur exécution. L'installateur exige les fichiers d'enrôlement protégés et conserve le token comme credential systemd.
### États — Détail Site
@@ -562,41 +564,15 @@ Matrice complète des 15 permissions système avec coches par rôle
---
## P14 — Administration (legacy)
## P14 — Administration centralisée (ancienne maquette retirée)
**Route** : `/admin`
**Auth** : Requise + `Admin.Manage`
```text
┌──────────────────────────────────────────────────────┐
│ Administration │
│ │
│ ┌──── Tabs ───────────────────────────────────────┐ │
│ │ Utilisateurs | Rôles | Clés API | Jobs │ │
│ │ │ │
│ │ [Tab Utilisateurs] │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ Jean Dupont Admin jean@ex.com [×] │ │ │
│ │ │ Marie Martin Superviseur marie@ex.com [×] │ │ │
│ │ │ Paul View paul@ex.com [×] │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ [Tab Clés API] │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ Key-1 Camera.Read 01/01/2026 Actif [×] │ │ │
│ │ │ Key-2 Camera.Write 15/06/2026 Expiré [×] │ │ │
│ │ │ Key-3 Person.Read 01/07/2026 Actif [×] │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ [Tab Jobs Hangfire] │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ Retention Check Tous les jours 🟢 OK │ │ │
│ │ │ S3 Cleanup Tous les jours 🟢 OK │ │ │
│ │ │ Unknown Faces Clean Toutes les sem. 🟢 OK │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
```
La page d’accueil `/admin` et les onglets regroupés dans cette maquette ne sont
pas mappés dans le runtime. Les capacités d’administration sont réparties sur
les pages actuelles : `/users`, `/admin/roles`, `/admin/groups`,
`/admin/claims`, `/admin/agents`, `/admin/api-keys`, `/settings` et `/hangfire`.
Les notifications et la configuration des releases sont des sections de
`/settings`, pas des sous-pages d’un dashboard `/admin`. Voir
[`docs/auth-roles.md`](auth-roles.md) pour les rôles, routes et policies actuels.
---
+26 -8
View File
@@ -1,15 +1,25 @@
#!/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" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
CENTRAL_URL="" SITE_TOKEN="" CENTRAL_URL_FILE="" SITE_TOKEN_FILE="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=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;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--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 are required" >&2; exit 1; }
while [[ $# -gt 0 ]]; do case "$1" in --central-url-file) CENTRAL_URL_FILE="$2"; shift 2;; --site-token-file) SITE_TOKEN_FILE="$2"; shift 2;; --central-url|--site-token) echo "Error: pass enrollment settings through protected files, not command-line values" >&2; exit 1;; --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;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url-file PATH --site-token-file PATH [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
read_protected_value() {
local path="$1" label="$2" mode
[[ -n "$path" && -f "$path" && ! -L "$path" ]] || { echo "Error: $label must reference a regular protected file" >&2; exit 1; }
mode=$(stat -c '%a' "$path")
(( (8#$mode & 077) == 0 )) || { echo "Error: $label file must not be accessible by group or others" >&2; exit 1; }
cat -- "$path"
}
[[ -n "$CENTRAL_URL_FILE" && -n "$SITE_TOKEN_FILE" ]] || { echo "Error: --central-url-file and --site-token-file are required" >&2; exit 1; }
CENTRAL_URL="$(read_protected_value "$CENTRAL_URL_FILE" 'Central URL')"
SITE_TOKEN="$(read_protected_value "$SITE_TOKEN_FILE" 'site token')"
[[ -n "$CENTRAL_URL" && -n "$SITE_TOKEN" ]] || { echo "Error: protected Central URL and site token files must be non-empty" >&2; exit 1; }
[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; }
if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi
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
echo "Error: Central URL must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
exit 1
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
@@ -45,9 +55,11 @@ RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
for attempt in 1 2 3; do
CURL_PROTOCOL=https
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
printf '%s' "$RELEASE_METADATA_URL" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/release-metadata.curl"
chmod 600 "$TMP_DIR/release-metadata.curl"
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
--connect-timeout 10 --max-time 30 \
-w '%{http_code}' "$RELEASE_METADATA_URL" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
-w '%{http_code}' --config "$TMP_DIR/release-metadata.curl" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
break
fi
@@ -109,6 +121,11 @@ with tarfile.open(sys.argv[1], 'r:gz') as archive:
shutil.copyfileobj(source,output)
PY
[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; }
printf '%s' "$CENTRAL_URL" | python3 -c 'import json,pathlib,sys; p=pathlib.Path(sys.argv[1]); raw=p.read_text() if p.exists() else "{}";
try: d=json.loads(raw)
except json.JSONDecodeError: d={}
d.setdefault("Agent",{})["CentralUrl"]=sys.stdin.read(); p.write_text(json.dumps(d,indent=2)+"\n")' "$TMP_DIR/agent/appsettings.json"
chmod 640 "$TMP_DIR/agent/appsettings.json"
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"
@@ -122,7 +139,9 @@ sudo install -d -o root -g root -m 755 /usr/local/libexec
SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py"
if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then
SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py"
curl -fsS "$CENTRAL_URL/install/agent-supervisor.py" -o "$SUPERVISOR_SOURCE" || {
printf '%s' "$CENTRAL_URL/install/agent-supervisor.py" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/supervisor.curl"
chmod 600 "$TMP_DIR/supervisor.curl"
curl -fsS --config "$TMP_DIR/supervisor.curl" -o "$SUPERVISOR_SOURCE" || {
echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1;
}
fi
@@ -150,7 +169,6 @@ if [[ "$RUN_MODE" == true ]]; then
ASPNETCORE_URLS=http://127.0.0.1:8081 \
HEIMDALL_DOTNET="$DOTNET_BIN" \
ASPNETCORE_ENVIRONMENT=Production \
Agent__CentralUrl="$CENTRAL_URL" \
Agent__AgentName="$AGENT_NAME" \
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
Agent__StateDirectory="$STATE_DIR" \
@@ -173,7 +191,6 @@ 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
@@ -183,6 +200,7 @@ $AGENT_NAME_CREDENTIAL
[Install]
WantedBy=multi-user.target
EOF
sudo chmod 600 "/etc/systemd/system/$SERVICE_NAME.service"
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME"
if [[ "$INSTALL_ONLY" == true ]]; then
echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME"
+9 -7
View File
@@ -110,6 +110,8 @@ copy_source_asset() {
say "Installation de Heimdall Central (serveur + PostgreSQL)."
destination="$(ask 'Dossier d’installation' "$HOME/heimdall")"
compose_project="$(ask 'Nom isolé du projet Docker Compose' 'heimdall')"
[[ "$compose_project" =~ ^[a-z0-9][a-z0-9_-]{0,62}$ ]] || { echo 'Nom de projet Compose invalide.' >&2; exit 1; }
compose_path="$destination/docker-compose.yml"
env_path="$destination/.env"
is_existing=no
@@ -125,7 +127,10 @@ if [[ -e "$compose_path" || -e "$env_path" ]]; then
is_existing=yes
else
web_port="$(ask 'Port HTTP du serveur' '5000')"
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')"
public_origin="${HEIMDALL_URL:-}"
cors_default=''
if [[ "$public_origin" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?$ ]]; then cors_default="$public_origin"; fi
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' "${cors_default:-https://heimdall.invalid}")"
[[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; }
[[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; }
fi
@@ -186,8 +191,6 @@ fi
compose_tmp="$(mktemp "$destination/.docker-compose.yml.XXXXXX")"
trap 'rm -f "${compose_tmp:-}"' EXIT
cat > "$compose_tmp" <<'COMPOSE'
name: heimdall
services:
postgresql:
image: postgres:17-alpine
@@ -257,11 +260,10 @@ secrets:
networks:
heimdall-net:
name: heimdall-net
driver: bridge
COMPOSE
chmod 600 "$compose_tmp"
docker compose --env-file "$env_path" -f "$compose_tmp" config --quiet
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_tmp" config --quiet
if [[ "$is_existing" == yes ]]; then
backup_path="$compose_path.bak.$(date -u +%Y%m%dT%H%M%SZ)"
cp -p "$compose_path" "$backup_path"
@@ -291,7 +293,7 @@ say "Variables protégées dans $destination/.env (mode 600), secret PostgreSQL
say "Validation du Compose avant démarrage…"
start_core=no
if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
docker compose --env-file "$env_path" -f "$compose_path" up -d
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_path" up -d
start_core=yes
fi
@@ -322,7 +324,7 @@ for service in "${selected[@]}"; do
;;
esac
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
docker compose --project-directory "$compose_project_directory" --project-name "heimdall-${service}" \
docker compose --project-directory "$compose_project_directory" --project-name "${compose_project}-${service}" \
--env-file "$destination/.env" \
-f "$destination/optional/docker-compose.${service}.yml" up -d
else
+33
View File
@@ -33,6 +33,28 @@ For Linux systemd installs, preserve the site display name through the existing
foreground installer may pass `Agent__AgentName` directly; do not put arbitrary
site names in an unescaped systemd `Environment=` assignment.
Linux enrollment values must be passed to `install/install-agent.sh` using
`--central-url-file` and `--site-token-file`, each pointing to a regular file
with no group/other permissions. Reject legacy `--central-url` and
`--site-token` values because they are visible in process listings. The site
token is persisted only in root-owned and Agent-owned mode-0600 credential
files and loaded by systemd `LoadCredential`; generated command text must not
contain either enrollment value. Keep the temporary prompt files mode 0600 in
a mode-0700 directory and remove them on every exit path. Verify generated
Linux command text has no Central URL or site token, both legacy value flags
fail before installation, and unsafe/symlink/empty files are rejected.
Keep the Central URL out of process arguments and unit contents. The Linux
installer stores it in the Agent release's `appsettings.json` with mode 0640
inside the mode-0750 Agent release tree; a new Agent may alternatively load it
from a systemd `central-url` credential through `CREDENTIALS_DIRECTORY`.
Agent logs must not include the Central URL.
The server installer Compose project/network must use Compose's project-scoped
resource names rather than fixed global `name:` values. The interactive
installer should default CORS to the configured public HTTPS origin when one
is supplied and otherwise use a restrictive placeholder that the operator
must replace; do not default a new installation to wildcard CORS.
Before accepting a native or Docker install flow, verify that Central's global
`updates.forgepublicurl` contains only the HTTPS public Forgejo origin and that
Central constructs `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` from
@@ -41,6 +63,17 @@ contain the signed manifest, asset checksums, and required image digest. A
`main` Docker image build alone cannot supply the signed Agent release metadata
used by installers and the IHM.
Forgejo releases may omit the optional `asset.digest` API field. In that case,
Central may fetch the public key, manifest, and signature only from HTTPS URLs
on the configured Forgejo origin, then must verify the ECDSA P-256 signature,
release tag, manifest schema, archive SHA-256 values, and image digests before
returning metadata. Use the hashes from the verified signed manifest for
downloadable archives. Reject cross-origin asset URLs, redirects to another
origin, bad signatures, malformed digests, and tag mismatches. Do not replace
missing API digests with unchecked archive metadata or disable verification.
Validate both an actual release whose API omits `asset.digest` and synthetic
tampered metadata in a source-built Compose acceptance.
## Linux rollback simulation
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
+3 -1
View File
@@ -15,6 +15,8 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files.
- Preserve the entire Data Protection ring and `dp-cert.pfx` together. Expired keys can still be required to unprotect stored payloads; never replace/delete one file as part of a restore. Heimdall has no validated manual rotation process for the certificate that protects the ring at rest; keep certificate rotation separate until tested against existing payloads. See `docker/backup/README.md`.
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
- The scheduled backup Compose installs Alpine `aws-cli`, `bash`, and GNU `coreutils`; it does not install MinIO Client (`mc`). `backup-rustfs.sh` uses `aws s3 sync` in this shipped container and only selects `mc mirror` when `mc` is already present in a customized environment. Keep `docker/backup/README.md` aligned with this effective default and never document a retired `mc` download as an installer step.
- The scheduled Compose sets `TZ` to `Europe/Paris` by default. Cron times in `docker-compose.backup.yml` use the container timezone, while scripts use UTC for archive timestamps and retention cutoffs. Document both clocks separately and describe any changed `TZ` as an operator configuration, not as UTC scheduling.
- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume.
## Acceptance
@@ -24,7 +26,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. For actual RPO/RTO drills, use the timestamp, resource, host, and repeated-run procedure in `docker/backup/README.md` and record the operator-approved target separately.
5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p <name> down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files even on a failed assertion. These fixtures use upstream PostgreSQL/RustFS images and build no local image unless a recipe change explicitly adds one; retain those upstream images. If adding a local build, record its unique tag and remove/verify that exact tag in the same trap after teardown. Never use `--rmi all` or broad prune commands.
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation.
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox), not MinIO Client. `backup-rustfs.sh` therefore uses `aws s3 sync`; its `mc mirror` branch is only a fallback when a customized image already provides `mc`. Do not rely on the retired MinIO client download URL. The AWS CLI path passes configured S3 credentials explicitly for each invocation.
7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed.
8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data.
+2
View File
@@ -7,6 +7,8 @@ description: Implement and validate Heimdall user-to-camera grants and group cam
Camera visibility is the union of direct camera grants, site-wide grants, legacy user site assignments, and cameras granted to groups the user belongs to. Keep that union in `CameraAccessService` and `ResourceAccess`; do not reimplement partial scope rules in controllers or UI queries. Site and camera resource checks must continue to run at API/application boundaries, including snapshots, events, hubs, and agent assignment.
When editing authorization examples in `docs/auth-roles.md`, verify routes against the actual controller mappings and explain the query/service-level access filtering. Human JWTs carry role/permission and session claims, not a frozen list of site IDs; do not describe a global `SiteScopeMiddleware` unless one is implemented.
Manage group-camera membership through the authenticated `api/groups/{groupId}/cameras` endpoints. The administration page loads all sites and their cameras with bounded paging, displays site names beside cameras, and adds/removes grants through the API. Treat failed loads and mutations as errors; do not optimistically report success.
When changing this area, verify:
+7 -1
View File
@@ -43,10 +43,16 @@ For installer, Compose, image, and documentation work that can proceed independe
- When a newer Compose needs an absent env key, append a generated secret or documented default only if that key is missing. Never print secret values. Refuse to continue if the existing database URL or password file needed by PostgreSQL is missing.
- If the user declines the Compose refresh, exit without changing the install. If only part of an install is present, stop and explain what is missing instead of creating a second set of credentials.
## Live Linux deployment evidence
For an explicitly authorized host validation, inspect existing services and data before mutation, use only that environment's protected credentials, and scope reset to the named Heimdall Compose projects. Install Central and Agent through the released `.sh` installers. Record image digest, Agent version/identity/site association, `/healthz`, local Agent version endpoint, heartbeat status, credential modes, listener bindings, and sanitized logs. Restart Central and Agent and verify health and persisted volumes/site identity. Do not infer Windows, GPU, camera, multicast, TURN, backup, or long-load acceptance from a single Linux host.
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the corresponding `:latest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use their corresponding immutable `repository@sha256:digest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. A signed Agent manifest always requires the CPU image repository and digest; GPU image metadata is optional for CPU-only releases, and must be present as a valid repository/digest pair when either field is supplied. Unit tests cover CPU-only and CPU+GPU signed manifests plus a malformed half-pair. Source-built Compose acceptance probes Central's latest-release API against the configured public Forgejo source and verifies the returned signature and required CPU digest; record whether the current release also carries GPU metadata. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup.
- The Site Install UI must retain the CPU/GPU image digest returned by Central and generate immutable `repository@sha256:digest` references for both Compose and Docker Run. Never reduce a verified release image to a mutable `:latest` tag. Test with distinct CPU/GPU digests and reject malformed/missing digest values by disabling Docker install generation.
@@ -0,0 +1,12 @@
---
name: dependency-security-acceptance
description: Update vulnerable NuGet dependencies and prove Heimdall's locked dependency security gate.
---
# NuGet dependency security acceptance
Before changing a dependency after a CI advisory failure, read `AGENTS.md`, `skills/gitea-ticket-workflow/SKILL.md`, and the relevant component skill. Reuse or create a focused Gitea issue before editing; record the advisory IDs, resolved package version, failing CI run, and any behavior changes announced by the upstream fix. Do not suppress an advisory or weaken `scripts/ci/security.sh` thresholds.
Update the direct `PackageReference` to an upstream patched release, then regenerate every affected `packages.lock.json` using the SDK pinned by `global.json`. Inspect all projects that transitively reference the package, run `dotnet restore --locked-mode`, and run focused tests for the consuming application. Review upstream release notes for compatibility changes and add or adjust regression coverage if the changed behavior reaches Heimdall code.
Acceptance requires a clean locked restore, passing focused tests, and `scripts/ci/security.sh dependencies` reporting no applicable high or critical advisories. Keep the issue and linked PR open until those checks and the required CI run pass. Document the CI run and exact package version in Gitea without copying credentials or sensitive build output. No disposable Compose project is needed for a library-only dependency update that does not change deployment behavior; when the dependency changes runtime or deployment behavior, also follow `skills/compose-disposable-recipe/SKILL.md`.
@@ -9,10 +9,15 @@ Read `AGENTS.md`, the linked Gitea issue, `docs/docker-compose.md`, and the rele
## Project-specific documentation checks
- Treat `docs/implementation.md` as a July 2026 historical MVP archive in its entirety. Do not use its old phase statuses, paths, commands, endpoint tables, or counts as current guidance; direct readers to the current focused docs and use Gitea issues for live status.
- When changing document structure, section numbering, or a product status summarized in `docs/specs.md`, verify the entry points in `docs/README.md`: every section/document reference must resolve, and summary wording must preserve optional, partial, and externally unvalidated states.
- Central production is PostgreSQL plus Heimdall Web. The development Compose builds Central from source; the interactive Linux/Windows installers create deployment files without cloning the repository.
- Production Agent Compose is generated in Central for the selected site and pins the image digest. The repository's Agent Compose files are development or optional hardware overlays only.
- Recording quota is configured through `RECORDING_STORAGE_QUOTA_MAX_BYTES`; absent an override, Central uses 1 TiB.
- The Central image installs Tesseract plus English language data. `PLATE_OCR_ENABLED` is mapped to `PlateOcr__Enabled` by the development and production Compose files and both Linux/Windows installer templates. New installs default it to false; upgrades preserve an existing value and add false if absent. If documented, explain that OCR is an operator-uploaded crop processed locally, not automatic video detection or face recognition; mention temporary crop deletion and that OCR candidates do not establish identity.
- Recording status must be traced across `AgentRecordingService` (primary RTSP stream, local MP4 segment spool, Central API upload), `RecordingsController`/Application storage, and the camera detail playback UI. Do not say recording is missing or that the Agent writes directly to S3; distinguish implemented code from real-camera/deployment validation.
- Live relay source tracking uses `AgentCameraConfig.EffectiveRtspUrl` (configured substream, otherwise primary RTSP). After a source change, `LiveCameraRelayService` stops and disposes the old FFmpeg process before starting the new source; do not retain the former renewal-delay caveat after issue #355.
- The current PWA baseline includes a manifest, bounded service worker, and static offline page. Web Push backend/client and offline business screens are not implemented; use `docs/pwa.md` for device and deployment validation status.
- The scheduled backup service installs AWS CLI, Bash, and GNU coreutils. The backup scripts select AWS CLI in this image and use S3-compatible configuration; do not instruct operators to download the retired MinIO `mc` URL.
- Optional Compose projects depend on the documented external core network and, where stated, the Central data volume. Do not describe an optional service as part of required startup.
+2
View File
@@ -10,6 +10,8 @@ Use this skill when changing ONNX Runtime packages, execution provider configura
## Project-specific workflow
- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. CUDA support is opt-in through `docker/Dockerfile.agent.gpu`, `docker/docker-compose.agent.dev.gpu-nvidia.yml`, and a separately signed release image manifest.
- Keep the GPU summary in `docs/README.md` aligned with `docs/gpu-runtime.md`: the default Agent remains CPU-only, an optional signed NVIDIA/CUDA amd64 image is published, and physical CUDA execution remains unvalidated until exercised on compatible hardware. Do not collapse these states into “published inference is CPU-only” or imply hardware validation from package/image publication.
- Keep technical-spec summaries consistent with `AgentOptions`, `AnalysisMode`, ONNX provider selection, and `docs/gpu-runtime.md`: distinguish CPU-default inference and optional NVIDIA/CUDA inference from GPU inventory and FFmpeg media handling. AMD/Intel device visibility or detected NVENC/QSV/VAAPI capability is not evidence that ONNX inference or a media pipeline uses those accelerators. Treat remote broker mode as configurable behavior, not a validated inter-site deployment; do not publish throughput estimates without reproducible measurements and hardware/method details.
- Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access.
- Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies:
+2
View File
@@ -7,6 +7,8 @@ description: Diagnose and recover Heimdall startup from transient Hangfire Postg
Heimdall registers all recurring jobs synchronously after database migrations in `src/Heimdall.Web/Program.cs`. Hangfire's PostgreSQL storage acquires a distributed lock per recurring-job id during `AddOrUpdate`; `agent-failover` is currently the first registration after removing the legacy `heartbeat-monitor` id.
The Central dashboard route is mapped from the same Program.cs with `MapHangfireDashboard("/hangfire", ...)`, guarded by `HangfireAdminAuthorizationFilter` for `Admin.Jobs` or the Admin role, and omitted in `Testing`. When updating `docs/hangfire-usage.md`, verify the route and filter against these sources; do not copy a stale `UseHangfireDashboard` or `/admin/jobs` example.
## Implementation and diagnosis
- Inspect the GlitchTip event stack, app start time, event timestamps, and `Program.cs`/`JobSetup.cs` line references. A timeout names the contended job key; it proves lock contention, not the number or identity of competing processes.
+2
View File
@@ -13,6 +13,8 @@ For persistence changes, inspect the entity configuration and latest migration,
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
When updating the domain model summary in `docs/specs.md`, verify entity and property names against `Domain/Entities` and `Domain/Enums`. The site registration token is persisted only as `RegistrationTokenHash` plus its expiry; never describe a stored plaintext token. Distinguish the `CameraEvent` type from conceptual event wording, and `Person` from its related `KnownFace` embeddings.
For application commands, validate at the boundary, enforce site/camera scope in the use case, and make external side effects retry-safe. For agent work, account for disconnected operation, bounded queues, cancellation, and resource disposal.
After the change, run the smallest meaningful test suite plus the build when public contracts change. Update the issue with what passed and what still requires a deployed runner, camera, network, or object store. Link it from the PR and close it only when all acceptance criteria are verified.
+6
View File
@@ -7,6 +7,12 @@ description: Implement and review Heimdall account, password, session, email con
Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md), and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
When maintaining `docs/auth-roles.md` or identity summaries in `docs/specs.md`, verify their role names and default permission summaries against `Infrastructure/Security/AppPermissions.cs` and `Domain/Enums/UserRole.cs`. Heimdall has `Admin`, `Supervisor`, and `Viewer`; site/camera access is separately enforced through resource-access services, not represented by a generic `User` role. Keep the authentication summary in `docs/README.md` aligned with that guide and model.
Verify identity model examples against `Infrastructure/Identity/IdentityAppUser.cs`, `Domain/Entities/UserSite.cs`, and `Infrastructure/Data/Configurations/UserSiteConfiguration.cs`. Keep ASP.NET Identity in Infrastructure; `UserSite` stores the user ID without an Identity navigation, and Infrastructure maps that foreign key.
Before documenting UI/API authorization examples in `docs/auth-roles.md`, verify referenced pages, methods, policies, and routes against `Components/Routes.razor`, the page components, controllers, and `ResourceAccess`. Do not preserve generic authorization snippets that reference services or callbacks absent from the application; distinguish page authentication from API resource filtering.
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
+4
View File
@@ -7,6 +7,10 @@ description: Implement and accept the authenticated Heimdall in-app notification
The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser.
When documenting delivery channels in `docs/notifications.md` or its summary in `docs/specs.md`, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. Remove obsolete channel integrations, editor flows, and test claims from `docs/notifications.md` and `docs/specs.md`; if a historical example must remain, label that exact heading/table/snippet locally rather than relying on a broad notice elsewhere in the guide. When the notification guide’s scope or delivered status changes, update both notification summaries in `docs/README.md` to match it.
When legacy notification designs remain in `docs/MASTER_SPECIFICATION.md`, put a local dated historical/non-shipped note beside each section, queue example, or UI mockup, and link to `docs/notifications.md`. A document-level historical header alone is not sufficient for Gotify or template-editor claims.
## Acceptance
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.
+1
View File
@@ -16,6 +16,7 @@ The Linux and Windows server installers save service secrets in `<install-root>/
## coturn
- Coturn is an optional live-view relay consumed by Central through `LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns short-lived TURN REST credentials to the browser; the shared secret stays server-side. Keep this service optional and do not describe its integration as future or external-only.
- Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`.
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
+1 -1
View File
@@ -27,7 +27,7 @@ Heimdall's connected Penpot file is part of the UI source of truth. Whenever a c
## Installer design reference
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation from the `latest` image tag, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation pinned to the immutable signed `repository@sha256:digest`, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
## Acceptance evidence
+25
View File
@@ -0,0 +1,25 @@
---
name: sentry-telemetry-privacy
description: Keep Heimdall Sentry events free of authentication material while preserving safe diagnostic metadata.
---
# Sentry telemetry privacy
Sentry event and transaction processing are configured in `src/Heimdall.Web/Program.cs`. `SetBeforeSend` and `SetBeforeSendTransaction` are separate SDK callbacks, so apply `SentryTelemetryPrivacy` to both. Before either payload is sent, filter request `Headers`, `Env`, and `Other` maps; remove request/response cookies, query strings, and bodies; strip URL user information; and filter sensitive values in event extras, transaction contexts, tags, spans, and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application.
When changing this behavior:
- Add focused tests under `tests/Heimdall.Web.Tests/Security/` using synthetic `SENTINEL_` values only. Serialize final events and transactions through the Sentry SDK serializers and assert no sentinel survives. Also assert safe diagnostic metadata remains.
- Treat header names case-insensitively and normalize common separators before matching names that indicate authorization, API keys, tokens, secrets, passwords, credentials, or cookies.
- Clear entire fields such as cookie strings, query strings, and request bodies when selective redaction could miss nested or encoded credentials. Strip URL user information, query, and fragment while retaining the safe path.
- Apply the same sensitive-key filtering to event extras and breadcrumbs. Preserve the existing rate-limit breadcrumb filter.
- Recursively inspect string-keyed maps in extras and custom contexts. Replace arrays, other collections, and opaque object graphs with `[Filtered]` instead of allowing uninspected JSON serialization; retain safe primitive values and safe map entries.
- Filter sensitive-name tags on both `SentryEvent` and `SentryTransaction`; sanitize trace custom data, response headers, and span data/tags.
- Include synthetic request `env`/`other`, sensitive event tags, nested maps, arrays, and opaque values in serializer-level tests.
- Never copy actual event headers, API keys, cookies, tokens, or request bodies into issue comments, test fixtures, logs, or acceptance evidence. Record only field names and synthetic test outcomes.
## Acceptance
Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Its `EXIT` trap disables inherited `errexit`/`nounset` while attempting each independent cleanup step, preserves the original test status, and reports cleanup failures. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR.
This proves local sanitization logic and event/transaction payload handling only. It does not claim a live Sentry/GlitchTip delivery or rotate any external credential.
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
project="heimdall-sentry-privacy-${suffix}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
compose_file="$temp_dir/compose.yml"
props_file="$temp_dir/acceptance.props"
local_image_tags=()
cleanup() {
status=$?
trap - EXIT
# Cleanup must continue through every independent resource even when the
# caller enabled errexit/nounset or an earlier Docker query failed.
set +e
set +u
cleanup_failed=0
docker compose --project-directory "$repo_root" --env-file "$env_file" \
-f "$compose_file" -p "$project" down --volumes --remove-orphans || cleanup_failed=1
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" ]]; then
while IFS= read -r container; do
[[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1
done <<< "$containers"
fi
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
cleanup_failed=1
else
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
fi
if ((${#local_image_tags[@]} == 0)); then
printf 'Local images built: none; upstream SDK image retained.\n'
fi
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Recipe image remains: %s\n' "$tag" >&2
cleanup_failed=1
else
printf 'Verified recipe image absent: %s\n' "$tag"
fi
done
rm -f -- "$env_file" "$compose_file" "$props_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if ((cleanup_failed)); then
printf 'Disposable Sentry privacy acceptance cleanup failed for %s\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
cat > "$env_file" <<EOF
REPO_ROOT=$repo_root
ACCEPTANCE_PROJECT=$project
ACCEPTANCE_DIR=$temp_dir
ACCEPTANCE_UID=$(id -u)
ACCEPTANCE_GID=$(id -g)
EOF
cat > "$props_file" <<'EOF'
<Project>
<PropertyGroup>
<BaseIntermediateOutputPath>/tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/</BaseIntermediateOutputPath>
<MSBuildProjectExtensionsPath>/tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/</MSBuildProjectExtensionsPath>
<BaseOutputPath>/tmp/$(ACCEPTANCE_PROJECT)/bin/$(MSBuildProjectName)/</BaseOutputPath>
<DefaultItemExcludes>$(DefaultItemExcludes);**/obj/**;**/bin/**</DefaultItemExcludes>
</PropertyGroup>
</Project>
EOF
cat > "$compose_file" <<'EOF'
services:
focused-tests:
image: mcr.microsoft.com/dotnet/sdk:10.0
entrypoint: ["dotnet"]
user: "${ACCEPTANCE_UID}:${ACCEPTANCE_GID}"
working_dir: /workspace
environment:
ACCEPTANCE_PROJECT: ${ACCEPTANCE_PROJECT}
volumes:
- ${REPO_ROOT}:/workspace
- ${ACCEPTANCE_DIR}:/acceptance
command:
- test
- tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj
- --filter
- FullyQualifiedName~SentryTelemetryPrivacyTests
- --verbosity
- minimal
- -p:RestoreLockedMode=true
- -p:CustomBeforeDirectoryBuildProps=/acceptance/acceptance.props
EOF
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
docker compose --project-directory "$repo_root" --env-file "$env_file" \
-f "$compose_file" -p "$project" config --quiet
docker compose --project-directory "$repo_root" --env-file "$env_file" \
-f "$compose_file" -p "$project" run --rm focused-tests
+4
View File
@@ -8,6 +8,8 @@ description: Keep Heimdall container health probes aligned with the HTTP methods
Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing.
- Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy.
- When documenting health status, compare each summary with the registered check names/tags, endpoint filters, and HTTP status mapping in Web and Agent. Web `/healthz` is liveness (`200`), `/readyz` checks the `ready` PostgreSQL and selected-storage dependencies (`200` only when healthy, otherwise `503`), and `/health/live` selects the `live` PostgreSQL and optional configured AI backend check (`503` when degraded). Agent `/healthz` runs its registered checks (`Degraded` maps to `200`, `Unhealthy` to `503`); `/health/live` selects only the Agent pipeline-degradation check (`503` when degraded). Do not claim a Central broker health check unless one is registered.
- Ollama is optional; its URL can be configured in Central settings, the admin connectivity action can ping it, and `AiHealthCheck` probes `/api/tags`. That endpoint check proves availability only, not model inference or summary generation. Do not document LLM-generated summaries until a production caller for a model generation/chat API is implemented.
- In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD.
- Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required.
- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Install an EXIT cleanup trap before build/start. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy. In cleanup remove only that project with `down --volumes --remove-orphans`, verify no labeled containers/volumes/networks remain, remove and inspect each exact local image tag even on failure, and retain shared base images. Preserve the test exit status and report cleanup failures.
@@ -16,6 +18,8 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal
For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward.
When updating implementation-status documentation, verify both `src/Heimdall.Web/Program.cs` and `src/Heimdall.Agent/Program.cs` for exporter registration and `/metrics` mapping, then compare the documented signal inventory with `docs/metrics.md` and example alert rules with `deploy/prometheus/heimdall-alerts.yml`. Mark exporter implementation separately from an operator's Prometheus scrape, deployed alerting, or threshold validation; local or CI evidence does not establish those external states.
On 5 November 2026, project hmd-metrics-scrape-1793874584 reused the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This is a partial Docker recipe result: it did not build a unique image for this scrape, so no exact-tag image removal was performed. Repeat the check with a fresh project-unique source-built tag before treating the Docker acceptance as complete. This local check does not validate a deployed Prometheus server or alert thresholds.
PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched.
+2
View File
@@ -28,4 +28,6 @@ Use this skill when changing a hub, SignalR authentication, subscription handlin
7. Link the focused tests and distinguish unit/CI evidence from proxy, network or deployment validation.
8. Review `docs/signalr-usage.md` for unsupported event names, copied pseudocode, stale security claims, and missing limits on delivery/replay.
When the SignalR or live-view summary in `docs/MASTER_SPECIFICATION.md` changes, treat that file's dated architecture sections as historical unless verified against the mapped routes and current media path. Keep the mapped hub list exact, do not describe a planned hub or peer-to-peer media path as shipped, and link readers to `docs/signalr-usage.md` and `docs/docker-compose.md` for current contracts and deployment guidance. If retaining superseded material, put a historical-status note immediately before each affected diagram, roadmap phase, UI mockup, or target-results block; a header-only disclaimer is insufficient for those detailed examples.
Do not add runtime behavior in a documentation-only change. If the audit reveals a behavior defect, create a separate Gitea issue before implementation and keep the documentation explicit about the current state.
+2 -1
View File
@@ -11,8 +11,9 @@ Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.r
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, but install the corresponding published `:latest` image. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, and install the corresponding immutable `repository@sha256:digest` reference. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
- The Linux generated installer command must not embed Central URL or site token in its text or process arguments. Prompt for both at execution time, hide token input, use protected temporary files and the installer's file-based flags, and clean those files on all exits.
- For live installer verification, use the authenticated Orca browser session. Check for the dedicated Heimdall login only in the user secret store at `~/.config/heimdall/credentials.json`; never put account passwords in this skill, repository config, shell arguments, or Orca `fill` commands. The file fallback is owner-only (`0700` directory, `0600` file) and base64-encoded, not encrypted. If it is absent, provide the user-run masked helper `~/.local/bin/store-heimdall-credentials`; do not report the credentials as persisted until that helper succeeds. If Orca has no safe autofill path, ask the user to enter the password in the visible browser.
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
- Match Pangolin's control hierarchy and compact copy affordance while using Heimdall's MudBlazor theme and supported installation choices. Keep selection and copy feedback accessible with selected styling, tooltips/aria labels, and a check icon after copying.
+2
View File
@@ -9,6 +9,8 @@ Heimdall renders its root `Routes` component in an interactive server circuit wi
The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component.
When maintaining route documentation or the UI summary in `docs/specs.md`, verify current routes against the Razor `@page` directives and point detailed inventories to `docs/ui-pages.md` instead of copying a hard page count. Also check route examples in navigation and authorization guides against the current layout links and their visibility conditions. Mark removed mockups as historical and link to the replacement pages; do not preserve a retired route such as `/admin` as if it were still mapped.
## Acceptance workflow
1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response.
+1
View File
@@ -72,6 +72,7 @@ the current implementation:
`src/Heimdall.Web/Components/Pages/CameraDetail.razor`; the browser module is
`src/Heimdall.Web/wwwroot/js/live-view.js`. Do not document a separate
`/cameras/{id}/live` route or rename the module to `liveView.js`.
- When documenting role visibility in `docs/auth-roles.md`, use the camera detail route for the embedded live-view and trace session permission to `LiveMediaController`; the endpoint requires `Camera.Read` plus camera-level access, not a separate `Camera.Live` endpoint policy.
- Session creation/release, authorization, short-lived tickets, WHEP URL and
ICE configuration are in `src/Heimdall.Web/Controllers/LiveMediaController.cs`.
- Agent RTSP publication and FFmpeg lifecycle are in
+9 -1
View File
@@ -14,7 +14,15 @@ public sealed class AgentOptions
/// <summary>URL of the Heimdall Central server, supplied by the installation or deployment configuration.</summary>
[Required, Url]
public string CentralUrl { get; init; } = string.Empty;
public string CentralUrl
{
get => string.IsNullOrWhiteSpace(_centralUrl)
? ReadSystemdCredential("central-url") ?? string.Empty
: _centralUrl;
init => _centralUrl = value ?? string.Empty;
}
private string _centralUrl = string.Empty;
/// <summary>Allow an unencrypted HTTP Central URL for isolated development networks only.</summary>
public bool AllowInsecureHttp { get; init; }
@@ -171,7 +171,7 @@ public class AgentRegistrationService : BackgroundService
throw new InvalidOperationException(
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
_logger.LogInformation("Registering agent with Central.");
var maxRetries = _options.RegistrationMaxRetries;
RegisterResponse? registration = null;
+3 -3
View File
@@ -91,8 +91,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.IdentityModel.JsonWebTokens": "8.14.0"
}
@@ -326,7 +326,7 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
+5 -301
View File
@@ -39,8 +39,6 @@
"resolved": "10.0.13",
"contentHash": "sk3VNcYEmgwYGPF4ze/112jpaeDKSsKGhmEZ8IlhOR8F6JT+1DYaZUb14jobVXiKhuXWIKcYXV7mkSPeA4dc3g==",
"dependencies": {
"Microsoft.Extensions.Hosting": "10.0.13",
"Microsoft.Extensions.Logging.EventLog": "10.0.13",
"System.ServiceProcess.ServiceController": "10.0.13"
}
},
@@ -91,8 +89,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.IdentityModel.JsonWebTokens": "8.14.0"
}
@@ -133,14 +131,6 @@
"resolved": "10.0.13",
"contentHash": "r9hlU+te+QWFJlUCt2C22TDKY3oMER8ayC7Qzeq6yJ5toHBKcSqshhyyaLKK1jgBuyNi4ejly0wE8ANV8TyfWQ=="
},
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13"
}
},
"Microsoft.AspNetCore.SignalR.Client.Core": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -202,290 +192,11 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.CommandLine": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "RwdNZ9JdGs8eZmeL5qRe7ugp0Irk3KVkWpC/w1c8kjJwu1R4HvCXYz9kwHZxn45WiaRBG5lphQKtqnBaJOQC+Q==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.EnvironmentVariables": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qJK2dm9/AxyPVfqqBaZtjkUFl2hnBR/CQnMJtSO5LdEoyATMqvZjeQVY+8l0oa6PM6qlVe28iMEyXIRQ0wyZjA==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.FileExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "kwC1DY55CsqPmDtJAz+7alD3G+gJcM+XwHSZrcRO8mJGYB9hRq1qC6ZH8DL0SPW9WtJ/Bae5ikzPic8SxSv6Vw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Json": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "acCWM2+WR67kBAz6gAhD2zG+IZH9Q2VpKv5le7Msiu0vAMsnnLXpnV3BAzxd8/i+uOEo/dfb2XRYTynRVTDvEg==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.UserSecrets": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "kQ/Tx972unP+ueQL8SSninthIj6w6XP2o0VnJPFC5HQIimPMwEN704MOspEgDkmm4FUL5SuxLEU0bNiW4HEZFA==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Json": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.FileProviders.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.FileProviders.Physical": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "U7HkgGCNPICN5k7NVK6dmLsSPSPeO/EbNcuxOl/5qdC9Ahjp9UZWKOvlnUC+rYurmoxIlwyv9e5j0BaQlTOELA==",
"dependencies": {
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileSystemGlobbing": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.FileSystemGlobbing": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "vQVzmAbnzlhXSXA2caYnlxtG9GXxEwtj5bODiWLu06A6iqeJmfBtlfKjuOSJGRy0/CFaNUrm7u9nxEUlljc2Rg=="
},
"Microsoft.Extensions.Hosting": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "Q+hmPoDqeHipHyJcY7mDCQiLDUcn9jIgjoCThcgaOgjLTTT3ApTe8p6M2+twsDyfKuuCsKhSNlnNjaaggtXxRA==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.Configuration.CommandLine": "10.0.13",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.13",
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.13",
"Microsoft.Extensions.Configuration.Json": "10.0.13",
"Microsoft.Extensions.Configuration.UserSecrets": "10.0.13",
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13",
"Microsoft.Extensions.Hosting.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Configuration": "10.0.13",
"Microsoft.Extensions.Logging.Console": "10.0.13",
"Microsoft.Extensions.Logging.Debug": "10.0.13",
"Microsoft.Extensions.Logging.EventLog": "10.0.13",
"Microsoft.Extensions.Logging.EventSource": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Hosting.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Console": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "i9rn0rHkiCxfNVbf4DRG7LOFcKPy/BioAxS07w6daWvIpLNRjskqDJcGGaYVFWndsq0iTRaS8Msry0t5fRYQug==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Configuration": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Debug": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yBig0DNMq+3UgliwxYlUC48dg0fPqvqI5B3ljzmLTrpR6maoKTOO5i9QnPgQUmQoaQWZMgu74fuF6oSDihb6pg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.EventLog": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "OAK40lXhgMuvyNwvzW3fxLvvucN8yr5XS7dQRcPmtnPf+Pt1lpbMgao5T4Wa6VdFagtIeDZNgPtV5Ig4xstziQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"System.Diagnostics.EventLog": "10.0.13"
}
},
"Microsoft.Extensions.Logging.EventSource": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "SxJu3oczk+TJtHvpgAmCVzEkzx69/obA6GZCbGrbqYqc981YOAyfEprySBdFX7Yc5qatHJKHNTlpGeeBAQkZcA==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA=="
},
"Microsoft.IdentityModel.Abstractions": {
"type": "Transitive",
"resolved": "8.14.0",
@@ -584,11 +295,6 @@
"SQLitePCLRaw.core": "3.0.5"
}
},
"System.Diagnostics.EventLog": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "DkNjtQyPR5Ud/zHnWHdsOuKbFRL9nIC92Q76z0NmHVDoQm40toLtsGFTIWq7toBoVa6fo/DInL3PLxY3Asixyw=="
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
@@ -602,12 +308,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -620,8 +325,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -632,4 +336,4 @@
}
}
}
}
}
@@ -5,7 +5,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="AutoMapper" Version="16.3.0" />
<PackageReference Include="FluentValidation" Version="11.11.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
<PackageReference Include="MediatR" Version="12.5.0" />
+3 -3
View File
@@ -4,9 +4,9 @@
"net10.0": {
"AutoMapper": {
"type": "Direct",
"requested": "[16.1.1, )",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"requested": "[16.3.0, )",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -145,8 +145,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -791,12 +791,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -806,8 +805,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -113,6 +113,10 @@ else if (_method == "docker-run")
</MudTooltip>
</MudPaper>
}
@if (_method is "linux-run" or "linux-systemd")
{
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_LinuxSecretPrompt"]</MudAlert>
}
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
@@ -244,12 +248,8 @@ else if (_method == "windows-service")
!string.IsNullOrWhiteSpace(release?.SignedManifest) &&
!string.IsNullOrWhiteSpace(release?.ManifestSignature) &&
release?.Assets.Count > 0;
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
_agentImageReference = LatestImageReference(release.ContainerImage);
if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) &&
!string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest))
_agentGpuImageReference = LatestImageReference(release.ContainerImageGpu);
_agentImageReference = ImmutableImageReference(release?.ContainerImage, release?.ContainerImageDigest);
_agentGpuImageReference = ImmutableImageReference(release?.ContainerImageGpu, release?.ContainerImageGpuDigest);
_updatePublicKeyPem = release?.UpdatePublicKeyPem;
}
catch
@@ -262,12 +262,14 @@ else if (_method == "windows-service")
}
}
private static string LatestImageReference(string image)
private static string? ImmutableImageReference(string? image, string? digest)
{
var lastSlash = image.LastIndexOf('/');
var lastColon = image.LastIndexOf(':');
var repository = lastColon > lastSlash ? image[..lastColon] : image;
return $"{repository}:latest";
if (string.IsNullOrWhiteSpace(image) || image.Contains('@', StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(digest) || !System.Text.RegularExpressions.Regex.IsMatch(
digest, "^sha256:[0-9a-fA-F]{64}$", System.Text.RegularExpressions.RegexOptions.CultureInvariant))
return null;
return $"{image}@{digest.ToLowerInvariant()}";
}
private string ComposeYaml
@@ -410,15 +412,16 @@ else if (_method == "windows-service")
private string LinuxInstallCommand(bool service)
{
var baseUrl = CentralUrl.TrimEnd('/');
var scriptUrl = ShellQuote(baseUrl + "/install/install-agent.sh");
var supervisorUrl = ShellQuote(baseUrl + "/install/agent-supervisor.py");
var args = $"--central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}";
var args = $"--central-url-file \"$tmp/central-url\" --site-token-file \"$tmp/site-token\" --agent-name {ShellQuote(SiteName)}";
args += service ? " --install-only" : " --run";
return "tmp=$(mktemp -d) && " +
$"curl -fsSL {scriptUrl} -o \"$tmp/install-agent.sh\" && " +
$"curl -fsSL {supervisorUrl} -o \"$tmp/agent-supervisor.py\" && " +
$"sudo bash \"$tmp/install-agent.sh\" {args}; rc=$?; rm -rf \"$tmp\"; exit $rc";
return "set -eu\n" +
"tmp=$(mktemp -d)\nchmod 700 \"$tmp\"\n" +
"cleanup() { rc=$?; trap - EXIT; rm -f \"$tmp/install-agent.sh\" \"$tmp/agent-supervisor.py\" \"$tmp/central-url\" \"$tmp/site-token\"; rmdir \"$tmp\"; exit $rc; }\ntrap cleanup EXIT HUP INT TERM\n" +
"printf 'Central HTTPS URL: '; IFS= read -r central_url\n" +
"printf 'Site enrollment token (input hidden): '; IFS= read -r -s site_token; printf '\\n'\n" +
"umask 077\nprintf '%s' \"$central_url\" > \"$tmp/central-url\"\nprintf '%s' \"$site_token\" > \"$tmp/site-token\"\nunset central_url site_token\n" +
"python3 - \"$tmp\" <<'PY'\nimport pathlib, sys, urllib.request\nroot=pathlib.Path(sys.argv[1])\nbase=(root/'central-url').read_text().rstrip('/')\nif not base.startswith('https://'): raise SystemExit('Central URL must use HTTPS')\nfor name in ('install-agent.sh','agent-supervisor.py'):\n request=urllib.request.Request(base+'/install/'+name, headers={'User-Agent':'Heimdall-Agent-Installer'})\n with urllib.request.urlopen(request, timeout=30) as response:\n if response.status != 200: raise SystemExit('Central installer asset request failed')\n (root/name).write_bytes(response.read())\nPY\n" +
$"sudo bash \"$tmp/install-agent.sh\" {args}";
}
private string WindowsServiceName => "HeimdallAgent-" + Slugify(SiteName)[..Math.Min(60, Slugify(SiteName).Length)];
@@ -131,44 +131,41 @@ public class UpdatesController : ControllerBase
return null;
var release = await ReadForgejoReleaseAsync(response.Content, ct);
if (release is null) return null;
var assets = new Dictionary<string, PlatformAsset>();
foreach (var asset in release.Assets ?? [])
{
var platform = DetectPlatform(asset.Name);
if (platform is null) continue;
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = ExtractSha256(asset.Digest), Size = asset.Size };
}
var result = new LatestReleaseResponse { Version = release.TagName, ReleaseNotes = release.Body, PublishedAt = release.PublishedAt, Assets = assets };
var publicKeyBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-release-public.pem", client, 4096, ct);
if (publicKeyBytes is not null)
{
try
{
var publicKeyPem = System.Text.Encoding.UTF8.GetString(publicKeyBytes);
using var verifier = ECDsa.Create();
verifier.ImportFromPem(publicKeyPem);
if (verifier.KeySize == 256)
result.UpdatePublicKeyPem = publicKeyPem;
}
catch (CryptographicException) { }
catch (ArgumentException) { }
}
var image = await FetchAgentImageManifestAsync(release.Assets, "agent-image.json", client, ct);
result.ContainerImage = image?.Image;
result.ContainerImageDigest = image?.Digest;
var gpuImage = await FetchAgentImageManifestAsync(release.Assets, "agent-image-gpu.json", client, ct);
result.ContainerImageGpu = gpuImage?.Image;
result.ContainerImageGpuDigest = gpuImage?.Digest;
"agent-release-public.pem", client, 4096, sourceUri, ct);
var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-update-manifest.json", client, 1_048_576, ct);
"agent-update-manifest.json", client, 1_048_576, sourceUri, ct);
var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-update-manifest.sig", client, 512, ct);
if (manifestBytes is not null && signatureBytes is not null)
"agent-update-manifest.sig", client, 512, sourceUri, ct);
var publicKeyPem = publicKeyBytes is null ? null : System.Text.Encoding.UTF8.GetString(publicKeyBytes);
if (publicKeyPem is null || manifestBytes is null || signatureBytes is null ||
!AgentReleaseManifestVerifier.TryVerify(publicKeyPem, manifestBytes, signatureBytes,
release.TagName, out var signedManifest) || signedManifest is null)
return null;
var assets = new Dictionary<string, PlatformAsset>();
foreach (var (platform, sha256) in signedManifest.Assets)
{
result.SignedManifest = Convert.ToBase64String(manifestBytes);
result.ManifestSignature = Convert.ToBase64String(signatureBytes);
var asset = release.Assets?.SingleOrDefault(a => DetectPlatform(a.Name) == platform);
if (asset is null || !IsSameHttpsOrigin(asset.BrowserDownloadUrl, sourceUri)) return null;
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = sha256, Size = asset.Size };
}
if (assets.Count == 0) return null;
var result = new LatestReleaseResponse
{
Version = signedManifest.Version,
ReleaseNotes = release.Body,
PublishedAt = release.PublishedAt,
Assets = assets,
ContainerImage = signedManifest.ContainerImage,
ContainerImageDigest = signedManifest.ContainerImageDigest,
ContainerImageGpu = signedManifest.ContainerImageGpu,
ContainerImageGpuDigest = signedManifest.ContainerImageGpuDigest,
UpdatePublicKeyPem = publicKeyPem,
SignedManifest = Convert.ToBase64String(manifestBytes),
ManifestSignature = Convert.ToBase64String(signatureBytes),
};
lock (_cacheLock) { _cache = new LatestReleaseCache(source!, result, DateTime.UtcNow); }
return result;
}
@@ -236,52 +233,19 @@ public class UpdatesController : ControllerBase
statusCode is System.Net.HttpStatusCode.RequestTimeout or System.Net.HttpStatusCode.TooManyRequests ||
(int)statusCode >= 500;
private static async Task<AgentImageManifest?> FetchAgentImageManifestAsync(List<ForgejoAsset>? assets,
string assetName, HttpClient client, CancellationToken ct)
{
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, assetName, StringComparison.OrdinalIgnoreCase));
var expectedSha256 = asset is null ? null : ExtractSha256(asset.Digest);
if (asset is null || !IsSha256Digest(expectedSha256)) return null;
try
{
using var response = await client.GetAsync(asset.BrowserDownloadUrl, HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is > 1_048_576)
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 > 1_048_576) return null;
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
var actualSha256 = Convert.ToHexString(SHA256.HashData(bytes));
if (!string.Equals(actualSha256, expectedSha256, StringComparison.OrdinalIgnoreCase)) return null;
var manifest = JsonSerializer.Deserialize<AgentImageManifest>(bytes, Json);
return manifest is not null && IsValidContainerImageRepository(manifest.Image) && IsValidContainerImageDigest(manifest.Digest)
? manifest
: null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch { return null; }
}
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)
string name, HttpClient client, int maxBytes, Uri sourceUri, 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;
if (asset is null || !IsSameHttpsOrigin(asset.BrowserDownloadUrl, sourceUri) ||
(asset.Digest is not 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)
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes ||
response.RequestMessage?.RequestUri is not { } finalUri || !IsSameHttpsOrigin(finalUri, sourceUri))
return null;
await using var stream = await response.Content.ReadAsStreamAsync(ct);
using var buffer = new MemoryStream();
@@ -294,29 +258,23 @@ public class UpdatesController : ControllerBase
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
return string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected,
return expected is null || 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 '-')
&& !image.Contains('@')
&& !image.Any(char.IsWhiteSpace)
&& !image.Split('/').Last().Contains(':');
private static bool IsSameHttpsOrigin(string candidate, Uri sourceUri) =>
Uri.TryCreate(candidate, UriKind.Absolute, out var candidateUri) && IsSameHttpsOrigin(candidateUri, sourceUri);
private static bool IsValidContainerImageDigest(string? digest) => digest is { Length: 71 }
&& digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& digest[7..].All(Uri.IsHexDigit);
private static bool IsSameHttpsOrigin(Uri candidateUri, Uri sourceUri) =>
candidateUri.Scheme == Uri.UriSchemeHttps &&
string.Equals(candidateUri.Host, sourceUri.Host, StringComparison.OrdinalIgnoreCase) &&
candidateUri.Port == sourceUri.Port && string.IsNullOrEmpty(candidateUri.UserInfo) &&
string.IsNullOrEmpty(candidateUri.Fragment);
private sealed class AgentImageManifest
{
[JsonPropertyName("image")] public string Image { get; init; } = string.Empty;
[JsonPropertyName("digest")] public string Digest { get; init; } = string.Empty;
}
private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
private async Task RefreshCacheAsync(string? source, CancellationToken ct)
{
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Install and run</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>At runtime, enter the Central HTTPS URL and then the site token (token input is hidden). These values are not included in the copied command.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Run</value>
</data>
@@ -4078,7 +4081,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>Docker installation pins the CPU or GPU Agent image to the signed repository@sha256:digest. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Installer et lancer</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>À l’exécution, saisissez l’URL HTTPS de Central puis le token du site (la saisie du token est masquée). Ces valeurs ne sont pas incluses dans la commande copiée.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Lancer</value>
</data>
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Install and run</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>At runtime, enter the Central HTTPS URL and then the site token (token input is hidden). These values are not included in the copied command.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Run</value>
</data>
@@ -4078,7 +4081,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>Docker installation pins the CPU or GPU Agent image to the signed repository@sha256:digest. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
+5 -8
View File
@@ -17,6 +17,7 @@ using Heimdall.Api.Hubs;
using Heimdall.Api;
using Heimdall.Web.Services;
using Heimdall.Web;
using Heimdall.Web.Security;
using Hangfire;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -822,18 +823,14 @@ public partial class Program
options.SetBeforeSend(static (sentryEvent, _) =>
{
sentryEvent.ServerName = null;
if (sentryEvent.Extra?.ContainsKey("password") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("password");
if (sentryEvent.Extra?.ContainsKey("token") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
if (sentryEvent.Extra?.ContainsKey("secret") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("secret");
return sentryEvent;
return SentryTelemetryPrivacy.Sanitize(sentryEvent);
});
options.SetBeforeSendTransaction(static (transaction, _) =>
SentryTelemetryPrivacy.Sanitize(transaction));
options.SetBeforeBreadcrumb(breadcrumb
=> breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting"
? null
: breadcrumb);
: SentryTelemetryPrivacy.SanitizeBreadcrumb(breadcrumb));
}
internal static void ConfigureMiddleware(WebApplication app)
@@ -0,0 +1,230 @@
using Sentry;
namespace Heimdall.Web.Security;
/// <summary>Removes authentication material from request data before error telemetry is sent.</summary>
internal static class SentryTelemetryPrivacy
{
private const string Redacted = "[Filtered]";
internal static SentryEvent Sanitize(SentryEvent sentryEvent)
{
ArgumentNullException.ThrowIfNull(sentryEvent);
SanitizeRequest(sentryEvent.Request);
SanitizeContexts(sentryEvent.Contexts);
foreach (var key in sentryEvent.Tags.Keys.ToArray())
{
if (IsSensitiveName(key))
sentryEvent.SetTag(key, Redacted);
}
if (sentryEvent.Extra is IDictionary<string, object?> extra)
RedactObjectValues(extra);
return sentryEvent;
}
internal static SentryTransaction Sanitize(SentryTransaction transaction)
{
ArgumentNullException.ThrowIfNull(transaction);
SanitizeRequest(transaction.Request);
SanitizeContexts(transaction.Contexts);
RedactObjectValues(transaction.Data, transaction.SetData);
foreach (var key in transaction.Tags.Keys.ToArray())
{
if (IsSensitiveName(key))
transaction.SetTag(key, Redacted);
}
if (transaction.Breadcrumbs is IList<Breadcrumb> breadcrumbs)
{
for (var index = 0; index < breadcrumbs.Count; index++)
breadcrumbs[index] = SanitizeBreadcrumb(breadcrumbs[index]);
}
foreach (var span in transaction.Spans)
{
RedactObjectValues(span.Data, span.SetData);
foreach (var key in span.Tags.Keys.ToArray())
{
if (IsSensitiveName(key))
span.SetTag(key, Redacted);
}
}
return transaction;
}
internal static Breadcrumb SanitizeBreadcrumb(Breadcrumb breadcrumb)
{
ArgumentNullException.ThrowIfNull(breadcrumb);
if (breadcrumb.Data is IDictionary<string, string> mutableData)
{
RedactStringValues(mutableData);
return breadcrumb;
}
var data = breadcrumb.Data?.ToDictionary(
pair => pair.Key,
pair => IsSensitiveName(pair.Key) ? Redacted : pair.Value,
StringComparer.Ordinal);
return new Breadcrumb(
breadcrumb.Message ?? string.Empty,
breadcrumb.Type ?? string.Empty,
data,
breadcrumb.Category,
breadcrumb.Level);
}
private static void RedactStringValues(IDictionary<string, string>? values)
{
if (values is null)
return;
foreach (var key in values.Keys.ToArray())
{
if (IsSensitiveName(key))
values[key] = Redacted;
}
}
private static void SanitizeRequest(SentryRequest? request)
{
if (request is null)
return;
RedactStringValues(request.Headers);
RedactStringValues(request.Env);
RedactStringValues(request.Other);
request.Cookies = null;
request.Url = StripQueryAndUserInfo(request.Url);
request.QueryString = null;
request.Data = null;
}
private static void SanitizeContexts(SentryContexts contexts)
{
RedactObjectValues(contexts.Trace.Data, contexts.Trace.SetData);
RedactStringValues(contexts.Response.Headers);
contexts.Response.Cookies = null;
contexts.Response.Data = null;
foreach (var key in contexts.Keys.ToArray())
{
if (key is "trace" or "response")
continue;
if (IsSensitiveName(key))
contexts[key] = Redacted;
else
contexts[key] = RedactValue(contexts[key])!;
}
}
private static void RedactObjectValues(IDictionary<string, object?> values)
{
foreach (var key in values.Keys.ToArray())
{
if (IsSensitiveName(key))
{
values[key] = Redacted;
continue;
}
values[key] = RedactValue(values[key]);
}
}
private static void RedactObjectValues(
IReadOnlyDictionary<string, object?> values,
Action<string, object?> setValue)
{
foreach (var key in values.Keys.ToArray())
{
if (IsSensitiveName(key))
{
setValue(key, Redacted);
continue;
}
setValue(key, RedactValue(values[key])!);
}
}
private static object? RedactValue(object? value)
{
if (value is IDictionary<string, object?> mutableDictionary)
{
RedactObjectValues(mutableDictionary);
return value;
}
if (value is IReadOnlyDictionary<string, object?> readOnlyDictionary)
{
var sanitized = new Dictionary<string, object?>(StringComparer.Ordinal);
foreach (var pair in readOnlyDictionary)
sanitized[pair.Key] = IsSensitiveName(pair.Key) ? Redacted : RedactValue(pair.Value);
return sanitized;
}
if (value is System.Collections.IDictionary dictionary)
{
var sanitized = new Dictionary<string, object?>(StringComparer.Ordinal);
foreach (System.Collections.DictionaryEntry entry in dictionary)
{
if (entry.Key is not string key)
return Redacted;
sanitized[key] = IsSensitiveName(key) ? Redacted : RedactValue(entry.Value);
}
return sanitized;
}
if (value is System.Collections.IEnumerable and not string)
return Redacted;
// Arbitrary objects may serialize properties containing credentials under unknown names.
// Keep primitive values; discard unsupported object graphs rather than emit them unsanitized.
return value is null or string or bool or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal
? value
: Redacted;
}
private static bool IsSensitiveName(string name)
{
var normalized = name.Replace("-", string.Empty, StringComparison.Ordinal)
.Replace("_", string.Empty, StringComparison.Ordinal);
return normalized.Contains("authorization", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("apikey", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("token", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("secret", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("password", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("credential", StringComparison.OrdinalIgnoreCase) ||
normalized.Contains("cookie", StringComparison.OrdinalIgnoreCase);
}
private static string? StripQueryAndUserInfo(string? url)
{
if (string.IsNullOrWhiteSpace(url))
return url;
if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
var builder = new UriBuilder(uri)
{
UserName = string.Empty,
Password = string.Empty,
Query = string.Empty,
Fragment = string.Empty,
};
return builder.Uri.GetLeftPart(UriPartial.Path);
}
var queryStart = url.IndexOfAny(['?', '#']);
return queryStart >= 0 ? url[..queryStart] : url;
}
}
@@ -0,0 +1,68 @@
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Heimdall.Web.Services;
/// <summary>Verifies the signed Agent release metadata before Central exposes it to installers.</summary>
public static class AgentReleaseManifestVerifier
{
private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
public static bool TryVerify(string publicKeyPem, byte[] manifestBytes, byte[] signatureBytes,
string releaseTag, out AgentReleaseManifest? manifest)
{
manifest = null;
if (string.IsNullOrWhiteSpace(publicKeyPem) || manifestBytes.Length is 0 or > 1_048_576 ||
signatureBytes.Length is 0 or > 512 || string.IsNullOrWhiteSpace(releaseTag))
return false;
try
{
using var verifier = ECDsa.Create();
verifier.ImportFromPem(publicKeyPem);
if (verifier.KeySize != 256 || !verifier.VerifyData(manifestBytes, signatureBytes,
HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence))
return false;
var parsed = JsonSerializer.Deserialize<AgentReleaseManifest>(manifestBytes, Json);
if (parsed is null || parsed.Assets is null ||
!string.Equals(NormalizeVersion(parsed.Version), NormalizeVersion(releaseTag),
StringComparison.Ordinal) || parsed.Assets.Count == 0 ||
parsed.Assets.Any(asset => string.IsNullOrWhiteSpace(asset.Key) || asset.Value is null || !IsSha256(asset.Value)) ||
!IsValidContainerImageRepository(parsed.ContainerImage) ||
!IsValidContainerImageDigest(parsed.ContainerImageDigest) ||
((parsed.ContainerImageGpu is null) != (parsed.ContainerImageGpuDigest is null)) ||
(parsed.ContainerImageGpu is not null &&
(!IsValidContainerImageRepository(parsed.ContainerImageGpu) ||
!IsValidContainerImageDigest(parsed.ContainerImageGpuDigest))))
return false;
manifest = parsed;
return true;
}
catch (CryptographicException) { return false; }
catch (ArgumentException) { return false; }
catch (JsonException) { return false; }
}
private static string NormalizeVersion(string value) => value.Trim().TrimStart('v', 'V');
private static bool IsSha256(string value) => value.Length == 64 && value.All(Uri.IsHexDigit);
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 '-')
&& !image.Contains('@') && !image.Any(char.IsWhiteSpace) && !image.Split('/').Last().Contains(':');
private static bool IsValidContainerImageDigest(string? digest) => digest is { Length: 71 }
&& digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& digest[7..].All(Uri.IsHexDigit);
}
public sealed class AgentReleaseManifest
{
[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; }
[JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; }
[JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; }
}
+3 -3
View File
@@ -142,8 +142,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.IdentityModel.JsonWebTokens": "8.14.0"
}
@@ -491,7 +491,7 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
@@ -0,0 +1,31 @@
namespace Heimdall.Agent.Tests;
[CollectionDefinition("AgentOptions environment", DisableParallelization = true)]
public sealed class AgentOptionsEnvironmentScope
{
public const string Name = "AgentOptions environment";
}
[Collection(AgentOptionsEnvironmentScope.Name)]
public sealed class AgentOptionsTests
{
[Fact]
public void CentralUrl_LoadsFromSystemdCredentialWhenNoEnvironmentSettingExists()
{
var previous = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-agent-options-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "central-url"), "https://central.example.test\n");
try
{
Environment.SetEnvironmentVariable("CREDENTIALS_DIRECTORY", directory);
new AgentOptions { }.CentralUrl.ShouldBe("https://central.example.test");
}
finally
{
Environment.SetEnvironmentVariable("CREDENTIALS_DIRECTORY", previous);
Directory.Delete(directory, recursive: true);
}
}
}
+9 -46
View File
@@ -82,8 +82,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -166,14 +166,6 @@
"resolved": "10.0.13",
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
},
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
}
},
"Microsoft.AspNetCore.DataProtection.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -197,15 +189,6 @@
"Microsoft.AspNetCore.Connections.Abstractions": "10.0.13"
}
},
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Identity.Stores": "10.0.13"
}
},
"Microsoft.AspNetCore.SignalR.Client": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -543,27 +526,6 @@
"Microsoft.Extensions.Options": "10.0.0"
}
},
"Microsoft.Extensions.Identity.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Stores": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.Identity.Core": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -874,7 +836,10 @@
"System.ServiceProcess.ServiceController": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ=="
"contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==",
"dependencies": {
"System.Diagnostics.EventLog": "10.0.13"
}
},
"xunit.abstractions": {
"type": "Transitive",
@@ -936,12 +901,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -954,8 +918,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -969,4 +932,4 @@
}
}
}
}
}
+4 -6
View File
@@ -56,8 +56,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -1061,12 +1061,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -1079,8 +1078,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -62,8 +62,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -115,28 +115,6 @@
"resolved": "2.0.1",
"contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ=="
},
"Microsoft.AspNetCore.Cryptography.Internal": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
},
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
}
},
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Identity.Stores": "10.0.13"
}
},
"Microsoft.CodeCoverage": {
"type": "Transitive",
"resolved": "17.14.1",
@@ -240,15 +218,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -257,15 +226,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -284,46 +244,6 @@
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Stores": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.Identity.Core": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -351,18 +271,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -513,12 +421,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -528,8 +435,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
+1 -199
View File
@@ -76,208 +76,11 @@
"resolved": "4.4.0",
"contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw=="
},
"Microsoft.AspNetCore.Cryptography.Internal": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
},
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
}
},
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Identity.Stores": "10.0.13"
}
},
"Microsoft.CodeCoverage": {
"type": "Transitive",
"resolved": "17.14.1",
"contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg=="
},
"Microsoft.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Abstractions": "10.0.13",
"Microsoft.EntityFrameworkCore.Analyzers": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A=="
},
"Microsoft.EntityFrameworkCore.Analyzers": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA=="
},
"Microsoft.EntityFrameworkCore.Relational": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==",
"dependencies": {
"Microsoft.EntityFrameworkCore": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "UOJqcdNMoFcV/5RUcOlVKq9pPmbrcmbpLx5iYz9QtrmMcWRQzlL5Q/NZRfbPPLNyIEc1HWjjs5Z7nIwqewU1sg==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Caching.Memory": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "q+At65RACuCtGwUDVI08TmmrC73YFouimMkJAtlhsGhFcU/dVpqYEKpNBOF9TUxkJ6aefEOShqe7StLK7q3NqA==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Stores": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.Identity.Core": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA=="
},
"Microsoft.TestPlatform.ObjectModel": {
"type": "Transitive",
"resolved": "17.14.1",
@@ -358,8 +161,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -104,7 +104,12 @@ public class UserManagementTests : E2ETestBase
using var cleanup = new HttpClient { BaseAddress = new Uri(BaseUrl) };
cleanup.DefaultRequestHeaders.Authorization = new("Bearer", token);
var deleteResponse = await cleanup.DeleteAsync($"/api/users/{body.GetProperty("user").GetProperty("id").GetString()}");
deleteResponse.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NoContent);
var deleteError = await deleteResponse.Content.ReadAsStringAsync();
deleteError = deleteError.Replace(email, "[email]", StringComparison.Ordinal)
.Replace(password, "[password]", StringComparison.Ordinal);
if (deleteResponse.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.NoContent))
throw new InvalidOperationException(
$"Viewer/Supervisor cleanup failed with HTTP {(int)deleteResponse.StatusCode}: {deleteError}");
}
private static async Task SelectCreateRoleAsync(ILocator dialog, string role)
+4 -6
View File
@@ -74,8 +74,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -1335,12 +1335,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -1353,8 +1352,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -77,8 +77,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -876,12 +876,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -905,8 +904,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -67,8 +67,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -1310,12 +1310,11 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -1328,8 +1327,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -82,7 +82,7 @@ public class SiteDetailTests : PageTestBase
cut.Markup.ShouldContain("Agent__SiteToken");
cut.Markup.ShouldContain("Régénérer");
var compose = cut.Find("pre code").TextContent;
compose.ShouldContain("image: registry.example/heimdall-agent:latest");
compose.ShouldContain("image: registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("network_mode: host");
compose.ShouldContain("Agent__CentralUrl: \"http://localhost\"");
@@ -95,7 +95,7 @@ public class SiteDetailTests : PageTestBase
var agent = GetAgentService(ParseCompose(compose));
agent.Children.ShouldNotContainKey(new YamlScalarNode("deploy"));
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value
.ShouldBe("registry.example/heimdall-agent:latest");
.ShouldBe("registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
var volumes = (YamlSequenceNode)agent.Children[new YamlScalarNode("volumes")];
volumes.Children.Select(node => ((YamlScalarNode)node).Value)
@@ -112,12 +112,12 @@ public class SiteDetailTests : PageTestBase
{
var commands = cut.FindAll("pre code").Select(code => code.TextContent).ToArray();
commands.Length.ShouldBe(6);
commands[0].ShouldContain("docker pull registry.example/heimdall-agent:latest");
commands[0].ShouldContain("docker pull registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
commands[1].ShouldContain("--pull always");
commands[1].ShouldContain("registry.example/heimdall-agent:latest");
commands[3].ShouldContain("docker pull 'registry.example/heimdall-agent:latest'");
commands[1].ShouldContain("registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
commands[3].ShouldContain("docker pull 'registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'");
commands[4].ShouldContain("'--pull','always'");
commands[4].ShouldContain("'registry.example/heimdall-agent:latest'");
commands[4].ShouldContain("'registry.example/heimdall-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'");
});
}
@@ -140,6 +140,29 @@ public class SiteDetailTests : PageTestBase
cut.Markup.ShouldNotContain("install-agent.ps1");
}
[Fact]
public void SiteDetail_CommandeLinuxNeContientNiUrlCentralNiToken()
{
Handler.OnGet("api/updates/latest", AgentRelease());
Handler.OnGet("api/sites/", new SiteItem(
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow));
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-linux-private-42", DateTime.UtcNow.AddHours(24)));
LoginAs();
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Générer un token"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-linux-private-42"));
var command = cut.Find("pre code").TextContent;
command.ShouldContain("--central-url-file");
command.ShouldContain("--site-token-file");
command.ShouldContain("read -r -s site_token");
command.ShouldNotContain("tok-linux-private-42");
command.ShouldNotContain("http://localhost");
cut.Markup.ShouldContain("saisie du token est masquée");
}
[Fact]
public void SiteDetail_ChoisirImageNvidia_GenereComposeAvecGpuEtProviderCuda()
{
@@ -160,7 +183,7 @@ public class SiteDetailTests : PageTestBase
cut.WaitForAssertion(() =>
{
var compose = cut.Find("pre code").TextContent;
compose.ShouldContain("image: registry.example/heimdall-agent-gpu:latest");
compose.ShouldContain("image: registry.example/heimdall-agent-gpu@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("Agent__InferenceExecutionProvider: CUDA");
compose.ShouldContain("driver: nvidia");
@@ -168,7 +191,7 @@ public class SiteDetailTests : PageTestBase
compose.ShouldContain("\n deploy:\n resources:\n reservations:");
var agent = GetAgentService(ParseCompose(compose));
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value.ShouldBe(
"registry.example/heimdall-agent-gpu:latest");
"registry.example/heimdall-agent-gpu@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
var deploy = (YamlMappingNode)agent.Children[new YamlScalarNode("deploy")];
var resources = (YamlMappingNode)deploy.Children[new YamlScalarNode("resources")];
@@ -185,11 +208,33 @@ public class SiteDetailTests : PageTestBase
run.ShouldContain("--gpus all");
run.ShouldContain("Agent__InferenceExecutionProvider=CUDA");
run.ShouldContain("--pull always");
run.ShouldContain("registry.example/heimdall-agent-gpu:latest");
run.ShouldContain("registry.example/heimdall-agent-gpu@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
run.ShouldContain("--group-add \"$(stat -c '%g' /var/run/docker.sock)\"");
run.ShouldContain("-v /var/run/docker.sock:/var/run/docker.sock");
commands[4].ShouldContain("'--pull','always'");
commands[4].ShouldContain("'registry.example/heimdall-agent-gpu:latest'");
commands[4].ShouldContain("'registry.example/heimdall-agent-gpu@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'");
});
}
[Fact]
public void SiteDetail_RefuseDockerComposeQuandDigestImageInvalide()
{
Handler.OnGet("api/updates/latest", AgentRelease("sha256:not-a-digest"));
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-invalid-digest", DateTime.UtcNow.AddHours(24)));
LoginAs();
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Générer un token"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-invalid-digest"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Docker", StringComparison.OrdinalIgnoreCase)).Click();
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("Le manifeste d’image de l’agent fourni par Central est indisponible");
cut.FindAll(".installer-copy-box").ShouldBeEmpty();
});
}
@@ -250,11 +295,11 @@ public class SiteDetailTests : PageTestBase
LastUsedAt = lastUsed,
};
private static LatestReleaseInfo AgentRelease() => new()
private static LatestReleaseInfo AgentRelease(string? imageDigest = null) => new()
{
Version = "1.0.0",
ContainerImage = "registry.example/heimdall-agent",
ContainerImageDigest = "sha256:" + new string('a', 64),
ContainerImageDigest = imageDigest ?? "sha256:" + new string('a', 64),
UpdatePublicKeyPem = "test-public-key",
SignedManifest = "eyJ2ZXJzaW9uIjoiMS4wLjAifQ==",
ManifestSignature = "c2lnbmF0dXJl",
@@ -9,6 +9,26 @@ namespace Heimdall.Web.Tests.Controllers;
public sealed class UpdatesControllerRetryTests
{
[Fact]
public async Task FetchBoundedReleaseAssetAsync_allowsMissingForgejoDigestForSignedMetadata()
{
using var client = new HttpClient(new StaticResponseHandler("verified-by-release-signature"));
var result = await FetchAssetAsync("https://forgejo.example/attachments/release-key", digest: null, client);
Assert.Equal("verified-by-release-signature", Encoding.UTF8.GetString(result!));
}
[Fact]
public async Task FetchBoundedReleaseAssetAsync_rejectsCrossOriginUrls()
{
var handler = new StaticResponseHandler("unexpected");
using var client = new HttpClient(handler);
var result = await FetchAssetAsync("https://other.example/asset", digest: null, client);
Assert.Null(result);
Assert.Equal(0, handler.RequestCount);
}
[Theory]
[InlineData("<html><title>Proxy error</title></html>")]
[InlineData("{not-json")]
@@ -63,6 +83,40 @@ public sealed class UpdatesControllerRetryTests
return task.GetType().GetProperty("Result")?.GetValue(task);
}
private static async Task<byte[]?> FetchAssetAsync(string url, string? digest, HttpClient client)
{
var assetType = typeof(UpdatesController).GetNestedType("ForgejoAsset", BindingFlags.NonPublic);
Assert.NotNull(assetType);
var asset = Activator.CreateInstance(assetType)!;
assetType.GetProperty("Name")!.SetValue(asset, "agent-release-public.pem");
assetType.GetProperty("BrowserDownloadUrl")!.SetValue(asset, url);
assetType.GetProperty("Digest")!.SetValue(asset, digest);
var listType = typeof(List<>).MakeGenericType(assetType);
var assets = (System.Collections.IList)Activator.CreateInstance(listType)!;
assets.Add(asset);
var method = typeof(UpdatesController).GetMethod("FetchBoundedReleaseAssetAsync",
BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(method);
var task = (Task<byte[]?>)method.Invoke(null,
[assets, "agent-release-public.pem", client, 4096, new Uri("https://forgejo.example/api/v1/releases/latest"), CancellationToken.None])!;
return await task;
}
private sealed class StaticResponseHandler(string body) : HttpMessageHandler
{
public int RequestCount { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
RequestCount++;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = request,
Content = new StringContent(body, Encoding.UTF8),
});
}
}
[Theory]
[InlineData(HttpStatusCode.RequestTimeout, true)]
[InlineData(HttpStatusCode.TooManyRequests, true)]
@@ -0,0 +1,183 @@
using Heimdall.Web.Security;
using Sentry;
namespace Heimdall.Web.Tests.Security;
public sealed class SentryTelemetryPrivacyTests
{
[Fact]
public void Sanitize_RedactsAuthenticationHeadersAndCookies_AndKeepsSafeRequestMetadata()
{
const string apiKey = "SENTINEL_API_KEY_411";
const string cookie = "SENTINEL_SESSION_COOKIE_411";
using var document = System.Text.Json.JsonDocument.Parse($$"""
{
"request": {
"url": "https://user:SENTINEL_URL_PASSWORD_411@central.example/api/agents?access_token=SENTINEL_QUERY_TOKEN_411",
"query_string": "access_token=SENTINEL_QUERY_TOKEN_411",
"headers": {
"x-api-key": "{{apiKey}}",
"Content-Type": "application/json"
},
"env": { "AUTHORIZATION": "SENTINEL_ENV_AUTH_411", "REMOTE_ADDR": "192.0.2.1" },
"other": { "access_token": "SENTINEL_OTHER_TOKEN_411", "safe": "preserved" },
"cookies": "session={{cookie}}",
"data": { "access_token": "SENTINEL_BODY_TOKEN_411" }
},
"extra": {
"safeValue": "preserved",
"nested": { "clientSecret": "SENTINEL_EXTRA_SECRET_411" },
"array": [ { "accessToken": "SENTINEL_ARRAY_TOKEN_411", "safe": "preserved" } ],
"opaque": { "credential": "SENTINEL_OPAQUE_CREDENTIAL_411" }
}
}
""");
var sentryEvent = SentryEvent.FromJson(document.RootElement);
var sanitized = SentryTelemetryPrivacy.Sanitize(sentryEvent);
Assert.Same(sentryEvent, sanitized);
Assert.Equal("[Filtered]", sanitized.Request!.Headers!["x-api-key"]);
Assert.Equal("application/json", sanitized.Request.Headers["Content-Type"]);
Assert.Equal("[Filtered]", sanitized.Request.Env!["AUTHORIZATION"]);
Assert.Equal("192.0.2.1", sanitized.Request.Env["REMOTE_ADDR"]);
Assert.Equal("[Filtered]", sanitized.Request.Other!["access_token"]);
Assert.Equal("preserved", sanitized.Request.Other["safe"]);
Assert.Null(sanitized.Request.Cookies);
Assert.Equal("https://central.example/api/agents", sanitized.Request.Url);
Assert.Null(sanitized.Request.QueryString);
Assert.Null(sanitized.Request.Data);
Assert.Equal("preserved", sanitized.Extra!["safeValue"]);
Assert.Equal("[Filtered]", ((IDictionary<string, object?>)sanitized.Extra["nested"]!)["clientSecret"]);
Assert.Equal("[Filtered]", sanitized.Extra["array"]);
Assert.Equal("[Filtered]", ((IDictionary<string, object?>)sanitized.Extra["opaque"]!)["credential"]);
var serialized = SerializeEvent(sanitized);
Assert.DoesNotContain(apiKey, serialized, StringComparison.Ordinal);
Assert.DoesNotContain(cookie, serialized, StringComparison.Ordinal);
Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal);
}
[Fact]
public void SanitizeBreadcrumb_RedactsSensitiveDataAndPreservesSafeData()
{
var breadcrumb = new Breadcrumb(
"request",
"http",
new Dictionary<string, string>
{
["Authorization"] = "SENTINEL_BREADCRUMB_AUTH_411",
["method"] = "GET",
},
"http.client",
BreadcrumbLevel.Info);
var sanitized = SentryTelemetryPrivacy.SanitizeBreadcrumb(breadcrumb);
Assert.Same(breadcrumb, sanitized);
Assert.Equal("[Filtered]", sanitized.Data!["Authorization"]);
Assert.Equal("GET", sanitized.Data["method"]);
Assert.DoesNotContain("SENTINEL_", System.Text.Json.JsonSerializer.Serialize(sanitized), StringComparison.Ordinal);
}
[Fact]
public void SanitizeTransaction_RedactsRequestContextsBreadcrumbsTagsAndSpans()
{
using var document = System.Text.Json.JsonDocument.Parse("""
{
"transaction": "GET /api/agents",
"start_timestamp": "2026-11-13T12:00:00Z",
"request": {
"url": "https://central.example/api/agents?api_key=SENTINEL_TRANSACTION_URL_411",
"query_string": "api_key=SENTINEL_TRANSACTION_QUERY_411",
"headers": {
"Authorization": "SENTINEL_TRANSACTION_AUTH_411",
"Content-Type": "application/json"
},
"cookies": "session=SENTINEL_TRANSACTION_COOKIE_411",
"data": { "password": "SENTINEL_TRANSACTION_BODY_411" }
},
"contexts": {
"trace": { "type": "trace", "data": { "api_key": "SENTINEL_TRANSACTION_TRACE_411", "safe": "preserved" } },
"response": { "type": "response", "cookies": "session=SENTINEL_TRANSACTION_RESPONSE_COOKIE_411", "headers": { "Set-Cookie": "SENTINEL_TRANSACTION_SET_COOKIE_411", "Content-Type": "application/json" }, "data": { "token": "SENTINEL_TRANSACTION_RESPONSE_BODY_411" } },
"custom": { "clientSecret": "SENTINEL_TRANSACTION_CONTEXT_411", "mode": "safe", "metadata": [ { "token": "SENTINEL_CONTEXT_ARRAY_411" } ] }
},
"breadcrumbs": [
{ "message": "request", "type": "http", "category": "http.client", "data": { "Authorization": "SENTINEL_TRANSACTION_BREADCRUMB_411", "method": "GET" } }
],
"tags": { "api_key": "SENTINEL_TRANSACTION_TAG_411", "method": "GET" },
"spans": [
{ "start_timestamp": "2026-11-13T12:00:00Z", "op": "http.client", "description": "GET /health", "data": { "credential": "SENTINEL_TRANSACTION_SPAN_411", "status_code": 200 }, "tags": { "secret": "SENTINEL_TRANSACTION_SPAN_TAG_411", "method": "GET" } }
]
}
""");
var transaction = SentryTransaction.FromJson(document.RootElement);
var sanitized = SentryTelemetryPrivacy.Sanitize(transaction);
Assert.Same(transaction, sanitized);
Assert.Equal("[Filtered]", sanitized.Request.Headers!["Authorization"]);
Assert.Equal("application/json", sanitized.Request.Headers["Content-Type"]);
Assert.Null(sanitized.Request.Cookies);
Assert.Null(sanitized.Request.QueryString);
Assert.Null(sanitized.Request.Data);
Assert.Equal("[Filtered]", sanitized.Contexts.Trace.Data["api_key"]);
Assert.Equal("preserved", sanitized.Contexts.Trace.Data["safe"]);
Assert.Equal("[Filtered]", sanitized.Contexts.Response.Headers["Set-Cookie"]);
Assert.Equal("application/json", sanitized.Contexts.Response.Headers["Content-Type"]);
Assert.Null(sanitized.Contexts.Response.Cookies);
Assert.Null(sanitized.Contexts.Response.Data);
Assert.Equal("[Filtered]", ((IDictionary<string, object?>)sanitized.Contexts["custom"])["clientSecret"]);
Assert.Equal("safe", ((IDictionary<string, object?>)sanitized.Contexts["custom"])["mode"]);
Assert.Equal("[Filtered]", ((IDictionary<string, object?>)sanitized.Contexts["custom"])["metadata"]);
Assert.Equal("[Filtered]", sanitized.Breadcrumbs.Single().Data!["Authorization"]);
Assert.Equal("GET", sanitized.Breadcrumbs.Single().Data!["method"]);
Assert.Equal("[Filtered]", sanitized.Tags["api_key"]);
Assert.Equal("GET", sanitized.Tags["method"]);
Assert.Equal("[Filtered]", sanitized.Spans.Single().Data["credential"]);
Assert.Equal("200", sanitized.Spans.Single().Data["status_code"]?.ToString());
Assert.Equal("[Filtered]", sanitized.Spans.Single().Tags["secret"]);
Assert.Equal("GET", sanitized.Spans.Single().Tags["method"]);
var serialized = SerializeTransaction(sanitized);
Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_RedactsSensitiveEventTagsInSdkPayload()
{
using var document = System.Text.Json.JsonDocument.Parse("""
{ "message": "synthetic", "tags": { "api_key": "SENTINEL_EVENT_TAG_411", "method": "GET" } }
""");
var sentryEvent = SentryEvent.FromJson(document.RootElement);
var sanitized = SentryTelemetryPrivacy.Sanitize(sentryEvent);
Assert.Equal("[Filtered]", sanitized.Tags["api_key"]);
Assert.Equal("GET", sanitized.Tags["method"]);
var serialized = SerializeEvent(sanitized);
Assert.DoesNotContain("SENTINEL_EVENT_TAG_411", serialized, StringComparison.Ordinal);
}
private static string SerializeTransaction(SentryTransaction transaction)
{
using var stream = new MemoryStream();
using (var writer = new System.Text.Json.Utf8JsonWriter(stream))
{
transaction.WriteTo(writer, null);
}
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
private static string SerializeEvent(SentryEvent sentryEvent)
{
using var stream = new MemoryStream();
using (var writer = new System.Text.Json.Utf8JsonWriter(stream))
{
sentryEvent.WriteTo(writer, null);
}
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
@@ -0,0 +1,100 @@
using System.Security.Cryptography;
using System.Text.Json;
using Heimdall.Web.Services;
using Xunit;
namespace Heimdall.Web.Tests.Services;
public sealed class AgentReleaseManifestVerifierTests
{
[Fact]
public void TryVerify_AcceptsSignedManifestWhenForgejoAssetDigestIsUnavailable()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
var valid = AgentReleaseManifestVerifier.TryVerify(
key.ExportSubjectPublicKeyInfoPem(), bytes, signature, "1.0.7", out var manifest);
Assert.True(valid);
Assert.NotNull(manifest);
Assert.Equal("1.0.7", manifest.Version);
Assert.True(manifest.Assets.ContainsKey("portable"));
}
[Fact]
public void TryVerify_AcceptsCpuOnlySignedManifest()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes(includeGpuImage: false);
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
var valid = AgentReleaseManifestVerifier.TryVerify(
key.ExportSubjectPublicKeyInfoPem(), bytes, signature, "1.0.7", out var manifest);
Assert.True(valid);
Assert.NotNull(manifest);
Assert.Null(manifest.ContainerImageGpu);
Assert.Null(manifest.ContainerImageGpuDigest);
}
[Fact]
public void TryVerify_RejectsIncompleteGpuImageMetadata()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes(invalidGpuPair: true);
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.7", out _));
}
[Fact]
public void TryVerify_RejectsModifiedManifest()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
bytes[^2] ^= 1;
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.7", out _));
}
[Fact]
public void TryVerify_RejectsTagMismatchAndMalformedArchiveDigest()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.8", out _));
bytes = ManifestBytes(invalidArchiveHash: true);
signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.7", out _));
}
private static byte[] ManifestBytes(bool invalidArchiveHash = false, bool includeGpuImage = true,
bool invalidGpuPair = false)
{
var manifest = new Dictionary<string, object?>
{
["version"] = "1.0.7",
["assets"] = new Dictionary<string, string>
{
["portable"] = invalidArchiveHash ? "not-a-sha256" : new string('c', 64)
},
["containerImage"] = "eltruncho/heimdall-agent",
["containerImageDigest"] = "sha256:" + new string('a', 64),
};
if (includeGpuImage || invalidGpuPair)
manifest["containerImageGpu"] = "eltruncho/heimdall-agent-gpu";
if (includeGpuImage && !invalidGpuPair)
manifest["containerImageGpuDigest"] = "sha256:" + new string('b', 64);
return JsonSerializer.SerializeToUtf8Bytes(manifest);
}
}
+3 -3
View File
@@ -131,8 +131,8 @@
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"resolved": "16.3.0",
"contentHash": "wFTqA37e1I4AOEhTTYlxrqDE8BQ4OB3dqhlv2KwYmHv+a4tn7R1JW2n2bzXb8eTBhWVBSl7iTZ0VxEt0a57D4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0",
"Microsoft.Extensions.Options": "10.0.0",
@@ -1188,7 +1188,7 @@
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"AutoMapper": "[16.3.0, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",