Compare commits
5
Commits
1.0.5
...
2ba35f6d12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ba35f6d12 | ||
|
|
a8ce828c01 | ||
|
|
c5a250586b | ||
|
|
c8a428555a | ||
|
|
ec80e31e33 |
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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 à
|
||||
|
||||
@@ -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,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/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.'
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
Executable
+95
@@ -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
|
||||
@@ -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`.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user