11 Commits
Author SHA1 Message Date
arnaud.dartois 36d4045387 feat(installer): use latest Agent Docker images
Heimdall Gitea / Detect CI scope (pull_request) Successful in 7s
Heimdall Gitea / Build and tests (pull_request) Successful in 16m26s
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 6m53s
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 3s
Refs #337
2026-11-12 14:54:21 +01:00
arnaud.dartois be1cb9b479 Fix camera config reconciliation latency
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 10m36s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m8s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Refs #157

Reconcile camera config changes immediately and strengthen the disposable toggle acceptance evidence.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 14:37:33 +01:00
arnaud.dartois a8ce828c01 docs(backup): clarify key lifecycle and recovery measurements
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 17m25s
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) Failing after 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 12:51:35 +01:00
arnaud.dartois c5a250586b fix(ci): use Forgejo-supported variable for Renovate endpoint
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 17m45s
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 3s
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-12 12:17:53 +01:00
arnaud.dartois c8a428555a test(install): assert agent socket access for #293 (#333)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 23m29s
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-12 11:26:49 +01:00
arnaud.dartois ec80e31e33 test(storage): document migration startup acceptance for #300 (#332)
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 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 11:12:37 +01:00
arnaud.dartois 511fbfce7b fix(install): rendre les secrets RustFS et coturn lisibles (#331)
Heimdall Gitea / CI policy (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Successful in 22m34s
Heimdall Gitea / Detect CI scope (push) Successful in 8s
Heimdall Gitea / Build and scan server image (push) Successful in 7m54s
Heimdall Gitea / Build and scan agent image (push) Successful in 13m51s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 26m57s
Heimdall Gitea / Publish versioned installer release (push) Successful in 6m47s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 06:34:19 +01:00
arnaud.dartois 78ff15799e [Auth] Couvrir le cookie navigateur après 2FA (#330)
Heimdall Gitea / Detect CI scope (push) Successful in 9s
Heimdall Gitea / Build and tests (push) Successful in 26m6s
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-12 05:00:00 +01:00
arnaud.dartois aef04552a8 [Auth] Couvrir la première connexion après création par rôle (#329)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 21m23s
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) Failing after 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 04:18:55 +01:00
arnaud.dartois 7c0c8ecf46 [Install] Vérifier le checksum publié du bundle serveur (#328)
Heimdall Gitea / Detect CI scope (push) Successful in 11s
Heimdall Gitea / Build and tests (push) Successful in 18m40s
Heimdall Gitea / Build and scan server image (push) Successful in 8m5s
Heimdall Gitea / Build and scan agent image (push) Successful in 12m52s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m19s
Heimdall Gitea / Publish versioned installer release (push) Successful in 4m43s
Heimdall Gitea / CI policy (push) Successful in 13s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 03:17:50 +01:00
arnaud.dartois dc8a313deb [Camera] Keep activated cameras offline until agent confirmation (#325)
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 21m18s
Heimdall Gitea / Build and scan server image (push) Successful in 8m5s
Heimdall Gitea / Build and scan agent image (push) Successful in 11m29s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 33m56s
Heimdall Gitea / Publish versioned installer release (push) Successful in 4m13s
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 02:06:10 +01:00
49 changed files with 1644 additions and 92 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
image: renovate/renovate:44.133.0
env:
RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: ${{ vars.GITEA_API_ENDPOINT }}
RENOVATE_ENDPOINT: ${{ vars.FORGEJO_API_ENDPOINT }}
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_ONBOARDING: 'false'
steps:
+52
View File
@@ -150,6 +150,58 @@ ne sont pas supprimés. L’archive contient le répertoire `dp-keys`, dont
`dp-cert.pfx` protège les clés Data Protection. Protéger les sauvegardes locales
et S3 comme des données sensibles.
### Conservation et rotation des clés Data Protection
Le volume Central contient le trousseau XML Data Protection et `dp-cert.pfx`,
qui protège ces clés au repos. L’archive de données protégées doit conserver
l’ensemble de `dp-keys`; restaurer PostgreSQL sans ce répertoire peut laisser
les identifiants et autres charges utiles protégées impossibles à relire.
- Arrêter Central avant la restauration et restaurer l’archive protégée complète
dans le volume correspondant. Ne remplacer ni supprimer `dp-cert.pfx` ou des
fichiers de clés indépendamment.
- Garder les archives comme des secrets : `dp-cert.pfx` contient la clé privée
qui déchiffre le trousseau. Le script crée l’archive locale avec le mode
`0600`; contrôler aussi les permissions et l’accès du bucket S3.
- Le framework fait évoluer automatiquement le trousseau selon sa politique de
durée de vie. Les clés expirées restent nécessaires pour lire les données
protégées avec ces clés; ne pas purger les anciennes clés au seul motif
qu’elles ont expiré.
- Le certificat de protection `dp-cert.pfx` n’a pas de procédure de rotation
manuelle validée dans Heimdall. Ne pas le remplacer lors d’une restauration.
Toute rotation planifiée doit faire l’objet d’une procédure séparée et d’un
essai sur copie isolée, avec vérification de lecture des anciennes et nouvelles
charges utiles avant suppression de la clé précédente.
Voir [la gestion des clés Data Protection dans ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management)
pour le cycle des clés; supprimer une clé qui protège encore des données rend
ces données définitivement illisibles.
### Mesure RPO/RTO
Les horaires configurés ne constituent pas une mesure de RPO. Les sauvegardes
PostgreSQL et du volume protégé sont prises séparément, et le miroir RustFS suit
un autre intervalle; Heimdall ne fournit pas de point de restauration atomique.
Le responsable d’exploitation doit définir les objectifs visés et le scénario
avant un exercice réel.
Pour chaque exercice autorisé, consigner sans données personnelles :
1. La date UTC du changement connu le plus récent dans chaque stockage, la date
de la panne simulée, et la date du changement le plus récent réellement
restauré. Calculer le RPO séparément pour PostgreSQL, objets locaux/S3 et
clés protégées; retenir le pire résultat pour le service.
2. L’heure de début de la restauration, ses jalons (base, objets, démarrage de
Central) et l’heure où les vérifications post-restauration réussissent. Cette
durée est le RTO mesuré pour cet essai, pas un engagement universel.
3. Versions des scripts/images, tailles et nombres d’objets, hôte/CPU/mémoire,
stockage et réseau utilisés, étapes manuelles, erreurs et résultat final.
Répéter l’exercice complet au moins deux fois avant de fixer une cible.
La recette synthétique de `test-backup-restore.sh` ne comprend pas le démarrage
de Central, une connexion utilisateur ni un backend S3; son temps d’exécution
ne doit jamais être présenté comme un RTO de production.
## Test de restauration (runbook)
### Prérequis
+24 -7
View File
@@ -3,6 +3,16 @@ services:
coturn:
image: coturn/coturn:4.6
pull_policy: always
# Local Compose secrets are read-only bind mounts and preserve the
# installer's 0600 owner-only permissions. Read the mounted file as a
# short-lived root initializer, write a private config into tmpfs, then
# run turnserver as nobody. The upstream binary does not exec with a
# reduced capability set; no-new-privileges still prevents elevation.
user: "0:0"
security_opt:
- no-new-privileges:true
tmpfs:
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
ports:
- "${COTURN_PORT:-3478}:3478/tcp"
- "${COTURN_PORT:-3478}:3478/udp"
@@ -10,13 +20,20 @@ services:
entrypoint: ["/bin/sh", "-c"]
command:
- >-
exec turnserver -n --use-auth-secret
--static-auth-secret="$$(cat /run/secrets/coturn_secret)"
--realm=${COTURN_REALM:-heimdall.local}
--fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout
--no-cli --listening-port=3478
--min-port=${COTURN_RELAY_PORT_MIN:-49160}
--max-port=${COTURN_RELAY_PORT_MAX:-49200}
set -eu;
umask 077;
printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n'
"$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}"
"${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}"
> /run/coturn/turnserver.conf;
printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf;
if [ -n "$$COTURN_EXTERNAL_IP" ]; then
printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf;
fi;
chown 65534:65534 /run/coturn /run/coturn/turnserver.conf;
exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody
environment:
COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-}
secrets:
- coturn_secret
restart: unless-stopped
+30 -2
View File
@@ -5,6 +5,34 @@ services:
image: rustfs/rustfs:latest
pull_policy: always
restart: unless-stopped
# Compose file secrets are read-only bind mounts locally. The installer
# deliberately creates them mode 0600, owned by root; RustFS runs as UID
# 10001 and cannot read that source directly. A small root init copies the
# files into tmpfs, then drops privileges before starting the server.
user: "0:0"
read_only: true
cap_drop:
- ALL
cap_add:
- CHOWN
- DAC_OVERRIDE
- SETGID
- SETUID
security_opt:
- no-new-privileges:true
tmpfs:
- /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700
- /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
entrypoint: ["/bin/sh", "-c"]
command:
- >-
set -eu;
umask 077;
cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key;
cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key;
chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key;
exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs
ports:
- "${RUSTFS_API_PORT:-9000}:9000"
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
@@ -13,8 +41,8 @@ services:
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key
RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key
secrets:
- rustfs_access_key
- rustfs_secret_key
+1 -1
View File
@@ -39,7 +39,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l
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 généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. 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. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. 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 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.
## Rotation
+9 -7
View File
@@ -1,8 +1,8 @@
# Docker Compose deployment
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
separately on each camera-network host; the Central UI supplies a
digest-pinned Agent Compose file for each site. RustFS, ntfy, Ollama, TURN,
separately on each camera-network host; the Central UI supplies an Agent
Compose file using the `latest` tag for each site. RustFS, ntfy, Ollama, TURN,
Redis and scheduled backups have separate Compose files and can be left out.
## Central and database
@@ -135,11 +135,13 @@ 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 image reference and digest from Central's verified release manifest and
includes the site token, public Central URL, Agent name and release public key.
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. Do
not substitute a mutable image tag for the digest.
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
`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
manifest before replacing the running container.
The Agent Compose is generated by Central's UI for the selected site; there is
no production Agent Compose in this repository. For local development only,
+1 -1
View File
@@ -8,7 +8,7 @@ Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent
Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir.
Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Avant de démarrer Renovate, il vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
Le workflow Renovate lit l’API Forgejo dans la variable d’action `FORGEJO_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Forgejo réserve les noms de variables commençant par `GITEA_`. Avant de démarrer Renovate, le workflow vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
`scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi.
+1 -1
View File
@@ -281,7 +281,7 @@ 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 une référence d'image vérifiée par digest. 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 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.
### États — Détail Site
+21 -2
View File
@@ -44,8 +44,27 @@ if ($script:PackageReleaseVersion -eq 'unversioned') {
if (-not $installerAsset -or $installerAsset.browser_download_url -notmatch '^https://') {
throw "La release ne contient pas son bundle d'installation versionné."
}
$expectedHash = [string]$installerAsset.digest -replace '^sha256:', ''
if ($expectedHash -notmatch '^[A-Fa-f0-9]{64}$') { throw 'La release ne fournit pas le SHA-256 du bundle.' }
$digestProperty = $installerAsset.PSObject.Properties['digest']
$assetDigest = if ($null -ne $digestProperty) { $digestProperty.Value } else { $null }
if ($null -ne $assetDigest) {
if ($assetDigest -isnot [string] -or $assetDigest -notmatch '^sha256:[A-Fa-f0-9]{64}$') {
throw 'Le digest Gitea du bundle est invalide.'
}
$expectedHash = $assetDigest.Substring(7)
} else {
$checksumName = "$installerName.sha256"
$checksumAsset = @($release.assets) | Where-Object { $_.name -eq $checksumName } | Select-Object -First 1
if (-not $checksumAsset -or $checksumAsset.browser_download_url -notmatch '^https://') {
throw 'La release ne fournit pas le checksum publié du bundle.'
}
$checksumPath = Join-Path $bootstrapRoot 'installers.zip.sha256'
Invoke-WebRequest -UseBasicParsing -Uri $checksumAsset.browser_download_url -OutFile $checksumPath -TimeoutSec 30
$checksumText = [IO.File]::ReadAllText($checksumPath)
$escapedName = [Regex]::Escape($installerName)
$checksumMatches = [Regex]::Matches($checksumText, "(?m)^([A-Fa-f0-9]{64})\s+\*?$escapedName\s*$")
if ($checksumMatches.Count -ne 1) { throw 'Le checksum publié du bundle est invalide.' }
$expectedHash = $checksumMatches[0].Groups[1].Value
}
Invoke-WebRequest -UseBasicParsing -Uri $installerAsset.browser_download_url -OutFile $bundlePath -TimeoutSec 120
$actualHash = (Get-FileHash -LiteralPath $bundlePath -Algorithm SHA256).Hash
if ($actualHash -ne $expectedHash) { throw 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' }
+19 -3
View File
@@ -62,9 +62,25 @@ if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
installer_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$asset_json")" || {
echo 'URL HTTPS du bundle d’installation invalide.' >&2; exit 1;
}
expected_sha256="$(jq -er '.digest | select(test("^sha256:[A-Fa-f0-9]{64}$")) | sub("^sha256:"; "")' <<<"$asset_json")" || {
echo 'La release ne fournit pas le SHA-256 du bundle.' >&2; exit 1;
}
asset_digest_type="$(jq -r 'if has("digest") then (.digest | type) else "missing" end' <<<"$asset_json")"
asset_digest="$(jq -r '.digest // empty' <<<"$asset_json")"
if [[ "$asset_digest_type" != null && "$asset_digest_type" != missing ]]; then
[[ "$asset_digest_type" == string && "$asset_digest" =~ ^sha256:[A-Fa-f0-9]{64}$ ]] || {
echo 'Le digest Gitea du bundle est invalide.' >&2; exit 1;
}
expected_sha256="${asset_digest#sha256:}"
else
checksum_asset_json="$(jq -ce --arg name "$installer_asset.sha256" '.assets[]? | select(.name == $name)' "$bootstrap_dir/release.json")" || {
echo 'La release ne fournit pas le checksum publié du bundle.' >&2; exit 1;
}
checksum_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$checksum_asset_json")" || {
echo 'URL HTTPS du checksum du bundle invalide.' >&2; exit 1;
}
curl --fail --silent --show-error --location "$checksum_url" --output "$bootstrap_dir/installers.zip.sha256"
expected_sha256="$(awk -v name="$installer_asset" '$2 == name && $1 ~ /^[A-Fa-f0-9]{64}$/ { print tolower($1); count++ } END { if (count != 1) exit 1 }' "$bootstrap_dir/installers.zip.sha256")" || {
echo 'Le checksum publié du bundle est invalide.' >&2; exit 1;
}
fi
curl --fail --silent --show-error --location "$installer_url" --output "$bootstrap_dir/installers.zip"
actual_sha256="$(sha256sum "$bootstrap_dir/installers.zip" | cut -d ' ' -f 1)"
[[ "${actual_sha256,,}" == "${expected_sha256,,}" ]] || { echo 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' >&2; exit 1; }
+1 -1
View File
@@ -87,7 +87,7 @@ Windows, copiez la commande affichée sur l’hôte distant : elle télécharge
script depuis le Central et l’exécute avec les identifiants propres à ce site.
L’installation Linux peut créer un service systemd; l’installation Windows
peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de
utilisez le Compose généré par l’IHM, qui suit le tag `latest`. Aucun fichier de
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
+84 -5
View File
@@ -131,13 +131,27 @@ output = args[args.index('--output') + 1]
with open(os.environ['OFFLINE_CURL_LOG'], 'a') as log:
log.write(url + '\n')
if url.endswith('/releases/latest'):
installer_path = os.environ['OFFLINE_INSTALLER_ZIP']
if os.environ.get('OFFLINE_BAD_API_DIGEST') == '1':
digest = 'invalid'
elif os.environ.get('OFFLINE_NULL_ASSET_DIGEST') == '1':
digest = None
else:
digest = 'sha256:' + hashlib.sha256(open(installer_path,'rb').read()).hexdigest()
payload = json.dumps({'tag_name':'1.2.3','assets':[{
'name':'heimdall-installers-1.2.3.zip',
'digest':'sha256:' + hashlib.sha256(open(os.environ['OFFLINE_INSTALLER_ZIP'],'rb').read()).hexdigest(),
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}]}).encode()
'digest':digest,
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}, {
'name':'heimdall-installers-1.2.3.zip.sha256',
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]}).encode()
open(output, 'wb').write(payload)
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
elif url == 'https://release.test/heimdall-installers-1.2.3.zip.sha256':
if os.environ.get('OFFLINE_BAD_CHECKSUM') == '1':
open(output, 'w').write('0' * 64 + ' heimdall-installers-1.2.3.zip\n')
else:
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'] + '.sha256', output)
else:
sys.exit(22)
'''
@@ -200,7 +214,9 @@ else:
elif path.endswith('/releases/latest'):
self._json(200, {'tag_name': '1.2.3', 'assets': [{
'name': 'heimdall-installers-1.2.3.zip',
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}]})
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}, {
'name': 'heimdall-installers-1.2.3.zip.sha256',
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]})
elif path.endswith('/releases/tags/1.2.3'):
self._json(404, {'message': 'not found'})
elif path.endswith('/releases/7301/assets'):
@@ -252,7 +268,7 @@ else:
if path.endswith('/releases/7301'):
assert set(release_state['assets']) >= {
'agent-update-manifest.json', 'agent-update-manifest.sig',
'heimdall-installers-1.2.3.zip'}
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256'}
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
release_state['release']['draft'] = body['draft']
@@ -318,6 +334,65 @@ else:
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
'https://release.test/heimdall-installers-1.2.3.zip',
]
checksum_log = curl_log
checksum_env = launcher_env.copy()
checksum_env.update({
'OFFLINE_CURL_LOG': str(checksum_log),
'OFFLINE_NULL_ASSET_DIGEST': '1',
'HEIMDALL_INSTALLER_VERSION': '',
})
(temp / 'compose-version-probe').unlink(missing_ok=True)
checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
env=checksum_env, capture_output=True, text=True)
checksum_output = checksum_launcher.stdout + checksum_launcher.stderr
assert checksum_launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
f'checksum fallback exit={checksum_launcher.returncode}; '
f'URLs={checksum_log.read_text() if checksum_log.exists() else "<none>"}; '
+ checksum_output[-2000:])
assert checksum_log.read_text().splitlines() == [
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
'https://release.test/heimdall-installers-1.2.3.zip',
checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
'https://release.test/heimdall-installers-1.2.3.zip',
], (f'checksum fallback did not request expected assets; '
f'HEIMDALL_INSTALLER_VERSION={checksum_env.get("HEIMDALL_INSTALLER_VERSION")!r}; '
f'log={checksum_log.read_text() if checksum_log.exists() else "<missing>"}; '
f'returncode={checksum_launcher.returncode}; output={checksum_output[-2000:]}')
(temp / 'compose-version-probe').unlink(missing_ok=True)
bad_checksum_log = temp / 'installer-bootstrap-bad-checksum-urls.txt'
bad_checksum_env = checksum_env.copy()
bad_checksum_env.update({
'OFFLINE_CURL_LOG': str(bad_checksum_log),
'OFFLINE_BAD_CHECKSUM': '1',
})
bad_checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
env=bad_checksum_env, capture_output=True, text=True)
bad_checksum_output = bad_checksum_launcher.stdout + bad_checksum_launcher.stderr
assert bad_checksum_launcher.returncode != 0 and 'ne correspond pas à la release' in bad_checksum_output, (
f'bad checksum was not rejected; returncode={bad_checksum_launcher.returncode}; '
f'output={bad_checksum_output[-2000:]}')
assert bad_checksum_log.read_text().splitlines() == [
bad_checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
'https://release.test/heimdall-installers-1.2.3.zip',
]
(temp / 'compose-version-probe').unlink(missing_ok=True)
invalid_digest_log = temp / 'installer-bootstrap-invalid-digest-urls.txt'
invalid_digest_env = checksum_env.copy()
invalid_digest_env.update({
'OFFLINE_CURL_LOG': str(invalid_digest_log),
'OFFLINE_BAD_API_DIGEST': '1',
})
invalid_digest_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
env=invalid_digest_env, capture_output=True, text=True)
invalid_digest_output = invalid_digest_launcher.stdout + invalid_digest_launcher.stderr
assert invalid_digest_launcher.returncode != 0 and 'digest Gitea du bundle est invalide' in invalid_digest_output, (
f'malformed API digest was not rejected; returncode={invalid_digest_launcher.returncode}; '
f'output={invalid_digest_output[-2000:]}')
assert invalid_digest_log.read_text().splitlines() == [
invalid_digest_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
]
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
env['GITEA_TOKEN'] = RELEASE_TOKEN
env['BEFORE_SHA'] = commit + '^'
@@ -379,8 +454,12 @@ else:
assert "PackageReleaseVersion = '1.2.3'" in windows_script
assert 'install/install-agent.sh' in bundle.namelist()
assert 'install/install-agent.ps1' in bundle.namelist()
checksum_asset = packages / 'heimdall-installers-1.2.3.zip.sha256'
checksum, filename = checksum_asset.read_text().split()
assert filename == 'heimdall-installers-1.2.3.zip'
assert checksum == hashlib.sha256((packages / filename).read_bytes()).hexdigest()
expected_release_assets = {
'heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
'agent-update-manifest.json', 'agent-update-manifest.sig',
'agent-image.json', 'agent-image-gpu.json',
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
+2
View File
@@ -64,4 +64,6 @@ Path('artifacts/packages/provenance.json').write_text(json.dumps({
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
PY
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
installer_bundle="artifacts/packages/heimdall-installers-$version.zip"
(cd artifacts/packages && sha256sum "$(basename "$installer_bundle")" > "$(basename "$installer_bundle").sha256")
printf '%s' "$version" > artifacts/version
+5 -4
View File
@@ -30,15 +30,16 @@ def request(path, method='GET', body=None, content_type='application/json', miss
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
package_root = Path('artifacts/packages')
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
installer_checksum = package_root / f'{installer_bundle.name}.sha256'
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
required_assets = [installer_bundle, package_root / 'agent-release-public.pem',
required_assets = [installer_bundle, installer_checksum, package_root / 'agent-release-public.pem',
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
if any(not path.is_file() for path in required_assets) or not agent_archives:
raise SystemExit('Installer bundle or signed Agent update assets are missing')
# CI provenance, image digests, and checksum bookkeeping stay in the build
# artifacts. Gitea releases expose only the Central installer bundle and the
# files Central/Agent need to verify and install native Agent updates.
# CI provenance, image digests, and general checksum bookkeeping stay in the
# build artifacts. Publish the installer bundle's checksum as a sidecar so
# bootstraps can verify it when the Gitea asset API omits its digest field.
package_files = sorted([*required_assets, *agent_archives])
if release is None:
release = request('/releases', 'POST', {
+3 -3
View File
@@ -9,12 +9,12 @@ export function validateEndpoint(value) {
try {
parsed = new URL(value);
} catch {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
if (parsed.protocol !== 'https:' || parsed.username || parsed.password ||
parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
return parsed.href.replace(/\/$/, '');
@@ -38,7 +38,7 @@ export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fet
if (!response.ok) {
const detail = response.status === 401 || response.status === 403
? 'Check that RENOVATE_TOKEN is active and has repository read and write access.'
: 'Check GITEA_API_ENDPOINT and the Gitea API availability.';
: 'Check FORGEJO_API_ENDPOINT and the Forgejo API availability.';
throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`);
}
}
+2 -2
View File
@@ -2,13 +2,13 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
test('accepts an HTTPS Gitea API endpoint and trims its trailing slash', () => {
test('accepts an HTTPS Forgejo API endpoint and trims its trailing slash', () => {
assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1');
});
test('rejects non-HTTPS, malformed, and non-API endpoints', () => {
for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) {
assert.throws(() => validateEndpoint(value), /HTTPS URL ending in \/api\/v1/);
assert.throws(() => validateEndpoint(value), /FORGEJO_API_ENDPOINT.*HTTPS URL ending in \/api\/v1/);
}
});
+2 -2
View File
@@ -279,7 +279,7 @@ class ReleaseTests(unittest.TestCase):
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': '1.2.3',
'html_url': 'https://example.test/releases/7'}).encode())
if req.method == 'GET':
names = ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
names = ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
@@ -289,7 +289,7 @@ class ReleaseTests(unittest.TestCase):
directory = Path(temp)/'artifacts/packages'
directory.mkdir(parents=True)
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'1.2.3'}))
for name in ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
for name in ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
(directory/name).write_bytes(b'archive')
+2 -1
View File
@@ -13,6 +13,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes.
- `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.
- `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.
@@ -21,7 +22,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
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.
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.
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.
+24 -3
View File
@@ -9,14 +9,19 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
## Implementation path
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central.
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled.
- Agent status reports require the API key to resolve to the same Agent ID in the route and the camera to be assigned to that Agent. Authenticate and authorize both resources with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`.
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal.
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
## Local verification
The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract.
Run the focused Agent lifecycle suites:
```bash
@@ -27,6 +32,8 @@ These tests cover session idempotence, process termination, and synchronization
## Central + Agent disposable acceptance
Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap.
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
@@ -42,7 +49,7 @@ This acceptance proves the source-built Central/Agent software lifecycle with a
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle.
- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external.
## Latest source-built run
@@ -50,4 +57,18 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
## Sixth source-built run
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source.
## Immediate config reconciliation regression test
`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance.
## Source-built acceptance — 2026-11-12
`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera.<id>.enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing.
## Camera status contract acceptance
For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, reject its report before camera assignment, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled.
A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence.
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
stamp="$(date +%s)-$RANDOM"
project="heimdall-157-${stamp}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
env_next="$temp_dir/acceptance.env.next"
compose_override="$temp_dir/compose.override.yml"
config_headers="$temp_dir/config.headers"
config_body="$temp_dir/config.json"
stage=setup
local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent")
compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override")
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
if (( status != 0 )); then
printf 'acceptance failed at stage=%s\n' "$stage" >&2
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null |
grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true
fi
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
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
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
rm -f -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'cleanup verification failed for %s\n' "$project" >&2
status=1
else
printf 'cleanup verified: project resources absent; exact local tags absent\n'
fi
exit "$status"
}
port=$((20000 + RANDOM % 20000))
pg_port=$((port + 1))
db_password=$(openssl rand -hex 24)
jwt_key=$(openssl rand -hex 48)
jwt_refresh=$(openssl rand -hex 48)
cat >"$env_file" <<EOF
POSTGRES_DB=heimdall_acceptance
POSTGRES_USER=acceptance
POSTGRES_PASSWORD=$db_password
POSTGRES_PORT=127.0.0.1:$pg_port
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=acceptance;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh
JWT__ISSUER=heimdall-acceptance
JWT__AUDIENCE=heimdall-acceptance-api
WEB_PORT=127.0.0.1:$port
ACCEPTANCE_PROJECT=$project
DOCKER_GID=0
HEIMDALL_NETWORK_NAME=${project}-network
HEIMDALL_TEST_SITE_TOKEN=placeholder-token
EOF
cat >"$compose_override" <<'EOF'
services:
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
heimdall-agent:
image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent
build:
context: ..
dockerfile: docker/Dockerfile.agent
user: "1654:1654"
environment:
Agent__CentralUrl: http://heimdall:8080
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required}
Agent__AgentName: camera-157-agent
Agent__HeartbeatIntervalSeconds: "5"
Agent__StateDirectory: /var/lib/heimdall
Agent__DiscoveryEnabled: "false"
volumes:
- agent_state:/var/lib/heimdall
depends_on:
heimdall:
condition: service_healthy
synthetic-camera-publisher:
condition: service_started
networks:
- heimdall-net
synthetic-camera:
image: bluenviron/mediamtx:1.21.3
volumes:
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
networks:
- heimdall-net
synthetic-camera-publisher:
image: jrottenberg/ffmpeg:7.1-alpine
entrypoint: ["/bin/sh", "-c"]
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"]
depends_on:
- synthetic-camera
networks:
- heimdall-net
volumes:
agent_state:
EOF
# The cleanup trap is installed before any image build or Compose start.
trap cleanup EXIT
chmod 600 "$env_file"
api="http://127.0.0.1:$port"
compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; }
contract_failures=0
wait_http() {
for _ in $(seq 1 90); do
if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi
sleep 2
done
return 1
}
request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; }
ffmpeg_count() {
compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"'
}
wait_count() {
expected=$1; seconds=$2
for _ in $(seq 1 "$((seconds * 20))"); do
count=$(ffmpeg_count)
observed_at_ns=$(date +%s%N)
(( count <= 1 )) || return 1
if [[ "$count" == "$expected" ]]; then
count_observed_at_ns=$observed_at_ns
return 0
fi
sleep 0.05
done
return 1
}
wait_ack() {
expected_enabled=$1
for _ in $(seq 1 100); do
request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body"
wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers")
actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body")
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents")
if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then
acknowledged_version=$wanted
return 0
fi
sleep 0.1
done
return 1
}
wait_agent_reconnected_and_ack() {
restarted_at_ns=$1
expected_version=$2
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents")
status=$(jq -r '.status // empty' <<<"$agent")
heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent")
applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent")
applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent")
if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then
heartbeat_ns=$(date -u -d "$heartbeat" +%s%N)
applied_at_ns=$(date -u -d "$applied_at" +%s%N)
if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then
return 0
fi
fi
sleep 1
done
return 1
}
printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}"
stage=build
compose build heimdall heimdall-agent
stage=central-startup
compose up -d postgresql heimdall
wait_http
stage=bootstrap
admin_password="Tst!$(openssl rand -hex 20)A9"
bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin")
admin_token=$(jq -er '.accessToken' <<<"$bootstrap")
printf 'synthetic Admin bootstrap accepted\n'
site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites")
site_id=$(jq -er '.id' <<<"$site")
printf 'synthetic site created\n'
site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token')
grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next"
printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next"
mv "$env_next" "$env_file"
camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras")
camera_id=$(jq -er '.id' <<<"$camera")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
printf 'synthetic camera created\n'
stage=agent-startup
compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent
agent_id=
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents")
[[ -n "$agent_id" ]] && break
sleep 1
done
[[ -n "$agent_id" ]]
printf 'Agent registered\n'
request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null
stage=initial-on
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
off_once() {
started=$(date +%s%N)
result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status")
response_ms=$((( $(date +%s%N) - started ) / 1000000))
[[ $(jq -r '.status' <<<"$result") == Disabled ]]
within_contract=1
if ! wait_count 0 2; then
within_contract=0
wait_count 0 10 || return 1
fi
elapsed_ms=$((( count_observed_at_ns - started ) / 1000000))
printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract"
if (( ! within_contract || elapsed_ms >= 2000 )); then
contract_failures=$((contract_failures + 1))
fi
wait_ack false
}
for iteration in 1 2 3; do
stage="cycle-${iteration}-off"
off_once
stage="cycle-${iteration}-on"
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
count=$(ffmpeg_count)
[[ "$count" == 1 ]]
done
stage=agent-restart-on
compose restart heimdall-agent
wait_count 1 10
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
[[ "$old_agent_id" == "$agent_id" ]]
wait_ack true
stage=final-off
off_once
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
compose restart heimdall-agent
post_off_restart_returned_ns=$(date +%s%N)
wait_count 0 10
wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version"
stage=central-restart-off
compose restart heimdall
central_restart_returned_ns=$(date +%s%N)
wait_http
sleep 2
[[ $(ffmpeg_count) == 0 ]]
camera=$(request "$api/api/cameras/$camera_id")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
wait_ack false
wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version"
printf 'restart OFF persisted; camera config digest acknowledged\n'
if (( contract_failures > 0 )); then
printf 'contract failures=%s\n' "$contract_failures" >&2
exit 1
fi
+2 -2
View File
@@ -19,7 +19,7 @@ For installer, Compose, image, and documentation work that can proceed independe
- Optional Agent public-IP discovery has no built-in provider hostname; configure `Agent:PublicIpResolverUrl` with an HTTPS endpoint or leave it empty to report no public IP. Validate the URL before creating the HTTP client.
- Server-side API calls from Blazor circuits must prefer the process's Kestrel loopback binding over a retained browser `Host`; a public reverse-proxy host may not be reachable from inside the Central container. Normalize wildcard Kestrel binds (`0.0.0.0`, `[::]`, and `+`) to loopback while preserving the bound port.
- Installer scripts should embed the official Heimdall source base as their standalone default and allow `HEIMDALL_SOURCE_BASE_URL` to override it for reviewed revisions or mirrors. Use it only for Heimdall-owned source assets; keep vendor dependencies on their official distribution sources.
- Configure the Gitea API endpoint used by Renovate through the Actions variable `GITEA_API_ENDPOINT`; do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- Configure the Forgejo API endpoint used by Renovate through the Actions variable `FORGEJO_API_ENDPOINT`; Forgejo reserves variable names beginning with `GITEA_`. Do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- Keep Compose network names project-scoped by omitting a fixed `networks.*.name`, especially for disposable validation projects.
## Deployment behavior
@@ -45,7 +45,7 @@ For installer, Compose, image, and documentation work that can proceed independe
## 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. 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 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.
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.
@@ -0,0 +1,22 @@
---
name: database-migration-startup
description: Diagnose and validate Heimdall Central's EF Core PostgreSQL migration startup, including first boot, restart, retry exhaustion, and recovery.
---
# Database migration startup
`src/Heimdall.Web/Program.cs` calls `Program.ApplyMigrationsAsync` before configuring recurring Hangfire jobs and seeding identity data. The method uses one `AppDbContext`, retries a failed `Database.MigrateAsync` five times with exponential delays, logs the terminal exception at Critical, then rethrows so Central cannot become ready with a failed migration.
For startup incidents, correlate the EF `CommandError` with the following `Program` retry/final logs. A failed EF command log alone does not prove that startup failed: a later retry may have succeeded. Preserve the provider exception and SQLSTATE when available, but never record a connection string, password, user identifier, or database row. Do not suppress EF command errors to hide a symptom.
## Acceptance
Run `bash skills/database-migration-startup/acceptance.sh` from a clean checkout. The recipe builds Central from this source with one unique local image tag, uses a fresh PostgreSQL database and generated credentials, and checks:
1. First boot applies migrations and `/healthz` becomes healthy.
2. A second startup against the migrated database remains healthy.
3. A synthetic database role with access to the database/schema but no `SELECT` on `public.__EFMigrationsHistory` causes migration startup to exhaust all five attempts, emit the final Critical failure, and exit nonzero without logging migration success.
4. Granting that role `SELECT` and restarting Central allows migration startup and health checks to succeed.
5. The EXIT trap removes only this Compose project and its exact image tag, then verifies that its containers, volumes, network, and image are absent. Shared PostgreSQL and .NET base images are retained.
This synthetic permission failure verifies fail-closed and recovery behavior; it does not establish the cause of a separate deployment's EF error. Record production evidence only when an event includes the provider exception/SQLSTATE and correlated startup outcome.
@@ -0,0 +1,198 @@
#!/usr/bin/env bash
set -Eeuo pipefail
project="heimdall-migration-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 4)"
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
failure_override="$temp_dir/compose.failure.yml"
recovery_override="$temp_dir/compose.recovery.yml"
compose_file="$(git rev-parse --show-toplevel)/docker/docker-compose.yml"
local_image_tags=("heimdall:${project}-central")
web_port="$(python3 - <<'PY'
import socket
s = socket.socket()
s.bind(('127.0.0.1', 0))
print(s.getsockname()[1])
s.close()
PY
)"
db_name="${project//-/_}"
db_user="migration_owner_${project//-/_}"
db_password="$(openssl rand -hex 24)"
probe_password="$(openssl rand -hex 24)"
jwt_key="$(openssl rand -base64 48 | tr -d '\n')"
jwt_refresh_key="$(openssl rand -base64 48 | tr -d '\n')"
cat > "$env_file" <<EOF
POSTGRES_DB=$db_name
POSTGRES_USER=$db_user
POSTGRES_PASSWORD=$db_password
DATABASE_URL=Host=postgresql;Port=5432;Database=$db_name;Username=$db_user;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh_key
JWT__ISSUER=$project
JWT__AUDIENCE=$project
ASPNETCORE_ENVIRONMENT=Development
Sentry__Dsn=
SENTRY_DSN=
WEB_PORT=$web_port
HEIMDALL_NETWORK_NAME=${project}_net
ACCEPTANCE_PROJECT=$project
MIGRATION_PROBE_PASSWORD=$probe_password
EOF
chmod 600 "$env_file"
cat > "$compose_override" <<'EOF'
services:
postgresql:
ports: !override []
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
ports: !override
- "127.0.0.1:${WEB_PORT}:8080"
EOF
cat > "$failure_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cat > "$recovery_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" down --volumes --remove-orphans || cleanup_failed=1
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
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
python3 - "$env_file" "$compose_override" "$failure_override" "$recovery_override" <<'PY' || cleanup_failed=1
import pathlib
import sys
for name in sys.argv[1:]:
pathlib.Path(name).unlink(missing_ok=True)
PY
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable migration recipe cleanup failed for project %s\n' "$project" >&2
status=1
else
printf 'Cleanup verified: project containers/volumes/network and exact tag absent (%s).\n' "${local_image_tags[*]}"
fi
exit "$status"
}
trap cleanup EXIT
for tag in "${local_image_tags[@]}"; do
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Unique acceptance image tag already exists: %s\n' "$tag" >&2
exit 1
fi
done
compose() {
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" "$@"
}
compose config --quiet
compose up -d --build
base_url="http://127.0.0.1:$web_port"
wait_healthy() {
for attempt in $(seq 1 120); do
if curl --fail --silent "$base_url/healthz" -o /dev/null; then return 0; fi
sleep 2
done
return 1
}
wait_healthy || { echo 'Central did not become healthy after first migration.' >&2; exit 1; }
echo 'First boot: PostgreSQL fresh schema migrated; Central healthz returned HTTP 200.'
compose restart heimdall
wait_healthy || { echo 'Central did not recover against the migrated database.' >&2; exit 1; }
echo 'Restart: Central healthz returned HTTP 200 on the migrated schema.'
postgres_container="$(compose ps -q postgresql)"
[[ -n "$postgres_container" ]] || { echo 'PostgreSQL container was not found.' >&2; exit 1; }
docker exec -i "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-v probe_password="$probe_password" <<'SQL'
CREATE ROLE migration_probe LOGIN PASSWORD :'probe_password';
SELECT format('GRANT CONNECT ON DATABASE %I TO migration_probe', current_database()) \gexec
GRANT USAGE ON SCHEMA public TO migration_probe;
GRANT CREATE ON SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO migration_probe;
GRANT USAGE, CREATE ON SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA hangfire TO migration_probe;
REVOKE SELECT ON TABLE public."__EFMigrationsHistory" FROM migration_probe;
SQL
compose -f "$failure_override" up -d --force-recreate heimdall
web_container="$(compose -f "$failure_override" ps -q heimdall)"
[[ -n "$web_container" ]] || { echo 'Central failure-test container was not found.' >&2; exit 1; }
failure_state=""
for attempt in $(seq 1 90); do
failure_state="$(docker inspect -f '{{.State.Status}}' "$web_container" 2>/dev/null || true)"
[[ "$failure_state" == exited ]] && break
sleep 1
done
[[ "$failure_state" == exited ]] || { echo 'Central did not exit on a permanent migration permission failure.' >&2; exit 1; }
failure_exit_code="$(docker inspect -f '{{.State.ExitCode}}' "$web_container")"
[[ "$failure_exit_code" != 0 ]] || { echo 'Central exited successfully despite the permanent migration failure.' >&2; exit 1; }
failure_logs="$(docker logs "$web_container" 2>&1)"
application_logs="$(grep -E 'Applying database migrations \(attempt|Database migration attempt .* failed|Failed to apply database migrations after 5 attempts|Database migrations applied successfully|permission denied' <<<"$failure_logs" | grep -v 'HttpTransport: Envelope')"
attempt_count="$(grep -c 'Applying database migrations (attempt' <<<"$application_logs" || true)"
retry_count="$(grep -c 'Database migration attempt .* failed' <<<"$application_logs" || true)"
terminal_count="$(grep -c 'Failed to apply database migrations after 5 attempts' <<<"$application_logs" || true)"
success_count="$(grep -c 'Database migrations applied successfully' <<<"$application_logs" || true)"
[[ "$attempt_count" -eq 5 && "$retry_count" -eq 4 && "$terminal_count" -eq 1 && "$success_count" -eq 0 ]] || {
printf 'Retry log counts: attempts=%s retries=%s terminal=%s successes=%s\n' \
"$attempt_count" "$retry_count" "$terminal_count" "$success_count" >&2
grep -E 'Applying database migrations \(attempt|Database migration attempt|Failed to apply database migrations|Database migrations applied successfully' \
<<<"$application_logs" | cut -c1-240 >&2 || true
echo 'Permanent failure did not show five attempts, four retries, one terminal failure, and zero success logs.' >&2
exit 1
}
grep -qi 'permission denied' <<<"$application_logs" || {
echo 'The synthetic failure did not report the expected history-table permission denial.' >&2
exit 1
}
echo 'Permanent failure: permission denied on migration history; five attempts, four retries, final Critical error, nonzero exit, no migration-success log.'
docker exec "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-c 'GRANT SELECT ON TABLE public."__EFMigrationsHistory" TO migration_probe;' >/dev/null
compose -f "$recovery_override" up -d --force-recreate heimdall
wait_healthy || {
echo 'Central did not recover after granting migration-history access.' >&2
docker logs "$(compose -f "$recovery_override" ps -q heimdall)" 2>&1 \
| grep -Ei 'failed|error|permission denied|database migration|migration.*success' \
| grep -v 'HttpTransport: Envelope' | cut -c1-240 | tail -n 20 >&2 || true
exit 1
}
echo 'Recovery: granting history-table SELECT allowed startup; Central healthz returned HTTP 200.'
+3
View File
@@ -16,6 +16,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`.
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
@@ -28,6 +29,8 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
+182
View File
@@ -0,0 +1,182 @@
#!/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')"
flow="${HEIMDALL_ACCEPTANCE_FLOW:-create-login}"
if [[ "$flow" != "create-login" && "$flow" != "2fa-cookie" ]]; then
echo 'HEIMDALL_ACCEPTANCE_FLOW must be create-login or 2fa-cookie' >&2
exit 2
fi
project="heimdall-auth-${flow}-${suffix}"
central_image="heimdall:${project}-central"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
override_file="$temp_dir/compose.override.yml"
compose_file="$repo_root/docker/docker-compose.yml"
local_image_tags=("$central_image")
compose_port=$(python3 - <<'PY'
import socket
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
print(sock.getsockname()[1])
PY
)
web_port=$(python3 - <<'PY'
import socket
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
print(sock.getsockname()[1])
PY
)
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" \
down --volumes --remove-orphans || cleanup_failed=1
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
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" "$override_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then status=1; fi
exit "$status"
}
trap cleanup EXIT
pg_password=$(python3 - <<'PY'
import secrets, string
alphabet=string.ascii_letters+string.digits
print(''.join(secrets.choice(alphabet) for _ in range(40)))
PY
)
jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
admin_password="${admin_password}Aa1!"
cat >"$env_file" <<EOF
ACCEPTANCE_PROJECT=$project
POSTGRES_DB=heimdall_acceptance
POSTGRES_USER=heimdall_acceptance
POSTGRES_PASSWORD=$pg_password
POSTGRES_PORT=$compose_port
WEB_PORT=$web_port
DATABASE_URL="Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=heimdall_acceptance;Password=$pg_password;Timeout=60;Command Timeout=300"
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$refresh_key
JWT__ISSUER=heimdall-acceptance
JWT__AUDIENCE=heimdall-acceptance
ASPNETCORE_ENVIRONMENT=Production
HEIMDALL_NETWORK_NAME=${project}-net
EOF
cat >"$override_file" <<EOF
services:
heimdall:
image: $central_image
environment:
Database__MigrateOnStartup: "true"
EOF
printf 'Disposable project: %s\nCentral image: %s\n' "$project" "$central_image"
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" up -d --build
base_url="http://127.0.0.1:$web_port"
deadline=$((SECONDS + 300))
until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do
if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi
sleep 2
done
printf 'Central /healthz: HTTP 200\n'
BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY'
import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request
base=os.environ['BASE_URL']
flow=os.environ['ACCEPTANCE_FLOW']
def request(method, path, body=None, token=None, cookie=None):
headers={'Content-Type':'application/json'}
if token: headers['Authorization']='Bearer '+token
if cookie: headers['Cookie']=cookie
data=json.dumps(body).encode() if body is not None else None
req=urllib.request.Request(base+path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=20) as response:
return response.status, response.read(), response.headers
except urllib.error.HTTPError as error:
return error.code, error.read(), error.headers
def post(path, body, token=None):
status, payload, _=request('POST', path, body, token)
return status, payload
def totp(key):
secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8))
counter=int(time.time())//30
digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest()
offset=digest[-1]&15
value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff
return f'{value%1000000:06d}'
status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'})
if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}')
if flow == 'create-login':
status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']})
if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}')
admin=json.loads(payload)['accessToken']
for role in ('Viewer','Supervisor'):
email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test'
password='CreateLogin!'+secrets.token_urlsafe(18)+'A1'
status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin)
if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}')
user_id=json.loads(payload)['id']
status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin)
if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}')
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}')
if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token')
print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)')
else:
admin=json.loads(bootstrap_payload)['accessToken']
email='acceptance-admin@heimdall.test'
password=os.environ['ACCEPTANCE_ADMIN_PASSWORD']
status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin)
if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}')
shared_key=json.loads(payload)['sharedKey']
# ResetAuthenticatorKey rotates the security stamp; renew the setup session
# before the authenticated confirmation call.
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}')
admin=json.loads(payload)['accessToken']
status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin)
if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}')
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}')
challenge=json.loads(payload)
if not challenge.get('requires2fa') or not challenge.get('challengeId'):
raise SystemExit('2FA login did not return an authenticator challenge')
status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)})
if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}')
access_token=json.loads(payload)['accessToken']
status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token})
if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}')
set_cookie=headers.get('Set-Cookie','').split(';',1)[0]
if not set_cookie.startswith('.Heimdall.Auth='):
raise SystemExit('2FA cookie sign-in returned no auth cookie')
status,_,_=request('GET','/api/users/me',cookie=set_cookie)
if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}')
print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)')
PY
@@ -0,0 +1,23 @@
---
name: installer-checksum-acceptance
description: Build and verify the versioned Central installer checksum asset and both server bootstrap verification paths.
---
# Central installer checksum acceptance
Use this workflow when changing `install/install-server.sh`, `install/install-server.ps1`, `scripts/ci/package.sh`, or the release asset set in `scripts/ci/release-gitea.py`.
## Release contract
- `package.sh` creates `heimdall-installers-<version>.zip.sha256` beside the ZIP. Its single standard `sha256sum` line names the ZIP asset exactly, with no workspace-relative path.
- `release-gitea.py` requires and publishes both files before making a release visible. The sidecar is part of the exact expected asset set for already-published releases.
- The raw Linux and Windows bootstraps prefer a valid `sha256:<64 hex>` digest from the matching release API asset. If the digest is absent or null, they find the correspondingly named checksum asset, require an HTTPS download URL and exactly one checksum line naming the ZIP, download the ZIP, and compare its SHA-256 before extraction or execution.
- A malformed, non-null API digest fails closed. Do not fall back from an invalid digest or calculate the expected checksum from the ZIP that is being verified.
## Acceptance
1. Run `python3 scripts/ci/accept-release-offline.py` in a clean dedicated checkout. Its TLS loopback Gitea double and fake Docker CLI must prove release asset publication, the API digest-present path, the Forgejo-compatible `digest: null` sidecar path, rejection of a mismatched sidecar, and fail-closed behavior for a malformed non-null API digest. Assert the expected installer asset names and the sidecar content against the produced ZIP.
2. Run `python3 -m unittest scripts.ci.test_ci` (or the repository's equivalent CI policy test command) and verify release asset fixtures include the sidecar.
3. Run `bash -n install/install-server.sh`; if `pwsh` is available, parse `install/install-server.ps1` without invoking Windows-only installation actions.
4. For any disposable Compose validation required by the behavior change, follow `skills/compose-disposable-recipe/SKILL.md`: use source-built unique tags and isolated credentials/ports/volumes, install cleanup before build/start, and verify project resources and exact image tags are absent afterward.
5. Record local and CI evidence in the Gitea issue and PR. Do not claim a production Gitea release, `/releases/latest`, Docker Hub, runner, or deployed installer was validated by the offline API double.
+5 -3
View File
@@ -10,18 +10,20 @@ The Linux and Windows server installers run optional Compose files with the inst
## RustFS
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
- Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files.
- Keep the named data volume and shared `heimdall-net` behavior intact.
## coturn
- 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 shell entrypoint and pass it to `--static-auth-secret`. Do not print the value.
- 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.
- Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings.
- Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults.
- Set `COTURN_EXTERNAL_IP` only when NAT requires coturn to advertise an explicit public address. The operator must forward the listener and relay range through firewalls/NAT.
- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address.
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
## Acceptance
Run both services in one uniquely named disposable Compose project using generated secrets and unique loopback listener ports. Use `docker compose --project-directory <install-root> --env-file <generated-env> -f <source-compose> -p <project> config` to prove the installer root resolves `optional/secrets/` correctly. Start RustFS and coturn; verify RustFS `/health` and S3 authentication and coturn startup plus a TURN REST authenticated allocation from a test client if available. State separately whether the real TURN allocation succeeded. Tear down only that project, verify its containers/volumes/networks are absent, and keep upstream images. No local images should be built by this recipe.
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
+226
View File
@@ -0,0 +1,226 @@
#!/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-optional-services-${suffix}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
install_root="$temp_dir/install-root"
secret_dir="$install_root/optional/secrets"
env_file="$temp_dir/acceptance.env"
override_file="$temp_dir/compose.override.yml"
turn_log="$temp_dir/turn-client.log"
rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml"
coturn_compose="$repo_root/docker/docker-compose.coturn.yml"
local_image_tags=()
mkdir -p "$secret_dir"
compose() {
docker compose --project-directory "$install_root" --env-file "$env_file" \
-f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \
-p "$project" "$@"
}
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
compose 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
# `compose run --rm` may leave a one-off test container behind if the
# client exits during shutdown; remove only containers carrying this
# recipe's unique Compose project label.
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 'No local images built; upstream service images 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" "$override_file" "$turn_log" \
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
"$secret_dir/coturn_secret" || cleanup_failed=1
rmdir -- "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if ((cleanup_failed)); then
printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
read -r rustfs_api_port rustfs_console_port coturn_port relay_min relay_max < <(python3 - <<'PY'
import random, socket
used=set()
def free_port(protocols):
for port in random.sample(range(20000, 60000), 2000):
if port in used: continue
sockets=[]
try:
for kind in protocols:
sock=socket.socket(socket.AF_INET,kind)
sock.bind(('127.0.0.1',port))
sockets.append(sock)
used.add(port)
return port
except OSError:
pass
finally:
for sock in sockets: sock.close()
raise SystemExit('No free loopback ports found')
def free_udp_range(width):
for start in random.sample(range(25000, 55000-width), 2000):
if any(port in used for port in range(start,start+width)): continue
sockets=[]
try:
for port in range(start,start+width):
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',port))
sockets.append(sock)
used.update(range(start,start+width))
return start,start+width-1
except OSError:
pass
finally:
for sock in sockets: sock.close()
raise SystemExit('No free contiguous UDP relay ports found')
print(free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,)),
free_port((socket.SOCK_STREAM,socket.SOCK_DGRAM)), *free_udp_range(20))
PY
)
rustfs_access_key="acceptance$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')"
rustfs_secret_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
coturn_secret=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
coturn_username=acceptance
printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key"
printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key"
printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret"
chmod 600 "$secret_dir"/*
cat > "$env_file" <<EOF
RUSTFS_API_PORT=$rustfs_api_port
RUSTFS_CONSOLE_PORT=$rustfs_console_port
COTURN_PORT=$coturn_port
COTURN_RELAY_PORT_MIN=$relay_min
COTURN_RELAY_PORT_MAX=$relay_max
COTURN_REALM=heimdall.acceptance.test
COTURN_SECRET=$coturn_secret
COTURN_USERNAME=$coturn_username
RUSTFS_ACCESS_KEY=$rustfs_access_key
RUSTFS_SECRET_KEY=$rustfs_secret_key
ACCEPTANCE_NETWORK=${project}-heimdall-net
EOF
chmod 600 "$env_file"
cat > "$override_file" <<'EOF'
services:
turn-test:
image: coturn/coturn:4.6
pull_policy: always
profiles: [acceptance]
entrypoint: ["/bin/sh", "-c"]
command:
- >-
exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478
-W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn
environment:
COTURN_SECRET: ${COTURN_SECRET}
COTURN_USERNAME: ${COTURN_USERNAME}
depends_on:
- coturn
networks:
heimdall-net:
name: ${ACCEPTANCE_NETWORK}
external: false
EOF
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
compose config --quiet
compose up -d rustfs coturn
base_url="http://127.0.0.1:$rustfs_api_port"
deadline=$((SECONDS + 180))
until curl -fsS "$base_url/health" >/dev/null 2>&1; do
if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi
sleep 2
done
printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \
"$rustfs_api_port" "$rustfs_console_port"
RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \
RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY'
import datetime, hashlib, hmac, os, urllib.error, urllib.request
access = os.environ['RUSTFS_ACCESS_KEY']
secret = os.environ['RUSTFS_SECRET_KEY']
host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT']
path = '/acceptance'
payload_hash = hashlib.sha256(b'').hexdigest()
now = datetime.datetime.now(datetime.timezone.utc)
amz_date = now.strftime('%Y%m%dT%H%M%SZ')
date = now.strftime('%Y%m%d')
canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n'
signed_headers = 'host;x-amz-content-sha256;x-amz-date'
canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}'
scope = f'{date}/us-east-1/s3/aws4_request'
to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest()
def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest()
key = sign(('AWS4' + secret).encode(), date)
key = sign(key, 'us-east-1')
key = sign(key, 's3')
key = sign(key, 'aws4_request')
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}'
request = urllib.request.Request(
f'http://{host}{path}', data=b'', method='PUT',
headers={'Host': host, 'x-amz-content-sha256': payload_hash,
'x-amz-date': amz_date, 'Authorization': authorization})
try:
with urllib.request.urlopen(request, timeout=15) as response:
if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status')
except urllib.error.HTTPError as error:
from xml.etree import ElementTree
body = error.read()
try: code = ElementTree.fromstring(body).findtext('{*}Code')
except ElementTree.ParseError: code = None
raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})')
PY
printf 'RustFS S3 authenticated bucket creation: passed.\n'
if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then
echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' "$turn_log" | tail -30 >&2 || true
echo 'sanitized coturn server diagnostics:' >&2
compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' | tail -40 >&2 || true
exit 1
fi
printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \
"$coturn_port" "$relay_min" "$relay_max"
for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do
if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then
echo 'A generated service secret appeared in container logs.' >&2
exit 1
fi
done
printf 'Verified generated service secrets are absent from container logs.\n'
+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, digest-pinned Docker image requirements, 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 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.
## Acceptance evidence
+3 -3
View File
@@ -19,9 +19,9 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
- Runs for the same ref are serialized so a slower older `main` run cannot overwrite a newer `latest` image.
- A `MAJOR.MINOR.PATCH` tag (optional prerelease suffix allowed) is a version release. It validates the complete source and builds/scans server, Agent CPU, and Agent GPU images once each. The verified images are pushed to Docker Hub as `sha-<full-sha>` and the application version.
- After merge of a release-worthy PR, use the current stable tag and all unreleased changes to calculate the SemVer increment according to `pr-release-versioning`. Fetch `main`, verify the merged commit is reachable from it, verify the selected tag is unused, create an annotated tag at the merged commit, and push it to trigger this workflow. Never ask the user to choose a version or release, infer a version from the PR title alone, or force-update an existing tag. Documentation and skills-only changes do not get a tag.
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, its `heimdall-installers-<version>.zip.sha256` sidecar, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and unrelated checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), verifies the Gitea SHA-256 asset digest, downloads that version's ZIP, and runs its version-pinned script. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. The package job writes a checksum sidecar with the archive's exact asset filename. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), uses a valid Gitea SHA-256 asset digest when present and otherwise downloads and parses the published sidecar, then verifies the ZIP before running its version-pinned script. A malformed non-null Gitea digest is a hard failure; it must not be silently replaced by the sidecar. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
- Central stores only the public Forgejo origin in `updates.forgepublicurl` and constructs the canonical Heimdall `releases/latest` API route in code. Preserve the legacy setting migration and never make the derived API route editable in Settings.
- The Site Install panel displays the configured signed release version and only exposes native install commands when the signed manifest, key, and platform assets are available. Docker commands also require a verified image digest.
@@ -34,7 +34,7 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
## Offline end-to-end acceptance
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP and its published checksum sidecar, installer bootstrap with both a valid API digest and `digest: null`, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
For build-scope changes, validate that documentation-only, Central-only, Agent-only, and shared-project file sets produce the intended image outputs. For behavior/deployment changes, also run the required disposable source-built Compose recipe with generated credentials, ports, project name, and unique local image tags. Its EXIT trap must verify project containers, volumes, and networks are gone and remove/verify absence of only its exact image tags.
+3 -2
View File
@@ -7,10 +7,11 @@ description: Diagnose and maintain Renovate dependency updates through Gitea Act
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `GITEA_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files.
- The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `FORGEJO_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files. Forgejo reserves variable names beginning with `GITEA_` and rejects them.
- The endpoint must be the HTTPS Forgejo API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR.
- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials.
- Run `bash skills/renovate-automation/acceptance.sh` after changing the preflight or its endpoint wiring. It exercises valid and rejected synthetic credentials over an isolated HTTPS mock in Compose; the test container trusts only the generated self-signed certificate for its local fixture.
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
- For operational changes, update the Renovate Gitea issue with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
set -Eeuo pipefail
project="heimdall-renovate-acceptance-$(date -u +%Y%m%d%H%M%S)-$RANDOM"
repo_root=$(git rev-parse --show-toplevel)
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
compose_file="$temp_dir/compose.yml"
runner_file="$temp_dir/acceptance.mjs"
cert_file="$temp_dir/mock.crt"
key_file="$temp_dir/mock.key"
local_image_tags=()
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans || cleanup_failed=1
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 cleanup_failed=1; fi
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
rm -f -- "$compose_file" "$runner_file" "$cert_file" "$key_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
echo "Disposable Compose cleanup failed for $project" >&2
status=1
else
echo "Verified no project containers, volumes, or networks; no local images built ($project)"
fi
exit "$status"
}
trap cleanup EXIT
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$key_file" -out "$cert_file" \
-subj "/CN=localhost" -addext "subjectAltName=IP:127.0.0.1" -days 1 >/dev/null 2>&1
cat > "$runner_file" <<'NODE'
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createServer } from 'node:https';
import { checkGiteaAccess } from '/workspace/scripts/ci/renovate-preflight.mjs';
const requests = [];
const server = createServer({
key: readFileSync('/acceptance/mock.key'),
cert: readFileSync('/acceptance/mock.crt'),
}, (request, response) => {
requests.push({ path: request.url, authorization: request.headers.authorization });
if (request.headers.authorization !== 'token synthetic-valid') {
response.writeHead(401, { 'content-type': 'application/json' });
response.end('{"message":"credential rejected"}');
return;
}
response.writeHead(200, { 'content-type': 'application/json' });
response.end('{}');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const endpoint = `https://127.0.0.1:${server.address().port}/api/v1`;
await checkGiteaAccess(endpoint, 'synthetic-valid');
await assert.rejects(
checkGiteaAccess(endpoint, 'synthetic-invalid'),
error => error.message.includes('HTTP 401') &&
error.message.includes('RENOVATE_TOKEN') &&
!error.message.includes('synthetic-invalid') &&
!error.message.includes('credential rejected'),
);
assert.deepEqual(requests.map(({ path }) => path), [
'/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall',
'/api/v1/user',
]);
assert.ok(requests.every(({ authorization }) =>
['token synthetic-valid', 'token synthetic-invalid'].includes(authorization)));
console.log('HTTPS mock preflight accepted valid and rejected invalid synthetic credentials without exposing response details.');
} finally {
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}
NODE
cat > "$compose_file" <<EOF
services:
acceptance:
image: node:22-alpine
working_dir: /workspace
volumes:
- "$repo_root:/workspace:ro"
- "$temp_dir:/acceptance:ro"
environment:
NODE_EXTRA_CA_CERTS: /acceptance/mock.crt
command: ["node", "/acceptance/acceptance.mjs"]
EOF
docker compose -p "$project" -f "$compose_file" config --quiet
docker compose -p "$project" -f "$compose_file" run --rm acceptance
+1 -1
View File
@@ -11,7 +11,7 @@ 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 a digest-pinned image reference and update key. Preserve these gates so the panel never offers a nonfunctional installer.
- 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.
- 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.
- 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`.
@@ -53,6 +53,7 @@ public sealed class SnapshotPipelineService : BackgroundService
private readonly FrameResizer? _resizer;
private readonly ILogger<SnapshotPipelineService> _logger;
private readonly SemaphoreSlim _syncLock = new(1, 1);
private readonly SemaphoreSlim _configChanged = new(0, 1);
private readonly Dictionary<Guid, string> _streamUrls = new();
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
@@ -154,8 +155,18 @@ public sealed class SnapshotPipelineService : BackgroundService
// (e.g. camera settings applied before we subscribed).
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0)
var periodicSyncDue = false;
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
{
wait.CancelAfter(TimeSpan.FromSeconds(1));
try { await _configChanged.WaitAsync(wait.Token); }
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
{
periodicSyncDue = true;
}
}
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || periodicSyncDue && DateTime.UtcNow.Second % 30 == 0)
await SyncStreamsAsync(stoppingToken);
}
}
@@ -181,6 +192,8 @@ public sealed class SnapshotPipelineService : BackgroundService
private void OnCameraConfigChanged(object? sender, EventArgs e)
{
Interlocked.Exchange(ref _configDirty, 1);
try { _configChanged.Release(); }
catch (SemaphoreFullException) { }
}
private async Task SyncStreamsAsync(CancellationToken ct)
@@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
var oldStatus = camera.Status;
var newStatus = camera.Status == CameraStatus.Disabled
? CameraStatus.Online
? CameraStatus.Offline
: CameraStatus.Disabled;
camera.SetStatus(newStatus);
@@ -633,7 +633,7 @@ else
if (result.Succeeded && result.Data is not null)
{
_camera.Status = result.Data.Status;
Snackbar.Add(result.Data.Status == "Online" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
Snackbar.Add(result.Data.Status != "Disabled" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
}
else _editError = result.ErrorMessage ?? Text["CameraDetail_StatusError"];
}
@@ -638,7 +638,7 @@
{
camera.Status = result.Data.Status;
Snackbar.Add(
result.Data.Status == "Online" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
result.Data.Status != "Disabled" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
Severity.Success);
}
else
@@ -246,15 +246,15 @@ else if (_method == "windows-service")
release?.Assets.Count > 0;
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
_agentImageReference = LatestImageReference(release.ContainerImage);
if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) &&
!string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest))
_agentGpuImageReference = $"{release.ContainerImageGpu}@{release.ContainerImageGpuDigest}";
_agentGpuImageReference = LatestImageReference(release.ContainerImageGpu);
_updatePublicKeyPem = release?.UpdatePublicKeyPem;
}
catch
{
// Native installers fetch signed release metadata directly; Docker needs a verified image reference and key.
// Native installers fetch signed release metadata directly; Docker needs verified image metadata and key.
}
finally
{
@@ -262,6 +262,14 @@ else if (_method == "windows-service")
}
}
private static string LatestImageReference(string image)
{
var lastSlash = image.LastIndexOf('/');
var lastColon = image.LastIndexOf(':');
var repository = lastColon > lastSlash ? image[..lastColon] : image;
return $"{repository}:latest";
}
private string ComposeYaml
{
get
@@ -277,6 +285,7 @@ else if (_method == "windows-service")
services:
heimdall-agent:
image: {{image}}
pull_policy: always
container_name: heimdall-agent-{{safeName}}
restart: unless-stopped
user: "1654:1654"
@@ -307,6 +316,7 @@ else if (_method == "windows-service")
agent-state-init:
image: {{image}}
pull_policy: always
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
@@ -337,7 +347,7 @@ else if (_method == "windows-service")
var name = "heimdall-agent-" + Slugify(SiteName);
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
return $"docker run --pull always -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
(_useGpuImage ? "--gpus all " : "") +
"--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " +
"-v /var/run/docker.sock:/var/run/docker.sock " +
@@ -370,7 +380,7 @@ else if (_method == "windows-service")
var name = "heimdall-agent-" + Slugify(SiteName);
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
var args = new List<string> { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
var args = new List<string> { "run", "--pull", "always", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
if (_useGpuImage) args.AddRange(["--gpus", "all"]);
args.AddRange([
"-e", "Agent__CentralUrl=" + CentralUrl,
@@ -10,6 +10,7 @@ using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory;
using Heimdall.Application.Cameras.Commands.ReportCameraStatus;
using Heimdall.Application.DTOs;
using Heimdall.Api.Security;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
@@ -24,6 +25,8 @@ namespace Heimdall.Api.Controllers;
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly ResourceAccess _resourceAccess;
/// <summary>Query parameters for agent log retrieval.</summary>
public record AgentLogsQuery(
[FromQuery] int Page = 1,
@@ -35,7 +38,11 @@ public class AgentsController : ControllerBase
private readonly IMediator _mediator;
public AgentsController(IMediator mediator) => _mediator = mediator;
public AgentsController(IMediator mediator, ResourceAccess resourceAccess)
{
_mediator = mediator;
_resourceAccess = resourceAccess;
}
/// <summary>Register an agent using a site registration token.</summary>
[AllowAnonymous]
@@ -149,6 +156,12 @@ public class AgentsController : ControllerBase
public async Task<IActionResult> ReportCameraStatus(
Guid id, Guid cameraId, [FromBody] ReportCameraStatusRequest request, CancellationToken ct)
{
var requester = await _resourceAccess.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Agent ||
!await _resourceAccess.AgentAsync(requester, id, ct) ||
!await _resourceAccess.CameraAsync(requester, cameraId, ct))
return Forbid();
if (!Enum.TryParse<CameraStatus>(request.Status, true, out var status))
return BadRequest(new { error = $"Invalid status: {request.Status}" });
@@ -171,7 +171,7 @@ public class CamerasController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Toggle a camera between Online and Disabled.</summary>
/// <summary>Toggle a camera between enabled (initially Offline) and Disabled.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/toggle-status")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
@@ -4078,7 +4078,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<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>
</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>
@@ -4078,7 +4078,7 @@
<value>Vérifier</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>L’installation Docker utilise l’image latest. Les mises à jour déclenchées par Central vérifient le digest signé avant de remplacer l’Agent. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage.</value>
@@ -4078,7 +4078,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<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>
</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>
@@ -9,7 +9,7 @@ public class SnapshotPipelineServiceTests
{
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer, ICameraStatusReporter StatusReporter) CreatePipeline(
List<AgentCameraOptions>? cameras = null,
AnalysisMode analysisMode = AnalysisMode.Local,
string? brokerUrl = null)
@@ -34,13 +34,13 @@ public class SnapshotPipelineServiceTests
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
Substitute.For<ILogger<SnapshotPipelineService>>(),
DegradationManager: degradationManager, Metrics: metrics));
return (service, state, store, streams, analyzer);
return (service, state, store, streams, analyzer, statusReporter);
}
[Fact]
public async Task StartStop_WithoutRegistration_StopsGracefully()
{
var (service, state, _, _, _) = CreatePipeline();
var (service, state, _, _, _, _) = CreatePipeline();
state.AgentId = Guid.Empty; // never registered
await service.StartAsync(CancellationToken.None);
@@ -52,7 +52,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _) = CreatePipeline();
var (service, _, _, streams, _, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
@@ -72,7 +72,7 @@ public class SnapshotPipelineServiceTests
{
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
};
var (service, _, store, streams, _) = CreatePipeline(cameras);
var (service, _, store, streams, _, _) = CreatePipeline(cameras);
await service.StartAsync(CancellationToken.None);
try
@@ -93,10 +93,45 @@ public class SnapshotPipelineServiceTests
}
}
[Fact]
public async Task CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync()
{
var (service, _, store, streams, _, statusReporter) = CreatePipeline();
var cameraId = Guid.NewGuid();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(TimeSpan.FromMilliseconds(1100));
statusReporter.ClearReceivedCalls();
store.ReplaceCentral(new Dictionary<string, string>
{
[$"camera.{cameraId}.enabled"] = "true",
[$"camera.{cameraId}.rtsp"] = "rtsp://camera/test",
});
// The full periodic resync runs every 30 seconds. A config event
// must instead reconcile this transition on the event signal.
var deadline = DateTime.UtcNow.AddMilliseconds(500);
while (DateTime.UtcNow < deadline && !statusReporter.ReceivedCalls().Any())
await Task.Delay(10);
streams.ActiveStreamCount.ShouldBe(0); // FFmpeg is intentionally absent.
// Error is reported only after the enabled assignment is reconciled.
statusReporter.ReceivedCalls().Any(call =>
call.GetMethodInfo().Name == nameof(ICameraStatusReporter.ReportAsync) &&
Equals(call.GetArguments()[0], cameraId) &&
Equals(call.GetArguments()[1], "Error")).ShouldBeTrue();
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, store, streams, analyzer) = CreatePipeline();
var (service, _, store, streams, analyzer, _) = CreatePipeline();
var id = Guid.NewGuid();
store.ReplaceCentral(new Dictionary<string, string>
{
@@ -128,7 +163,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var (service, _, _, _, _) = CreatePipeline();
var (service, _, _, _, _, _) = CreatePipeline();
await service.StopAsync(CancellationToken.None);
service.ShouldNotBeNull();
}
@@ -136,7 +171,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public void IsRemoteMode_LocalMode_ReturnsFalse()
{
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
service.IsRemoteMode.ShouldBeFalse();
}
@@ -144,14 +179,14 @@ public class SnapshotPipelineServiceTests
public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse()
{
// Remote mode but no broker service injected → not actually remote
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void RemoteSubmissions_InitiallyZero()
{
var (service, _, _, _, _) = CreatePipeline();
var (service, _, _, _, _, _) = CreatePipeline();
service.RemoteSubmissions.ShouldBe(0);
service.RemoteFallbacks.ShouldBe(0);
}
@@ -20,7 +20,7 @@ public class ToggleCameraStatusCommandTests
}
[Fact]
public async Task Toggle_disabled_camera_should_set_online()
public async Task Toggle_disabled_camera_should_set_offline_until_agent_confirms_connectivity()
{
var context = Substitute.For<IApplicationDbContext>();
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>([_disabledCamera]));
@@ -30,7 +30,7 @@ public class ToggleCameraStatusCommandTests
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Status.ShouldBe(CameraStatus.Online);
result.Data.Status.ShouldBe(CameraStatus.Offline);
}
[Fact]
@@ -76,6 +76,6 @@ public class ToggleCameraStatusCommandTests
context.AuditLogs.Received(1).Add(Arg.Is<AuditLog>(log => log != null
&& log.UserId == actorId && log.Action == "Camera.StatusChanged"
&& log.OldValue!.Contains("\"status\":\"Disabled\"")
&& log.NewValue!.Contains("\"status\":\"Online\"")));
&& log.NewValue!.Contains("\"status\":\"Offline\"")));
}
}
@@ -1,4 +1,6 @@
using System.Buffers.Binary;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Heimdall.Domain.Entities;
using Heimdall.TestCommon;
using Microsoft.AspNetCore.Identity;
@@ -83,6 +85,73 @@ public class AuthFlowTests : E2ETestBase
navCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task Authenticator_2fa_login_creates_a_usable_browser_cookie()
{
const string password = "BrowserTwoFactorPass123!";
var email = $"e2e-2fa-{Guid.NewGuid():N}@heimdall.test";
IdentityAppUser? user = null;
try
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
user = new IdentityAppUser
{
Id = Guid.NewGuid(),
Email = email,
UserName = email,
EmailConfirmed = true
};
(await users.CreateAsync(user, password)).Succeeded.ShouldBeTrue();
(await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue();
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
}
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", email);
await Page.FillAsync("input[autocomplete='current-password']", password);
await Page.ClickAsync("button:has-text('Se connecter')");
var codeInput = Page.Locator("input[autocomplete='one-time-code']");
await codeInput.WaitForAsync(new() { Timeout = 15000 });
string authenticatorKey;
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user!.Id.ToString());
authenticatorKey = (await users.GetAuthenticatorKeyAsync(storedUser!))!;
}
await codeInput.FillAsync(GenerateTotp(authenticatorKey));
await Page.ClickAsync("button:has-text('Vérifier')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
var cookies = await Page.Context.CookiesAsync([BaseUrl]);
var authCookie = cookies.SingleOrDefault(cookie => cookie.Name == ".Heimdall.Auth");
authCookie.ShouldNotBeNull();
using var authenticated = new HttpClient();
authenticated.DefaultRequestHeaders.Add("Cookie", $".Heimdall.Auth={authCookie!.Value}");
var response = await authenticated.GetAsync($"{BaseUrl}/api/users/me");
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
}
finally
{
if (user is not null)
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user.Id.ToString());
if (storedUser is not null)
(await users.DeleteAsync(storedUser)).Succeeded.ShouldBeTrue();
}
}
}
[Fact]
public async Task Login_with_wrong_password_shows_error()
{
@@ -153,4 +222,30 @@ public class AuthFlowTests : E2ETestBase
}
private sealed record BootstrapStatus(bool SetupRequired);
#pragma warning disable CA5350
private static string GenerateTotp(string base32Key)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var key = new List<byte>();
var buffer = 0;
var bits = 0;
foreach (var character in base32Key.TrimEnd('='))
{
buffer = (buffer << 5) | alphabet.IndexOf(character);
bits += 5;
if (bits < 8) continue;
bits -= 8;
key.Add((byte)(buffer >> bits));
}
Span<byte> message = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
var hash = HMACSHA1.HashData(key.ToArray(), message);
var offset = hash[^1] & 0x0f;
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
| (hash[offset + 2] << 8) | hash[offset + 3];
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
#pragma warning restore CA5350
}
@@ -56,6 +56,64 @@ public class UserManagementTests : E2ETestBase
body.ShouldContain("E2E Viewer");
}
[Theory]
[InlineData("Supervisor", true)]
[InlineData("Supervisor", false)]
[InlineData("Viewer", true)]
[InlineData("Viewer", false)]
public async Task User_created_from_dialog_can_log_in_with_submitted_password_after_email_confirmation(
string role, bool selectRoleBeforePassword)
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
await Page.ClickAsync("text=Nouvel utilisateur");
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
var email = $"e2e-{role.ToLowerInvariant()}-{Guid.NewGuid():N}@heimdall.test";
var password = "FirstLoginPass123!";
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
await dialog.Locator("input[autocomplete='name']").FillAsync($"E2E {role}");
if (selectRoleBeforePassword)
await SelectCreateRoleAsync(dialog, role);
await dialog.Locator("input[autocomplete='new-password']").FillAsync(password);
if (!selectRoleBeforePassword)
await SelectCreateRoleAsync(dialog, role);
await dialog.Locator("button:has-text('Créer')").ClickAsync();
await dialog.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
var token = await LoginViaApiAsync();
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
var row = Page.Locator($"tr:has-text('{email}')");
await row.WaitForAsync(new() { Timeout = 15000 });
await row.GetByRole(AriaRole.Button, new() { Name = "Confirmer l’email", Exact = true }).ClickAsync();
using var login = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var response = await login.PostAsJsonAsync("/api/auth/login", new { email, password });
response.StatusCode.ShouldBe(HttpStatusCode.OK,
$"A {role} account created with role selected {(selectRoleBeforePassword ? "before" : "after")} its password should authenticate after admin email confirmation.");
var body = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>();
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrWhiteSpace();
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);
}
private static async Task SelectCreateRoleAsync(ILocator dialog, string role)
{
await dialog.Locator(".mud-input-control.mud-select").ClickAsync();
await dialog.Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = role }).ClickAsync();
}
[Fact]
public async Task New_user_can_log_in_with_viewer_role()
{
@@ -67,11 +67,58 @@ public class CamerasControllerTests : PostgresTestBase
var cameraId = cameraContent.GetProperty("id").GetGuid();
cameraContent.GetProperty("status").GetString().ShouldBe("Disabled");
// Toggle → Online
// Activation is enabled but has no connectivity evidence yet.
var toggleResponse = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
toggleResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var toggled = await toggleResponse.Content.ReadFromJsonAsync<JsonElement>();
toggled.GetProperty("status").GetString().ShouldBe("Online");
toggled.GetProperty("status").GetString().ShouldBe("Offline");
var cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
var camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
camera.GetProperty("status").GetString().ShouldBe("Offline");
var tokenResponse = await client.PostAsync($"api/sites/{siteId}/tokens", null);
var siteToken = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>())
.GetProperty("token").GetString()!;
var registerResponse = await client.PostAsJsonAsync("api/agents/register", new
{
token = siteToken,
hostname = "camera-connectivity-agent",
version = "1.0.0-test"
});
var registration = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
var agentId = registration.GetProperty("agentId").GetGuid();
var apiKey = registration.GetProperty("apiKey").GetString()!;
var agentClient = Factory.CreateClient();
agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var heartbeatResponse = await agentClient.PostAsJsonAsync(
$"api/agents/{agentId}/heartbeat", new { publicIp = "127.0.0.1" });
heartbeatResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var unassignedReport = await agentClient.PutAsJsonAsync(
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
unassignedReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
var assignmentResponse = await client.PostAsJsonAsync("api/assignments", new
{
cameraId,
agentId,
reason = "integration test"
});
assignmentResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var reportResponse = await agentClient.PutAsJsonAsync(
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
reportResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var wrongAgentReport = await agentClient.PutAsJsonAsync(
$"api/agents/{Guid.NewGuid()}/cameras/{cameraId}/status", new { status = "Offline" });
wrongAgentReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
camera.GetProperty("status").GetString().ShouldBe("Online");
// Toggle back → Disabled
var toggleBack = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
@@ -82,7 +82,8 @@ 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("registry.example/heimdall-agent@sha256:");
compose.ShouldContain("image: registry.example/heimdall-agent:latest");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("network_mode: host");
compose.ShouldContain("Agent__CentralUrl: \"http://localhost\"");
compose.ShouldContain("Agent__SiteToken: \"tok-detail-42\"");
@@ -93,6 +94,15 @@ public class SiteDetailTests : PageTestBase
compose.ShouldNotContain("ollama");
var agent = GetAgentService(ParseCompose(compose));
agent.Children.ShouldNotContainKey(new YamlScalarNode("deploy"));
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value
.ShouldBe("registry.example/heimdall-agent:latest");
((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)
.ShouldContain("/var/run/docker.sock:/var/run/docker.sock");
var groups = (YamlSequenceNode)agent.Children[new YamlScalarNode("group_add")];
groups.Children.Select(node => ((YamlScalarNode)node).Value)
.ShouldContain("${DOCKER_GID:-0}");
var environment = (YamlMappingNode)agent.Children[new YamlScalarNode("environment")];
((YamlScalarNode)environment.Children[new YamlScalarNode("Agent__InferenceExecutionProvider")]).Value.ShouldBe("CPU");
});
@@ -137,14 +147,16 @@ public class SiteDetailTests : PageTestBase
cut.WaitForAssertion(() =>
{
var compose = cut.Find("pre code").TextContent;
compose.ShouldContain("image: registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
compose.ShouldContain("image: registry.example/heimdall-agent-gpu:latest");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("Agent__InferenceExecutionProvider: CUDA");
compose.ShouldContain("driver: nvidia");
compose.ShouldContain("capabilities: [gpu]");
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@sha256:" + new string('b', 64));
"registry.example/heimdall-agent-gpu:latest");
((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")];
var reservations = (YamlMappingNode)resources.Children[new YamlScalarNode("reservations")];
@@ -159,7 +171,10 @@ public class SiteDetailTests : PageTestBase
var run = commands[1];
run.ShouldContain("--gpus all");
run.ShouldContain("Agent__InferenceExecutionProvider=CUDA");
run.ShouldContain("registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
run.ShouldContain("--pull always");
run.ShouldContain("registry.example/heimdall-agent-gpu:latest");
run.ShouldContain("--group-add \"$(stat -c '%g' /var/run/docker.sock)\"");
run.ShouldContain("-v /var/run/docker.sock:/var/run/docker.sock");
});
}