ci(release): publish versioned installer bundles #315

Merged
arnaud.dartois merged 2 commits from fix/release-installer-flow-314 into main 2026-11-09 17:06:36 +01:00
29 changed files with 964 additions and 296 deletions

No files matched your search

+2 -1
View File
@@ -19,6 +19,7 @@ Refs #
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
- [ ] Revue des changements de contrats/migrations/configuration
- [ ] Après merge `main` : release publiée automatiquement, assets complets et version courante vérifiée
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
SonarQube, matériel et autres contrôles externes ne sont considérés validés que si une preuve réelle est jointe. Une protection de branche doit exiger le contexte Gitea constaté sur le run avant de compter sur le blocage d’un merge.
+51 -104
View File
@@ -3,8 +3,12 @@ on:
pull_request:
push:
branches: [main]
tags: ['*.*.*']
permissions:
contents: read
concurrency:
group: heimdall-${{ gitea.ref }}
cancel-in-progress: false
env:
BUILD_SERVER_URL: ${{ gitea.server_url }}
BUILD_REPOSITORY: ${{ gitea.repository }}
@@ -14,13 +18,16 @@ jobs:
runs-on: [ubuntu-latest, build-agent]
outputs:
run_validation: ${{ steps.filter.outputs.run_validation }}
build_server: ${{ steps.filter.outputs.build_server }}
build_agent: ${{ steps.filter.outputs.build_agent }}
build_agent_gpu: ${{ steps.filter.outputs.build_agent_gpu }}
steps:
- name: Checkout
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
persist-credentials: false
- name: Detect changes that need validation
- name: Detect changed projects and images
id: filter
env:
PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
@@ -28,40 +35,11 @@ jobs:
CURRENT_SHA: ${{ gitea.sha }}
EVENT_NAME: ${{ gitea.event_name }}
REF: ${{ gitea.ref }}
run: |
set -eu
if [ "$EVENT_NAME" = pull_request ]; then
changed_files="$(git diff --name-only "$PR_BASE_SHA...HEAD")"
elif [ -n "$PUSH_BEFORE_SHA" ] && [ "$PUSH_BEFORE_SHA" != 0000000000000000000000000000000000000000 ]; then
changed_files="$(git diff --name-only "$PUSH_BEFORE_SHA" "$CURRENT_SHA")"
else
echo 'run_validation=true' >> "$GITEA_OUTPUT"
exit 0
fi
if [ "$EVENT_NAME" = push ] && [ "$REF" = refs/heads/main ]; then
echo 'run_validation=true' >> "$GITEA_OUTPUT"
exit 0
fi
run_validation=false
while IFS= read -r path; do
case "$path" in
src/*|tests/*|Heimdall.slnx|global.json|Directory.Build.*|GitVersion*.yml|.dockerignore|.env.example|.gitea/workflows/*|scripts/ci/*|docker/*|install/*|models/*|Makefile)
run_validation=true
break
;;
esac
done <<EOF
$changed_files
EOF
echo "run_validation=$run_validation" >> "$GITEA_OUTPUT"
run: python3 scripts/ci/change_scope.py
policy:
name: CI policy
if: always()
needs: [changes, verify, server_image, agent_image, agent_gpu_image, dockerhub_latest, publish]
needs: [changes, verify, server_image, agent_image, agent_gpu_image, publish]
runs-on: [ubuntu-latest, build-agent]
steps:
- name: Require all applicable validation jobs to pass
@@ -72,7 +50,6 @@ jobs:
SERVER_IMAGE_RESULT: ${{ needs.server_image.result }}
AGENT_IMAGE_RESULT: ${{ needs.agent_image.result }}
AGENT_GPU_IMAGE_RESULT: ${{ needs.agent_gpu_image.result }}
DOCKERHUB_RESULT: ${{ needs.dockerhub_latest.result }}
RELEASE_RESULT: ${{ needs.publish.result }}
EVENT_NAME: ${{ gitea.event_name }}
REF: ${{ gitea.ref }}
@@ -86,19 +63,11 @@ jobs:
fi
test "$VERIFY_RESULT" = success
if [ "${{ needs.changes.outputs.build_server }}" = true ]; then test "$SERVER_IMAGE_RESULT" = success; fi
if [ "${{ needs.changes.outputs.build_agent }}" = true ]; then test "$AGENT_IMAGE_RESULT" = success; fi
if [ "${{ needs.changes.outputs.build_agent_gpu }}" = true ]; then test "$AGENT_GPU_IMAGE_RESULT" = success; fi
case "$EVENT_NAME:$REF" in
pull_request:*)
test "$SERVER_IMAGE_RESULT" = success
test "$AGENT_IMAGE_RESULT" = success
test "$AGENT_GPU_IMAGE_RESULT" = success
;;
push:refs/heads/main)
test "$SERVER_IMAGE_RESULT" = success
test "$AGENT_IMAGE_RESULT" = success
test "$AGENT_GPU_IMAGE_RESULT" = success
test "$DOCKERHUB_RESULT" = success
test "$RELEASE_RESULT" = success
;;
push:refs/tags/*) test "$RELEASE_RESULT" = success ;;
esac
verify:
name: Build and tests
@@ -152,15 +121,16 @@ jobs:
run: |
python3 -m unittest discover -s scripts/ci -p 'test_*.py'
python3 scripts/ci/check-efcore-usage.py
- name: Validate Compose and build .NET solution
- name: Validate Compose and restore .NET solution
run: |
mkdir -p artifacts/tests artifacts/security
dotnet --info > artifacts/dotnet-info.txt
bash scripts/ci/validate-compose.sh
dotnet restore Heimdall.slnx --locked-mode
dotnet build Heimdall.slnx -c Release --no-restore -m:2
- name: Plan affected test suites
run: python3 scripts/ci/test-plan.py
- name: Build affected projects
run: python3 scripts/ci/build-plan.py
- name: Agent tests
run: bash scripts/ci/test-suite.sh Heimdall.Agent.Tests
- name: API tests
@@ -179,8 +149,6 @@ jobs:
run: python3 scripts/ci/check-camera-access-coverage.py artifacts/tests artifacts/tests/plan.json
- name: Browser tests
run: bash scripts/ci/test-suite.sh Heimdall.E2E.Tests
- name: Publish server PWA and agent archives
run: bash scripts/ci/package.sh
- name: NuGet dependency security gate
run: bash scripts/ci/security.sh dependencies --no-restore
- name: Reclaim build storage after job
@@ -191,7 +159,7 @@ jobs:
fi
server_image:
name: Build and scan server image
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_server == 'true'
needs: [changes, verify]
runs-on: [ubuntu-latest, build-agent]
container:
@@ -216,14 +184,17 @@ jobs:
- name: Reclaim old build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: Build server image
env:
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/images.sh server
- name: Scan server image
run: bash scripts/ci/security.sh server
- name: Push immutable server image to Docker Hub
if: gitea.ref == 'refs/heads/main'
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/push-images.sh server
- name: Reclaim build storage after job
if: always()
@@ -233,7 +204,7 @@ jobs:
fi
agent_image:
name: Build and scan agent image
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent == 'true'
needs: [changes, verify]
runs-on: [ubuntu-latest, build-agent]
container:
@@ -258,14 +229,17 @@ jobs:
- name: Reclaim old build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: Build agent image
env:
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/images.sh agent
- name: Scan agent image
run: bash scripts/ci/security.sh agent
- name: Push immutable agent image to Docker Hub
if: gitea.ref == 'refs/heads/main'
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/push-images.sh agent
- name: Reclaim build storage after job
if: always()
@@ -275,7 +249,7 @@ jobs:
fi
agent_gpu_image:
name: Build and scan NVIDIA Agent image
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent_gpu == 'true'
needs: [changes, verify]
runs-on: [ubuntu-latest, build-agent]
container:
@@ -300,46 +274,18 @@ jobs:
- name: Reclaim old build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: Build NVIDIA Agent image
env:
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/images.sh agent-gpu
- name: Scan NVIDIA Agent image
run: bash scripts/ci/security.sh agent-gpu
- name: Reclaim build storage after job
if: always()
run: |
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
bash scripts/ci/cleanup-docker.sh after
fi
dockerhub_latest:
name: Publish Docker Hub latest tags
if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main'
needs: [changes, server_image, agent_image]
runs-on: [ubuntu-latest, build-agent]
container:
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
steps:
- name: Prepare action runtime before checkout
run: |
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
test "$(uname -m)" = x86_64
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
ln -sf /usr/local/bin/node /usr/bin/node
rm /tmp/node.tar.xz
- name: Checkout
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Docker prerequisites
run: bash scripts/ci/bootstrap.sh
- name: Reclaim old build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: Move latest tags after both image scans pass
- name: Push immutable NVIDIA Agent image to Docker Hub
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
run: bash scripts/ci/push-images.sh latest
BUILD_REF: ${{ gitea.ref }}
run: bash scripts/ci/push-images.sh agent-gpu
- name: Reclaim build storage after job
if: always()
run: |
@@ -347,8 +293,8 @@ jobs:
bash scripts/ci/cleanup-docker.sh after
fi
publish:
name: Publish signed main release
if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main'
name: Publish versioned installer release
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/')
needs: [changes, verify, server_image, agent_image, agent_gpu_image]
runs-on: [ubuntu-latest, build-agent]
container:
@@ -373,30 +319,30 @@ jobs:
fetch-depth: 0
persist-credentials: false
- run: bash scripts/ci/bootstrap.sh
- name: Rebuild release archives from verified merge
- name: Build versioned installer and Agent archives
env:
BUILD_REF: ${{ gitea.ref }}
BUILD_REPOSITORY: ${{ gitea.repository }}
BUILD_RUN_ID: ${{ gitea.run_id }}
run: bash scripts/ci/package.sh
- name: Generate merged pull request release notes
- name: Generate changes since the previous version tag
run: |
current_tag="${GITEA_REF#refs/tags/}"
previous_tag="$(git tag --merged "$CURRENT_SHA" --sort=-version:refname | sed -n '/^[0-9][0-9]*\.[0-9]/p' | grep -Fvx "$current_tag" | head -n 1 || true)"
if [ -n "$previous_tag" ]; then
BEFORE_SHA="$(git rev-list -n 1 "$previous_tag")"
else
BEFORE_SHA="$(git rev-list --max-parents=0 "$CURRENT_SHA" | tail -n 1)"
fi
export BEFORE_SHA CURRENT_SHA GITEA_TOKEN BUILD_SERVER_URL BUILD_REPOSITORY
python3 scripts/ci/release-notes.py
env:
GITEA_REF: ${{ gitea.ref }}
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
BUILD_SERVER_URL: ${{ gitea.server_url }}
BUILD_REPOSITORY: ${{ gitea.repository }}
BEFORE_SHA: ${{ gitea.event.before }}
CURRENT_SHA: ${{ gitea.sha }}
run: python3 scripts/ci/release-notes.py
- name: Docker prerequisites
run: bash scripts/ci/bootstrap.sh
- name: Build release images
run: bash scripts/ci/images.sh
- name: Scan release images
run: |
bash scripts/ci/security.sh server
bash scripts/ci/security.sh agent
bash scripts/ci/security.sh agent-gpu
- name: Publish immutable images and release
- name: Publish signed release assets
env:
BUILD_REF: ${{ gitea.ref }}
BUILD_REPOSITORY: ${{ gitea.repository }}
@@ -407,6 +353,7 @@ jobs:
RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }}
EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }}
RELEASE_NOTES_FILE: artifacts/release-notes.md
RELEASE_TAG: ${{ gitea.ref_name }}
run: bash scripts/ci/publish.sh
- name: Reclaim build storage after release
if: always()
+1
View File
@@ -11,6 +11,7 @@
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
For Penpot design work, follow [skills/penpot-design-sync/SKILL.md](skills/penpot-design-sync/SKILL.md): always open Penpot and establish the authenticated session through the Orca browser, and keep the connected design synchronized with relevant shipped UI changes.
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
+4 -2
View File
@@ -16,9 +16,11 @@ La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B
Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release.
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent ces références et leur SHA-256 est listé dans `SHA256SUMS`. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent les références que Central utilise pour afficher et générer les commandes Docker; leurs sommes de contrôle restent dans la sortie CI. La release contient ces deux fichiers, `agent-update-manifest.sig` (signature ECDSA/SHA-256), la clé publique et les archives Agent. La clé publique permet de vérifier les valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
Avant de générer ou mettre à jour un Agent, configurer dans Central le réglage global `updates.releaseapiurl` avec l’URL HTTPS de l’API de la dernière release Gitea publiée, par exemple `https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest`. Le panneau d’installation Docker n’affiche le Compose que si cette API retourne une image et un digest signés. Chaque merge vers `main` publie automatiquement une release signée avec notes issues des PR fusionnées; aucun tag Git ni promotion manuelle n’est requis. La version est `0.0.0-ci.<12 premiers caractères du SHA>`.
Avant de générer ou mettre à jour un Agent, configurer dans Central le réglage global `updates.releaseapiurl` avec l’URL HTTPS de la dernière release Gitea publiée, par exemple `https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest`. Le panneau d’installation n’affiche les commandes Linux/Windows que si cette API retourne la clé, le manifeste signé et les archives nécessaires; les commandes Docker exigent aussi un digest vérifié. Publier une version signée en poussant un tag Git `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Les merges ordinaires vers `main` mettent à jour Docker Hub pour les images touchées mais ne créent pas de release. Chaque release versionnée contient les archives Agent et leurs métadonnées signées consommées par les installateurs natifs et les mises à jour, ainsi que le ZIP d’installation serveur versionné; elle ne contient pas d’images Docker.
Pour installer une version précise du serveur, télécharger et extraire `heimdall-installers-<version>.zip` depuis sa release Gitea, puis lancer `install/install-server.sh` ou `install/install-server.ps1`. Ces copies utilisent les fichiers du bundle et épinglent l’image Central à la même version Docker Hub. Les scripts servis directement depuis `main` récupèrent le dernier bundle stable via l’API Gitea puis exécutent le script inclus, épinglé sur cette version. Sous Linux, ils requièrent `curl`, `jq`, `unzip`, Docker Compose et OpenSSL. La variable `HEIMDALL_INSTALLER_VERSION` sélectionne une version précise.
Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM.
+5 -8
View File
@@ -1,6 +1,6 @@
# CI Gitea et images Heimdall
La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et le build/scan de l’image Agent CUDA optionnelle, sans exiger de matériel GPU. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image`, `agent_image` et `agent_gpu_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur des runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Chaque merge vers `main`, y compris une fusion limitée à la documentation, publie une release signée après validation et scan des images.
La chaîne active est `.gitea/workflows/build.yml`. Le job `changes` détecte le graphe touché. Les PR compilent et testent le code concerné, puis construisent/scannent uniquement les images dont les fichiers ou dépendances ont changé. Les jobs d’image tournent en parallèle après `verify`. `CI policy` doit être configuré comme contrôle obligatoire de `main`.
## Sélection des runners
@@ -14,18 +14,15 @@ Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_EN
## Tests
`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne ensuite les suites affectées par une PR selon les fichiers modifiés et les `ProjectReference` transitifs. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toutes les suites. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `v*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés.
`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne les suites affectées et leurs projets de build selon les fichiers modifiés et les `ProjectReference` transitifs; `build-plan.py` ne compile que ces cibles sur une PR. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toute la solution. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Le restore NuGet verrouillé reste solution-wide pour la vérification des dépendances, mais les compilations ciblées ne recompilent pas les graphes Agent/Web sans lien avec les fichiers touchés. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `*.*.*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés.
## Publication continue
Après validation de `verify` sur `main`, chaque job d'image publie son tag immuable `sha-<commit complet>` une fois son scan réussi. Le job `dockerhub_latest` attend les deux jobs, récupère les deux images publiées et déplace leurs tags `latest` :
Les PR ne reçoivent aucun secret de publication et ne poussent aucune image. Les runs du même ref sont sérialisés pour qu’un build plus lent d’un commit ancien ne remette pas `latest` en arrière. Après validation sur `main`, chaque job touché publie sur Docker Hub son image `sha-<SHA>` et déplace uniquement son propre tag `latest`. Les builds inchangés sont sautés, y compris si le changement ne concerne que la documentation, le compose de déploiement ou un autre composant.
- `eltruncho/heimdall:latest` et `eltruncho/heimdall:sha-<commit complet>` ;
- `eltruncho/heimdall-agent:latest` et `eltruncho/heimdall-agent:sha-<commit complet>`.
Une version est publiée en poussant un tag `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Le workflow complet construit/scanne les images serveur, Agent CPU et Agent GPU une seule fois, puis publie leurs tags `sha-<SHA>` et version sur Docker Hub. Le job release réutilise ces images pour recueillir les digests; il ne les reconstruit pas et ne les rescane pas. Gitea reçoit `heimdall-installers-<version>.zip` pour Central, plus les archives Agent signées, leur clé publique, leur manifeste et les références d’images CPU/GPU nécessaires aux mises à jour natives. Provenance, liste de digests et checksums restent dans la sortie interne CI. Les couches Docker ne sont jamais attachées à Gitea. Les scripts Central `.sh` et `.ps1` récupèrent l’API de la dernière release stable, téléchargent le ZIP correspondant et exécutent son script épinglé à cette version; `HEIMDALL_INSTALLER_VERSION` permet de demander une version explicite. Le panneau d’installation Central confirme la release signée et masque les commandes natives tant que les assets nécessaires ne sont pas disponibles.
Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie.
La publication automatique n’exige aucune création de tag Git ni promotion manuelle. Chaque commit fusionné reçoit la version `0.0.0-ci.<12 premiers caractères du SHA>` et une release Gitea identifiée par `ci-<SHA complet>`. Elle reste brouillon pendant le téléversement des assets et est publiée automatiquement seulement quand ils sont complets. Les notes listent les PR fusionnées entre le commit précédent de `main` et le nouveau commit. Les images serveur, Agent CPU et Agent GPU sont publiées sous les tags immuables `sha-<SHA>` et `0.0.0-ci.<SHA court>`, avec signature ECDSA P-256, manifestes et checksums attachés à la release. Si un job retardé publie un commit déjà dépassé par `main`, sa release est marquée prérelease afin qu’elle ne remplace pas la version `latest`. Le job nécessite `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`; ils ne sont exposés qu’après les validations, sur push `main`, jamais aux PR.
Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d’organisation `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64` doivent être disponibles pour les événements de publication uniquement. Les identifiants Docker sont transmis à `docker login` sur stdin et stockés dans une configuration temporaire supprimée en sortie.
## Renovate
+49 -6
View File
@@ -226,19 +226,62 @@ Dashboard shows agent offline state
│ │ │ Token: a1b2c3d4-... (caché après création)│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ │ │
│ │ Commande Docker à exécuter sur le site distant : │ │
│ │ Installer l'Agent │ │
│ │ Déployez le connecteur sur la machine du site. │ │
│ │ Release signée disponible : vX.Y.Z │ │
│ │ │ │
│ │ Système d'exploitation │ │
│ │ [🐧 Linux] [⊞ Windows] [🐳 Docker] │ │
│ │ │ │
│ │ Méthode │ │
│ │ [Exécution] [Service systemd] │ │
│ │ │ │
│ │ Configuration (Docker avec image GPU disponible)│ │
│ │ [ ] Utiliser l'inférence GPU NVIDIA │ │
│ │ │ │
│ │ Commandes │ │
│ │ Installer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ docker run -e HEIMDALL_CENTRAL_URL=... │ │ │
│ │ │ -e HEIMDALL_SITE_TOKEN=... │ │ │
│ │ │ heimdall/agent:latest │ │ │
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ Lancer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ sudo systemctl start heimdall-agent [⧉]│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ │ │
│ │ [Copier la commande] [× Révoquer le token] │ │
│ │ [× Révoquer le token] │ │
│ └──────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
```
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, `MudSnackbar` (copié)
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, panneau installateur (`SiteInstallPanel`), commandes copiables avec `MudIconButton` et `MudTooltip`, `MudSnackbar` (copié)
### Parcours d'installation Agent
Le panneau suit le parcours de l'installateur Pangolin : choix de plateforme en tuiles, choix de méthode en tuiles, configuration optionnelle puis étapes de commandes. Les tuiles sont en trois colonnes sur écran large et s'empilent sur petit écran; les méthodes prennent toute la largeur disponible. La tuile sélectionnée garde un contour et un fond teinté de la couleur primaire.
```text
Système d'exploitation
[Linux] [Windows] [Docker]
Méthode
[Exécution] [Service systemd]
Configuration (Docker uniquement si l'image GPU est publiée)
[ ] Utiliser l'inférence GPU NVIDIA
Commandes
Installer
┌──────────────────────────────────────────────┐
│ commande/script [⧉]│
└──────────────────────────────────────────────┘
Lancer
┌──────────────────────────────────────────────┐
│ commande de démarrage [⧉]│
└──────────────────────────────────────────────┘
```
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.
### États — Détail Site
+51 -3
View File
@@ -4,12 +4,63 @@ param()
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$script:PackageReleaseVersion = 'unversioned'
$script:ReleaseApiUrl = if ($env:HEIMDALL_RELEASE_API_URL) {
$env:HEIMDALL_RELEASE_API_URL.TrimEnd('/')
} else {
'https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases'
}
$script:SourceBaseUrl = if ($env:HEIMDALL_SOURCE_BASE_URL) {
$env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/')
} else {
'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main'
}
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.'
}
$installerVersion = if ($env:HEIMDALL_INSTALLER_VERSION) { $env:HEIMDALL_INSTALLER_VERSION } else { $script:PackageReleaseVersion }
if ($script:PackageReleaseVersion -eq 'unversioned') {
$releaseUri = "$script:ReleaseApiUrl/latest"
if ($env:HEIMDALL_INSTALLER_VERSION) {
$installerVersion = $env:HEIMDALL_INSTALLER_VERSION
if ($installerVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
throw 'Version Heimdall invalide.'
}
$releaseUri = "$script:ReleaseApiUrl/tags/$installerVersion"
}
$bootstrapRoot = Join-Path ([IO.Path]::GetTempPath()) ('heimdall-installer-' + [Guid]::NewGuid().ToString('N'))
$bundlePath = Join-Path $bootstrapRoot 'installers.zip'
$null = New-Item -ItemType Directory -Path $bootstrapRoot
try {
$release = Invoke-RestMethod -Method Get -Uri $releaseUri -TimeoutSec 30
$resolvedVersion = [string]$release.tag_name
if ($resolvedVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
throw 'La release Heimdall retournée a une version invalide.'
}
$installerName = "heimdall-installers-$resolvedVersion.zip"
$installerAsset = @($release.assets) | Where-Object { $_.name -eq $installerName } | Select-Object -First 1
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.' }
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.' }
Expand-Archive -LiteralPath $bundlePath -DestinationPath $bootstrapRoot -Force
$packagedScript = Join-Path $bootstrapRoot 'install\install-server.ps1'
if (-not (Test-Path -LiteralPath $packagedScript)) { throw 'Le bundle ne contient pas install/install-server.ps1.' }
$env:HEIMDALL_INSTALLER_VERSION = $resolvedVersion
& $packagedScript
if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
return
} finally {
Remove-Item -LiteralPath $bootstrapRoot -Recurse -Force -ErrorAction SilentlyContinue
}
}
function Read-Answer {
param([string]$Prompt, [string]$Default)
$answer = Read-Host "$Prompt [$Default]"
@@ -78,9 +129,6 @@ function Invoke-DockerCompose {
if ($LASTEXITCODE -ne 0) { throw "docker compose a échoué (code $LASTEXITCODE)." }
}
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.'
}
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw 'Docker est requis.' }
& docker compose version | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Le plugin Docker Compose est requis.' }
+45 -1
View File
@@ -7,6 +7,8 @@ if [[ -n "$SCRIPT_PATH" ]]; then
SCRIPT_DIR="$(cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)"
fi
readonly SOURCE_BASE_URL="${HEIMDALL_SOURCE_BASE_URL:-https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main}"
readonly PACKAGE_RELEASE_VERSION="unversioned"
readonly RELEASE_API_URL="${HEIMDALL_RELEASE_API_URL:-https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases}"
REPO_ROOT=""
if [[ -n "$SCRIPT_DIR" && -f "${SCRIPT_DIR}/../docker/docker-compose.ollama.yml" ]]; then
REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
@@ -26,11 +28,53 @@ if [[ ! -t 0 && (! -r /dev/tty || ! -w /dev/tty) ]]; then
echo "Ce script nécessite un terminal interactif." >&2
exit 2
fi
for command in docker openssl curl; do
for command in docker openssl curl jq unzip; do
command -v "$command" >/dev/null || { echo "Commande requise absente : $command" >&2; exit 1; }
done
docker compose version >/dev/null
# A raw-branch bootstrap resolves the latest stable installer bundle, then
# re-enters the version-pinned script contained in that bundle. Packaged copies
# already carry their version and never resolve a moving release again.
installer_version="$PACKAGE_RELEASE_VERSION"
if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
release_api="$RELEASE_API_URL/latest"
if [[ -n "${HEIMDALL_INSTALLER_VERSION:-}" ]]; then
installer_version="$HEIMDALL_INSTALLER_VERSION"
[[ "$installer_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
echo 'Version Heimdall invalide.' >&2; exit 1;
}
release_api="$RELEASE_API_URL/tags/$installer_version"
fi
bootstrap_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimdall-installer.XXXXXX")"
cleanup_bootstrap() { rm -rf -- "$bootstrap_dir"; }
trap cleanup_bootstrap EXIT
if ! curl --fail --silent --show-error --location "$release_api" --output "$bootstrap_dir/release.json"; then
echo 'Impossible de récupérer la dernière release Heimdall.' >&2; exit 1
fi
resolved_version="$(jq -er '.tag_name | select(type == "string" and test("^[0-9]+\\.[0-9]+\\.[0-9]+([.-][0-9A-Za-z.-]+)?$"))' "$bootstrap_dir/release.json")" || {
echo 'La release Heimdall retournée a une version invalide.' >&2; exit 1;
}
installer_asset="heimdall-installers-$resolved_version.zip"
asset_json="$(jq -ce --arg name "$installer_asset" '.assets[] | select(.name == $name)' "$bootstrap_dir/release.json")" || {
echo 'La release ne contient pas son bundle d’installation versionné.' >&2; exit 1;
}
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;
}
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; }
unzip -q "$bootstrap_dir/installers.zip" -d "$bootstrap_dir/bundle"
packaged_script="$bootstrap_dir/bundle/install/install-server.sh"
[[ -f "$packaged_script" ]] || { echo 'Le bundle ne contient pas install/install-server.sh.' >&2; exit 1; }
HEIMDALL_INSTALLER_VERSION="$resolved_version" bash "$packaged_script" "$@"
exit $?
fi
copy_source_asset() {
local relative_path="$1" destination_path="$2" asset_tmp="${2}.tmp.$$"
if [[ -n "$REPO_ROOT" && -f "$REPO_ROOT/$relative_path" ]]; then
+126 -36
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Offline acceptance for packaging, release notes, and publication with synthetic doubles."""
"""Offline acceptance for one tagged image and installer release with synthetic doubles."""
import base64
import email
import hashlib
@@ -67,14 +67,22 @@ args = sys.argv[1:]
log = os.environ['OFFLINE_DOCKER_LOG']
with open(log, 'a') as f: f.write(json.dumps(args) + '\n')
if args[:1] == ['build']:
target = args[args.index('-t') + 1]
sys.exit(0)
sys.exit(12) # Release publication must reuse the scanned image builds.
if args[:2] == ['login', 'docker.io']:
if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user':
sys.exit(11)
sys.exit(0)
if args[:2] == ['manifest', 'inspect']:
sys.exit(1) # Simulate absent remote tags; never call a registry.
if args[:2] == ['compose', 'version']:
marker = os.environ.get('OFFLINE_STOP_COMPOSE_MARKER')
if marker:
try:
open(marker, 'x').close()
except FileExistsError:
sys.exit(37)
print('Docker Compose version v2.offline')
sys.exit(0)
if args[:1] == ['pull']:
sys.exit(0) # Synthetic registry pull; never contact Docker Hub.
if args[:1] == ['tag']:
sys.exit(0)
if args[:1] == ['push']:
@@ -87,7 +95,10 @@ if args[:2] == ['image', 'inspect']:
digest = os.environ['OFFLINE_AGENT_DIGEST']
else:
digest = os.environ['OFFLINE_SERVER_DIGEST']
print(image + '@' + digest)
if '--format' in args and 'RepoDigests' in args[args.index('--format') + 1]:
print(image + '@' + digest)
elif '--format' in args and 'org.opencontainers.image.revision' in args[args.index('--format') + 1]:
print(os.environ['OFFLINE_COMMIT'])
sys.exit(0)
if args[:1] == ['save']:
from pathlib import Path
@@ -112,6 +123,28 @@ sys.exit(12)
docker_path = fakebin / 'docker'
docker_path.write_text(docker_stub)
docker_path.chmod(0o700)
curl_stub = r'''#!/usr/bin/env python3
import hashlib, json, os, shutil, sys
args = sys.argv[1:]
url = next(value for value in args if value.startswith('https://'))
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'):
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()
open(output, 'wb').write(payload)
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
else:
sys.exit(22)
'''
curl_path = fakebin / 'curl'
curl_path.write_text(curl_stub)
curl_path.chmod(0o700)
curl_log = temp / 'installer-bootstrap-urls.txt'
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
@@ -142,9 +175,11 @@ sys.exit(12)
elif path.endswith('/commits/synthetic-merge-commit/pull'):
self._json(200, {'number': 42, 'merged': True, 'title': 'Offline acceptance feature',
'html_url': 'https://gitea.test/pulls/42'})
elif path.endswith('/branches/main'):
self._json(200, {'commit': {'id': commit}})
elif path.endswith('/releases/tags/ci-' + commit):
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'}]})
elif path.endswith('/releases/tags/1.2.3'):
self._json(404, {'message': 'not found'})
elif path.endswith('/releases/7301/assets'):
self._json(200, [])
@@ -159,10 +194,10 @@ sys.exit(12)
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
if path.endswith('/releases'):
release = json.loads(body)
assert release['tag_name'] == 'ci-' + subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
assert release['tag_name'] == '1.2.3'
assert release['name'] == '1.2.3'
assert release['draft'] is True
assert release['prerelease'] is True
assert release['prerelease'] is False
assert 'Offline acceptance feature' in release['body']
assert release['target_commitish'] == subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
@@ -193,7 +228,11 @@ sys.exit(12)
path = urlsplit(self.path).path
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', '0'))))
if path.endswith('/releases/7301'):
assert set(release_state['assets']) >= {'agent-update-manifest.json', 'agent-update-manifest.sig'}
assert set(release_state['assets']) >= {
'agent-update-manifest.json', 'agent-update-manifest.sig',
'heimdall-installers-1.2.3.zip'}
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']
release_state['release']['prerelease'] = body['prerelease']
self._json(200, release_state['release'])
@@ -215,7 +254,7 @@ sys.exit(12)
'SSL_CERT_FILE': str(cert),
'NO_PROXY': '127.0.0.1,localhost',
'no_proxy': '127.0.0.1,localhost',
'BUILD_REF': 'refs/heads/main',
'BUILD_REF': 'refs/tags/1.2.3',
'BUILD_REPOSITORY': REPOSITORY,
'BUILD_RUN_ID': 'offline-acceptance',
'BUILD_SERVER_URL': origin,
@@ -228,14 +267,45 @@ sys.exit(12)
'OFFLINE_SERVER_DIGEST': SERVER_DIGEST,
'OFFLINE_AGENT_DIGEST': AGENT_DIGEST,
'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST,
'OFFLINE_COMMIT': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
'RELEASE_NOTES_FILE': str(artifacts_dir/'release-notes.md'),
'RELEASE_TAG': '1.2.3',
})
run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh')
with __import__('zipfile').ZipFile(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip') as bundle:
package_server_script = bundle.read('install/install-server.sh').decode()
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in package_server_script, package_server_script[:1200]
launcher_env = env.copy()
launcher_env.update({
'HEIMDALL_RELEASE_API_URL': origin + '/api/v1/repos/' + REPOSITORY + '/releases',
'OFFLINE_CURL_LOG': str(curl_log),
'OFFLINE_INSTALLER_ZIP': str(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip'),
'OFFLINE_STOP_COMPOSE_MARKER': str(temp / 'compose-version-probe'),
'TMPDIR': str(temp),
})
launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
env=launcher_env, capture_output=True, text=True)
launcher_output = launcher.stdout + launcher.stderr
assert launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
f'installer bootstrap exit={launcher.returncode}; URLs={curl_log.read_text() if curl_log.exists() else "<none>"}; '
+ launcher_output[-2000:])
bootstrap_urls = curl_log.read_text().splitlines()
assert bootstrap_urls == [
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
'https://release.test/heimdall-installers-1.2.3.zip',
]
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
env['GITEA_TOKEN'] = RELEASE_TOKEN
env['BEFORE_SHA'] = commit + '^'
env['CURRENT_SHA'] = commit
run([sys.executable, 'scripts/ci/release-notes.py'], cwd=ROOT, env=env, label='release-notes.py')
for component in ('server', 'agent', 'agent-gpu'):
main_env = env.copy()
main_env['BUILD_REF'] = 'refs/heads/main'
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=main_env,
label=f'push-images.sh {component} main')
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=env,
label=f'push-images.sh {component} tag')
run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh')
packages = ROOT / 'artifacts/packages'
@@ -245,49 +315,69 @@ sys.exit(12)
signature = temp / 'manifest.sig'
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
manifest = json.loads(manifest_bytes)
assert manifest['version'] == '0.0.0-ci.' + commit[:12]
assert manifest['version'] == '1.2.3'
assert manifest['containerImage'] == 'eltruncho/heimdall-agent'
assert manifest['containerImageDigest'] == AGENT_DIGEST
assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu'
assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST
provenance = json.loads(release_state['assets']['provenance.json'])
assert provenance['commit'] == commit and provenance['ref'] == 'refs/heads/main'
provenance = json.loads((packages / 'provenance.json').read_text())
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/1.2.3'
agent_image = json.loads(release_state['assets']['agent-image.json'])
assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'}
gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json'])
assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'}
for platform, digest in manifest['assets'].items():
archive = f'heimdall-agent-{platform}-0.0.0-ci.{commit[:12]}.tar.gz'
archive = f'heimdall-agent-{platform}-1.2.3.tar.gz'
assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key),
'-signature', str(signature), str(packages / 'agent-update-manifest.json')],
check=True, stdout=subprocess.DEVNULL)
checksums = release_state['assets']['SHA256SUMS'].decode().splitlines()
checksums = (packages / 'SHA256SUMS').read_text().splitlines()
for line in checksums:
digest, filename = line.split(maxsplit=1)
filename = filename.lstrip('* ')
assert filename in release_state['assets'], f'missing checksum asset {filename}'
assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename
image_digests = release_state['assets']['image-digests.txt'].decode().splitlines()
assert len(image_digests) == 6
assert sum(AGENT_DIGEST in item for item in image_digests) == 2
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 2
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
assert sum(call[:1] == ['build'] for call in docker_calls) == 3
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
assert len(pushes) == 6
assert pushes == {
f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall:0.0.0-ci.{commit[:12]}',
f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:0.0.0-ci.{commit[:12]}',
f'eltruncho/heimdall-agent-gpu:sha-{commit}', f'eltruncho/heimdall-agent-gpu:0.0.0-ci.{commit[:12]}',
assert (packages / filename).is_file(), f'missing package checksum input {filename}'
assert hashlib.sha256((packages / filename).read_bytes()).hexdigest() == digest, filename
image_digests = (packages / 'image-digests.txt').read_text().splitlines()
assert len(image_digests) == 3
assert sum(AGENT_DIGEST in item for item in image_digests) == 1
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 1
with __import__('zipfile').ZipFile(packages/'heimdall-installers-1.2.3.zip') as bundle:
assert 'install/install-server.sh' in bundle.namelist()
assert 'install/install-server.ps1' in bundle.namelist()
assert 'docker/docker-compose.yml' in bundle.namelist()
server_script = bundle.read('install/install-server.sh').decode()
windows_script = bundle.read('install/install-server.ps1').decode()
assert '/raw/tag/1.2.3' in server_script
assert 'eltruncho/heimdall:1.2.3' in server_script
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in server_script
assert "PackageReleaseVersion = '1.2.3'" in windows_script
assert 'install/install-agent.sh' in bundle.namelist()
assert 'install/install-agent.ps1' in bundle.namelist()
expected_release_assets = {
'heimdall-installers-1.2.3.zip', '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']],
}
assert sum(call[:1] == ['login'] for call in docker_calls) == 1
assert set(release_state['assets']) == expected_release_assets
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
assert sum(call[:1] == ['build'] for call in docker_calls) == 0
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
assert len(pushes) == 9
for image in ('eltruncho/heimdall', 'eltruncho/heimdall-agent', 'eltruncho/heimdall-agent-gpu'):
assert f'{image}:sha-{commit}' in pushes
assert f'{image}:latest' in pushes
assert f'{image}:1.2.3' in pushes
assert sum(call[:1] == ['login'] for call in docker_calls) == 7
assert release_state['release']['draft'] is False
assert release_state['release']['prerelease'] is False
assert len(release_state['assets']) >= 9
assert len(release_state['assets']) == len(expected_release_assets)
assert release_state['authorized'] >= 7
print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} published assets, checksums, CPU/GPU image digests, and six simulated pushes.')
assert sum(call[:1] == ['push'] for call in docker_calls if call[0] != 'login') == 12
print(f'Offline version release simulation passed: installer ZIP, Agent archives, P-256 signature, {len(release_state["assets"])} Gitea assets, immutable image refs, and selective Docker Hub tags.')
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
finally:
server.shutdown()
+1 -1
View File
@@ -2,7 +2,7 @@
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y --no-install-recommends ca-certificates curl git python3 unzip postgresql-client docker.io docker-compose-v2
apt-get install -y --no-install-recommends ca-certificates curl git jq python3 unzip postgresql-client docker.io docker-compose-v2
# Fail explicitly if a runner cannot provide the required Docker build service.
docker version --format '{{.Server.Version}}'
docker compose version
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Build only the projects selected by test-plan.py after solution restore."""
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[2]
PLAN = ROOT / "artifacts" / "tests" / "plan.json"
def main() -> None:
plan = json.loads(PLAN.read_text())
targets = plan.get("build_projects")
if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets):
raise SystemExit("Test plan has an invalid build_projects list")
if not targets:
print("No .NET build targets selected")
return
for target in targets:
path = ROOT / target
if not path.is_file():
raise SystemExit(f"Build target does not exist: {target}")
print(f"Building affected target: {target}", flush=True)
subprocess.run(
["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"],
cwd=ROOT,
check=True,
)
if __name__ == "__main__":
main()
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Set Gitea workflow outputs for validation and affected container images."""
import os
import re
import subprocess
def changed_paths() -> list[str]:
event = os.environ.get("EVENT_NAME", "")
ref = os.environ.get("REF", "")
if event == "push" and ref.startswith("refs/tags/"):
tag = ref.removeprefix("refs/tags/")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[.-][0-9A-Za-z.-]+)?", tag):
raise SystemExit("Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix")
return ["*"]
if event == "pull_request":
base = os.environ["PR_BASE_SHA"]
return subprocess.check_output(
["git", "diff", "--name-only", f"{base}...HEAD"], text=True
).splitlines()
before = os.environ.get("PUSH_BEFORE_SHA", "")
current = os.environ.get("CURRENT_SHA", "HEAD")
if before and before != "0" * 40:
return subprocess.check_output(
["git", "diff", "--name-only", before, current], text=True
).splitlines()
return ["*"]
def under(path: str, *prefixes: str) -> bool:
return any(path == prefix or path.startswith(prefix.rstrip("/") + "/") for prefix in prefixes)
def scope_for(paths: list[str]) -> dict[str, bool]:
all_images = "*" in paths
validation_prefixes = ("src/", "tests/", "scripts/ci/", "docker/", "install/", "models/")
validation_files = {
"Heimdall.slnx", "global.json", ".dockerignore", ".env.example", "Makefile",
"GitVersion.yml", "GitVersion.Agent.yml", "Directory.Packages.props", "NuGet.Config",
}
run_validation = all_images or any(
under(path, *validation_prefixes) or path in validation_files or
path.startswith(".gitea/workflows/") or path.startswith("Directory.Build.")
for path in paths
)
# Shared projects included by both Docker build graphs.
shared = {
"global.json", "Directory.Packages.props", "NuGet.Config", "GitVersion.yml",
}
shared_image_change = all_images or any(
path in shared or path.startswith("Directory.Build.") for path in paths
)
server = shared_image_change or any(
under(path, "src/Heimdall.Web", "src/Heimdall.Infrastructure",
"src/Heimdall.Application", "src/Heimdall.Domain",
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts")
or path == "docker/Dockerfile" or under(path, "install")
for path in paths
)
agent_projects = (
"src/Heimdall.Agent", "src/Heimdall.Application", "src/Heimdall.Domain",
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts", "src/Heimdall.Mdns",
)
agent_common = any(
under(path, *agent_projects) or path == "models/yolov8n.onnx"
for path in paths
)
agent = shared_image_change or agent_common or any(
path == "docker/Dockerfile.agent" or path == "GitVersion.Agent.yml"
for path in paths
)
agent_gpu = shared_image_change or agent_common or any(
path == "docker/Dockerfile.agent.gpu" or path == "GitVersion.Agent.yml"
for path in paths
)
return {
"run_validation": run_validation,
"build_server": server,
"build_agent": agent,
"build_agent_gpu": agent_gpu,
}
def main() -> None:
output = os.environ.get("GITEA_OUTPUT")
if not output:
raise SystemExit("GITEA_OUTPUT is required")
with open(output, "a", encoding="utf-8") as stream:
for name, selected in scope_for(changed_paths()).items():
stream.write(f"{name}={'true' if selected else 'false'}\n")
if __name__ == "__main__":
main()
+5 -1
View File
@@ -1,7 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
sha=$(git rev-parse HEAD)
version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}")
if [[ "${BUILD_REF:-}" == refs/tags/* ]]; then
version=${BUILD_REF#refs/tags/}
else
version="0.0.0-ci.${sha:0:12}"
fi
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
: "${BUILD_REPOSITORY:?Gitea repository is required}"
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
+53 -15
View File
@@ -2,28 +2,66 @@
set -euo pipefail
sha=$(git rev-parse HEAD)
ref=${BUILD_REF:-}
version="0.0.0-ci.${sha:0:12}"
if [[ "$ref" == refs/tags/* ]]; then
version=${ref#refs/tags/}
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
echo 'Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix.' >&2; exit 2;
}
else
version="0.0.0-ci.${sha:0:12}"
fi
mkdir -p artifacts/packages
for component in Web Agent; do
rid=portable
out="artifacts/publish/$component-$rid"
dotnet publish "src/Heimdall.$component" -c Release --self-contained false \
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
if [[ "$component" == Agent ]]; then
mkdir -p "$out/models"
cp models/yolov8n.onnx "$out/models/"
fi
epoch=$(git show -s --format=%ct HEAD)
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -n > "artifacts/packages/heimdall-${component,,}-$rid-$version.tar.gz"
done
component=Agent
rid=portable
out="artifacts/publish/$component-$rid"
dotnet publish "src/Heimdall.Agent" -c Release --self-contained false \
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
mkdir -p "$out/models"
cp models/yolov8n.onnx "$out/models/"
epoch=$(git show -s --format=%ct HEAD)
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -1 -n > "artifacts/packages/heimdall-agent-$rid-$version.tar.gz"
python3 - "$version" "$ref" <<'PY'
import os,sys,zipfile
from datetime import datetime,timezone
from pathlib import Path
version, ref = sys.argv[1:]
epoch = int(__import__('subprocess').check_output(['git','show','-s','--format=%ct','HEAD'],text=True))
stamp = datetime.fromtimestamp(max(epoch, 315532800), timezone.utc).timetuple()[:6]
tag = version
source_base = f"https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/tag/{tag}"
files = [Path('install/install-server.sh'), Path('install/install-server.ps1')]
files += sorted(Path('install').glob('*.sh'))
files += sorted(Path('install').glob('*.ps1'))
files += sorted(Path('install').glob('*.py'))
files += sorted(Path('docker').glob('docker-compose*.yml'))
files += sorted(Path('docker/scripts').glob('*')) if Path('docker/scripts').exists() else []
archive = Path(f'artifacts/packages/heimdall-installers-{version}.zip')
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
for path in sorted(set(files)):
if not path.is_file():
continue
data = path.read_bytes()
if path.name in {'install-server.sh', 'install-server.ps1'} or path.name.startswith('docker-compose'):
text = data.decode('utf-8')
text = text.replace('https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main', source_base)
text = text.replace('eltruncho/heimdall:latest', f'eltruncho/heimdall:{version}')
text = text.replace('PACKAGE_RELEASE_VERSION="unversioned"', f'PACKAGE_RELEASE_VERSION="{version}"')
text = text.replace("PackageReleaseVersion = 'unversioned'", f"PackageReleaseVersion = '{version}'")
data = text.encode('utf-8')
entry = zipfile.ZipInfo(path.as_posix(), stamp)
entry.compress_type = zipfile.ZIP_DEFLATED
entry.external_attr = (0o100755 if path.suffix in {'.sh', '.py'} else 0o100644) << 16
bundle.writestr(entry, data)
PY
python3 - "$sha" "$version" "$ref" <<'PY'
import json,os,sys
from pathlib import Path
Path('artifacts/packages/provenance.json').write_text(json.dumps({
'commit':sys.argv[1], 'version':sys.argv[2], 'ref':sys.argv[3],
'repository':os.environ.get('BUILD_REPOSITORY'), 'run_id':os.environ.get('BUILD_RUN_ID'),
'targets':['Web/PWA','Agent'], 'rids':['portable-framework-dependent'],
'targets':['Agent native updater'], 'rids':['portable-framework-dependent'],
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
PY
(cd artifacts/packages && sha256sum *.tar.gz provenance.json > SHA256SUMS)
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
printf '%s' "$version" > artifacts/version
+12 -20
View File
@@ -33,22 +33,19 @@ openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prim
}
openssl pkey -in "$signing_key" -pubout -out artifacts/packages/agent-release-public.pem
(cd artifacts/packages && sha256sum agent-release-public.pem >> SHA256SUMS)
[[ "$BUILD_REF" == refs/heads/main ]] || { echo 'Release publication is restricted to verified main merges' >&2; exit 1; }
tag="ci-$sha"
[[ "$BUILD_REF" == refs/tags/* ]] || { echo 'Release publication is restricted to version tags MAJOR.MINOR.PATCH' >&2; exit 1; }
tag=${BUILD_REF#refs/tags/}
python3 - "$sha" "$tag" <<'PY'
import json,sys
with open('artifacts/packages/provenance.json') as f:p=json.load(f)
if p['commit'] != sys.argv[1] or p['version'] != '0.0.0-ci.' + sys.argv[1][:12] or p['ref'] != 'refs/heads/main':
raise SystemExit('Artifact provenance does not match verified main commit')
if p['commit'] != sys.argv[1] or p['version'] != sys.argv[2] or p['ref'] != 'refs/tags/' + sys.argv[2]:
raise SystemExit('Artifact provenance does not match the verified version tag')
PY
(cd artifacts/packages && sha256sum --check SHA256SUMS)
version=$(python3 -c 'import json;print(json.load(open("artifacts/packages/provenance.json"))["version"])')
printf '%s' "$version" > artifacts/version
bash scripts/ci/images.sh
for image_component in server agent agent-gpu; do
bash scripts/ci/security.sh "$image_component"
done
# No mutation is attempted until all credentials, provenance and local builds pass.
# The three image jobs have already built, scanned and pushed this exact commit.
# Pull only those immutable refs here; this job must not rebuild or rescan images.
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
@@ -67,17 +64,12 @@ for component in server agent agent-gpu; do
else
image=$server_image
fi
for image_tag in "sha-$sha" "$version"; do
if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then
docker pull "$image:$image_tag"
revision=$(docker image inspect "$image:$image_tag" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
[[ "$revision" == "$sha" ]] || { echo 'Refusing to overwrite an image from another commit' >&2; exit 1; }
else
docker tag "heimdall-$component:ci-$sha" "$image:$image_tag"
docker push "$image:$image_tag"
fi
docker image inspect "$image:$image_tag" --format '{{range .RepoDigests}}{{println .}}{{end}}' >> artifacts/image-digests.txt
done
docker pull "$image:sha-$sha"
revision=$(docker image inspect "$image:sha-$sha" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
[[ "$revision" == "$sha" ]] || { echo 'Pulled image does not match the versioned source commit' >&2; exit 1; }
digests=$(docker image inspect "$image:sha-$sha" --format '{{range .RepoDigests}}{{println .}}{{end}}')
[[ "$(printf '%s\n' "$digests" | sed '/^$/d' | wc -l)" == 1 ]] || { echo 'Expected one registry digest for the immutable image tag' >&2; exit 1; }
printf '%s\n' "$digests" >> artifacts/image-digests.txt
done
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
+18 -18
View File
@@ -1,9 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
mode=${1:?Expected server, agent, agent-gpu or latest}
case "$mode" in server|agent|agent-gpu|latest) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu|latest' >&2; exit 2 ;; esac
mode=${1:?Expected server, agent or agent-gpu}
case "$mode" in server|agent|agent-gpu) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu' >&2; exit 2 ;; esac
sha=$(git rev-parse HEAD)
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
ref=${BUILD_REF:-}
if [[ "$ref" == refs/tags/* ]]; then
version=${ref#refs/tags/}
else
version="0.0.0-ci.${sha:0:12}"
fi
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
@@ -17,19 +22,14 @@ repository() {
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
if [[ "$mode" == latest ]]; then
# Move mutable tags only after both independently built images passed their scans.
for component in server agent; do
docker pull "$(repository "$component"):sha-$sha"
done
for component in server agent; do
repo=$(repository "$component")
docker tag "$repo:sha-$sha" "$repo:latest"
docker push "$repo:latest"
done
else
repo=$(repository "$mode")
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
docker push "$repo:sha-$sha"
repo=$(repository "$mode")
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
docker push "$repo:sha-$sha"
if [[ "$ref" == refs/tags/* ]]; then
docker tag "heimdall-$mode:ci-$sha" "$repo:$version"
docker push "$repo:$version"
elif [[ "$ref" == refs/heads/main ]]; then
docker tag "heimdall-$mode:ci-$sha" "$repo:latest"
docker push "$repo:latest"
fi
+19 -11
View File
@@ -1,4 +1,4 @@
"""Create/update the published Gitea release for one verified main commit."""
"""Create/update the Gitea release for one verified version tag."""
import json
import os
import uuid
@@ -10,7 +10,9 @@ import urllib.request
base = os.environ['BUILD_SERVER_URL'] + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
token = os.environ['RELEASE_TOKEN']
provenance = json.loads(Path('artifacts/packages/provenance.json').read_text())
tag = 'ci-' + provenance['commit']
tag = os.environ['RELEASE_TAG']
if tag != provenance['version']:
raise SystemExit('Release tag does not match the packaged application version')
def request(path, method='GET', body=None, content_type='application/json', missing=False):
data = json.dumps(body).encode() if content_type == 'application/json' and body is not None else body
@@ -26,12 +28,23 @@ def request(path, method='GET', body=None, content_type='application/json', miss
raise SystemExit(f'Gitea release API failed: HTTP {error.code}') from None
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
package_files = sorted(path for path in Path('artifacts/packages').iterdir() if path.is_file())
package_root = Path('artifacts/packages')
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
required_assets = [installer_bundle, 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.
package_files = sorted([*required_assets, *agent_archives])
if release is None:
release = request('/releases', 'POST', {
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
'draft': True, 'prerelease': True,
'body': f"Automated continuous delivery for merge `{provenance['commit']}`.\n"
'draft': True, 'prerelease': '-' in provenance['version'],
'body': f"Automated Heimdall release `{provenance['version']}` from `{provenance['commit']}`.\n"
f"Actions run: {provenance['run_id']}\n\n"
'## Changes\n'
+ Path(os.environ['RELEASE_NOTES_FILE']).read_text()})
@@ -56,12 +69,7 @@ for path in package_files:
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
'POST', payload, 'multipart/form-data; boundary='+boundary)
main_branch = request('/branches/main')
main_sha = main_branch.get('commit', {}).get('id') if main_branch else None
if not main_sha:
raise SystemExit('Could not verify current main commit before publishing the release')
is_current_main = main_sha == provenance['commit']
expected_prerelease = not is_current_main
expected_prerelease = '-' in provenance['version']
published = request(f"/releases/{release['id']}", 'PATCH', {
'draft': False,
'prerelease': expected_prerelease,
+1 -1
View File
@@ -1,4 +1,4 @@
"""Generate release notes from pull requests merged by one main push."""
"""Generate release notes from pull requests merged since the previous version tag."""
import json
import os
from pathlib import Path
+38 -7
View File
@@ -9,6 +9,8 @@ import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon")
SOURCES = sorted((ROOT / "src").glob("*/*.csproj"))
ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")]
def references(project: Path) -> set[Path]:
@@ -19,6 +21,30 @@ def references(project: Path) -> set[Path]:
}
def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]:
result: set[Path] = set()
pending = list(graph.get(project, set()))
while pending:
dependency = pending.pop()
if dependency in result:
continue
result.add(dependency)
pending.extend(graph.get(dependency, set()))
return result
def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]],
mode: str) -> list[str]:
if mode == "all":
return ["Heimdall.slnx"]
suite_projects = [project for project in TESTS if project.stem in suites]
covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set()
targets = [*suite_projects, *(project for project in SOURCES
if project.resolve() in affected and project.resolve() not in covered_sources)]
return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets})
def changed_files() -> list[str] | None:
if os.environ.get("GITEA_EVENT_NAME") != "pull_request":
return None
@@ -31,11 +57,11 @@ def changed_files() -> list[str] | None:
def plan(changed: list[str] | None) -> dict[str, object]:
if changed is None:
return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]}
suites = [p.stem for p in TESTS]
return {"mode": "all", "changed": [], "suites": suites,
"build_projects": build_targets(set(), suites, {}, "all")}
all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | {
p.resolve() for p in (ROOT / "tests").glob("*/*.csproj")
}
all_paths = {p.resolve() for p in ALL_PROJECTS}
graph = {project: references(project) for project in all_paths}
changed_projects: set[Path] = set()
broad = False
@@ -59,10 +85,12 @@ def plan(changed: list[str] | None) -> dict[str, object]:
or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"}
for name in changed
):
return {"mode": "affected", "changed": changed, "suites": []}
return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []}
if broad or (changed and not changed_projects):
return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]}
suites = [p.stem for p in TESTS]
return {"mode": "all", "changed": changed, "suites": suites,
"build_projects": build_targets(set(), suites, graph, "all")}
affected = set(changed_projects)
while True:
@@ -72,7 +100,9 @@ def plan(changed: list[str] | None) -> dict[str, object]:
affected |= additions
suites = [p.stem for p in TESTS if p.resolve() in affected]
return {"mode": "affected", "changed": changed, "suites": suites}
projects = build_targets(affected, suites, graph, "affected")
return {"mode": "affected", "changed": changed, "suites": suites,
"build_projects": projects}
if __name__ == "__main__":
@@ -81,3 +111,4 @@ if __name__ == "__main__":
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(result, indent=2) + "\n")
print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}")
print(f"Build targets: {', '.join(result['build_projects']) or 'none'}")
+113 -12
View File
@@ -1,4 +1,4 @@
"""Contract tests for security gates and automatic release uploads, without network."""
"""Contract tests for security gates and versioned release uploads, without network."""
import contextlib
import io
import importlib.util
@@ -6,6 +6,7 @@ import json
import os
from pathlib import Path
import runpy
import shutil
import subprocess
import sys
import tempfile
@@ -15,6 +16,59 @@ from unittest.mock import patch
ROOT = Path(__file__).resolve().parent
REPO_ROOT = ROOT.parent.parent
def load_change_scope():
spec = importlib.util.spec_from_file_location('heimdall_change_scope', ROOT/'change_scope.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class ChangeScopeTests(unittest.TestCase):
def setUp(self):
self.scope = load_change_scope().scope_for
def test_documentation_does_not_build_or_validate_images(self):
self.assertEqual(self.scope(['docs/operations.md']), {
'run_validation': False, 'build_server': False,
'build_agent': False, 'build_agent_gpu': False,
})
def test_ci_script_changes_validate_without_building_container_images(self):
result = self.scope(['.gitea/workflows/build.yml', 'scripts/ci/change_scope.py'])
self.assertTrue(result['run_validation'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(False, False, False))
def test_server_only_change_selects_only_server_image(self):
result = self.scope(['src/Heimdall.Web/Controllers/HealthController.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(True, False, False))
def test_agent_change_selects_cpu_and_gpu_images(self):
result = self.scope(['src/Heimdall.Agent/Program.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(False, True, True))
def test_shared_project_selects_all_dependent_images(self):
result = self.scope(['src/Heimdall.Application/Services/AgentService.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(True, True, True))
def test_version_tag_selects_every_image(self):
self.assertTrue(all(self.scope(['*']).values()))
def test_version_tag_must_be_semver_before_build_jobs_start(self):
with patch.dict(os.environ, {'EVENT_NAME': 'push', 'REF': 'refs/tags/not-a-version'}):
with self.assertRaises(SystemExit):
load_change_scope().changed_paths()
class PowerShellInstallerTests(unittest.TestCase):
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
def test_server_installer_has_valid_powershell_syntax(self):
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
result = subprocess.run([shutil.which('pwsh'), '-NoProfile', '-Command', parser],
cwd=REPO_ROOT, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
class PwaAssetTests(unittest.TestCase):
def test_manifest_raster_icons_exist_with_declared_dimensions(self):
manifest = json.loads((REPO_ROOT/'src/Heimdall.Web/wwwroot/manifest.webmanifest').read_text())
@@ -43,6 +97,12 @@ def load_test_plan():
spec.loader.exec_module(module)
return module
def load_build_plan():
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def load_efcore_policy():
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
module = importlib.util.module_from_spec(spec)
@@ -74,20 +134,54 @@ class TestPlanTests(unittest.TestCase):
self.assertIn('Heimdall.E2E.Tests', suites)
def test_agent_change_does_not_run_unrelated_web_tests(self):
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites']
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
suites = plan['suites']
self.assertIn('Heimdall.Agent.Tests', suites)
self.assertNotIn('Heimdall.Web.Tests', suites)
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
def test_web_change_does_not_rebuild_agent(self):
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
self.assertIn('Heimdall.Web.Tests', plan['suites'])
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
def test_solution_change_runs_all_and_docs_change_runs_none(self):
planner = load_test_plan()
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
solution = planner.plan(['global.json'])
self.assertEqual(len(solution['suites']), len(planner.TESTS))
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
docs = planner.plan(['docs/README.md'])
self.assertEqual(docs['suites'], [])
self.assertEqual(docs['build_projects'], [])
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
planner = load_test_plan()
result = planner.plan(['todo.md'])
self.assertEqual(result['mode'], 'all')
self.assertEqual(len(result['suites']), len(planner.TESTS))
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
class BuildPlanTests(unittest.TestCase):
def test_builds_only_existing_targets_from_the_plan(self):
builder = load_build_plan()
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
project = root/target
project.parent.mkdir(parents=True)
project.write_text('<Project />')
plan_path = root/'artifacts/tests/plan.json'
plan_path.parent.mkdir(parents=True)
plan_path.write_text(json.dumps({'build_projects':[target]}))
builder.ROOT = root
builder.PLAN = plan_path
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
builder.main()
run.assert_called_once_with(
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
cwd=root, check=True)
class GpuAgentImageTests(unittest.TestCase):
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
@@ -171,24 +265,31 @@ class ReleaseTests(unittest.TestCase):
def fake_request(req, timeout):
calls.append(req)
if req.method == 'GET' and '/releases/tags/' in req.full_url:
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': 'ci-abc123',
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':
return Response(b'[{"id":8,"name":"package.tar.gz"},{"id":9,"name":"provenance.json"}]')
names = ['heimdall-installers-1.2.3.zip', '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())
if req.method == 'DELETE': return Response(b'')
return Response(b'{"id":9}')
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)/'artifacts/packages'
directory.mkdir(parents=True)
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'0.0.0-ci.abc123'}))
(directory/'package.tar.gz').write_bytes(b'archive')
(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',
'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')
(directory/'agent-release-public.pem').write_bytes(b'key')
notes = Path(temp)/'release-notes.md'
notes.write_text('- Feature from PR #3.\n')
original = Path.cwd()
try:
os.chdir(temp)
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/heads/main','RELEASE_TOKEN':'dummy',
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
'RELEASE_NOTES_FILE':str(notes)}), \
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
try:
@@ -202,7 +303,7 @@ class ReleaseTests(unittest.TestCase):
def test_complete_published_release_is_not_mutated_on_rerun(self):
calls = self.execute()
self.assertTrue(any('/releases/tags/ci-abc123' in call.full_url for call in calls))
self.assertTrue(any('/releases/tags/1.2.3' in call.full_url for call in calls))
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
class OfflineReleaseAcceptanceTests(unittest.TestCase):
@@ -211,8 +312,8 @@ class OfflineReleaseAcceptanceTests(unittest.TestCase):
[sys.executable, str(ROOT/'accept-release-offline.py')],
cwd=REPO_ROOT, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn('CPU/GPU image digests', result.stdout)
self.assertIn('six simulated pushes', result.stdout)
self.assertIn('installer ZIP', result.stdout)
self.assertIn('selective Docker Hub tags', result.stdout)
if __name__ == '__main__':
unittest.main()
+38
View File
@@ -0,0 +1,38 @@
---
name: penpot-design-sync
description: Open Heimdall's connected Penpot workspace through Orca, authenticate safely, update design source alongside UI work, and verify the saved frames.
---
# Heimdall Penpot design sync
Heimdall's connected Penpot file is part of the UI source of truth. Whenever a change affects a screen, interaction, responsive layout, installer, or visible state, update the corresponding Penpot design in the same change. Do not leave a known implementation/design mismatch for a later task. When a UI change does not affect the design, state why in the Gitea issue evidence.
## Required entry path: Orca browser
1. Read the Orca `orca-cli` and `orca-computer-use` skills when not already loaded. Use the Orca CLI to list/open tabs and inspect browser state; use computer-use only when a visible GUI action is necessary.
2. Open the Penpot site in the Orca browser and sign in there using credentials already present in the environment or Orca-managed account. Never echo, log, paste into issue comments, or otherwise expose credential values. Do not try public Penpot Cloud as a substitute when Heimdall uses its connected self-hosted Penpot instance.
3. Confirm the signed-in team, Heimdall file, and target page before editing. The current Heimdall file is `aadb42b1-1e8d-8014-8008-7dc15de6e3ff`, team `073c6639-4451-8006-8008-e66329727382`. Resolve the current page from the file; do not assume page IDs remain stable.
4. Use Penpot MCP design operations only after Orca has opened the authenticated workspace and the correct file. The browser is the required way to establish and verify the user session, even when MCP is used for precise shape edits.
5. If login, workspace access, or the connected Penpot tool fails, diagnose the actual browser/session path first. Do not claim that the design was updated. Continue independent code work when possible, then report the concrete access blocker and leave the issue open.
## Design update workflow
1. Read `AGENTS.md`, the focused UI skill (for the site Agent installer, `site-agent-installer-ui/SKILL.md`), the UI implementation, and `docs/ui-pages.md`. Review the current Penpot page in Orca before changing it.
2. Compare the shipped behavior with the existing frames. Preserve Heimdall's established visual language and component patterns while representing every meaningful state introduced by the change. Cover loading, success, error/unavailable, permissions, and empty states when they are relevant.
3. For responsive UI, represent desktop and narrow/mobile widths. For installers, show platform and method selection, optional configuration, copyable commands, and unavailable signed-release/image states. Keep fake credentials, real tokens, private URLs, and customer data out of design content.
4. Update the existing relevant frame in place where practical. Rename frames so their platform, viewport, and state are clear. Remove obsolete competing mockups or stale secret-bearing examples when they would mislead implementers; preserve unrelated page content.
5. Match text, labels, command behavior, option availability, selected states, and copy affordances to the implementation and localization. Do not introduce unsupported options simply to imitate another product. Keep `docs/ui-pages.md` consistent when it describes the same UI.
6. Save/commit the design through Penpot, then verify the resulting frames in the Orca browser. Inspect the actual canvas at a useful zoom and check hierarchy, clipping, responsive composition, and stale content. A successful MCP response alone is not visual acceptance.
7. Record the Penpot file/page link, frame names/states changed, and visual review outcome in the linked Gitea issue. Distinguish verified Penpot design work from code tests and real release/deployment evidence.
## 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.
## Acceptance evidence
- Orca browser opened the self-hosted Penpot workspace and authenticated session was confirmed without exposing credentials.
- Correct Heimdall file and target page were confirmed before edits.
- Changed frames were inspected visually in the browser after the edit; list their names/states and link the file/page in the Gitea issue.
- Design and shipped UI/docs agree on supported choices, labels, states, and interaction behavior.
- If an external Penpot outage prevents completion, record the exact blocked step in Gitea and do not mark the design acceptance complete.
+21 -13
View File
@@ -1,26 +1,34 @@
---
name: release-automation
description: Build, sign, and automatically publish one Heimdall release for each validated merge to main.
description: Build and validate changed Heimdall images on pushes, then publish versioned Docker Hub images and signed installer assets for semver tags.
---
# Heimdall continuous delivery releases
# Heimdall build and release workflow
Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gitea.py`, `release-notes.py`, release signing, Docker image tags, or the Gitea release job.
Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_scope.py`, image build/push scripts, installer packages, release signing, or the Gitea release job.
## Delivery contract
- Every push to `main`, including documentation-only merges, runs validation and publishes. Pull requests never receive publication credentials.
- After `verify` and all server/Agent image build and scan jobs pass, the release job builds from the exact merged commit and publishes the server, CPU Agent, and GPU Agent artifacts.
- Each commit has version `0.0.0-ci.<12-character-sha>`, Docker tags `sha-<full-sha>` and the version tag, plus Gitea release identity `ci-<full-sha>`. Do not require maintainers to create Git tags or promote a draft.
- Gitea release notes list merged pull requests between the previous and current `main` commits. The release stays draft and prerelease while assets upload, then is published automatically only after the complete asset set is present. Gitea's `latest` endpoint sorts by creation time, so a delayed job for a commit behind `main` is published as a prerelease and cannot replace the current main release.
- The release contains deterministic archives, provenance, checksums, the ECDSA P-256 public key, immutable image digests, and the signed Agent update manifest.
- `RELEASE_SERVER_URL` must match the HTTPS forge origin in `BUILD_SERVER_URL`. Only the main publication job receives `RELEASE_TOKEN`, `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, and `RELEASE_SIGNING_KEY_B64`.
- Publication is idempotent per commit. A rerun may refresh assets for that exact commit release, but must not alter another commit's release or image tags.
- Pull requests run `verify` and build/scan only images affected by the changed project graph. They never receive Docker Hub or Gitea publication credentials.
- `test-plan.py` computes both affected test suites and build targets from transitive `ProjectReference` edges. PRs build only those test projects and any changed source projects not covered by them; the solution is built only for main/tag runs or broad CI/build-configuration changes. The solution restore remains locked and solution-wide for the dependency security report.
- A push to `main` validates the changed source and builds/scans/pushes only affected images. The affected image gets immutable `sha-<full-sha>` and mutable `latest` tags on Docker Hub. Main pushes do not create Gitea releases.
- 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.
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to collect registry digests, then 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. 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 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.
- 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.
- 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.
- Required publication secrets are `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN`, and `RELEASE_SIGNING_KEY_B64`; `RELEASE_SERVER_URL` must match the HTTPS origin in `BUILD_SERVER_URL`. They are used only on `main` image pushes or version-tag publication, never on pull requests.
## Image change scope
`scripts/ci/change_scope.py` maps changed paths to the exact Docker build graphs. Shared build configuration and shared Domain/Application/Contracts projects affect both Central and Agent. Web/Infrastructure/installer assets affect Central; Agent and mDNS projects plus the model affect Agent CPU and GPU; each Dockerfile affects only its own image. Keep this map aligned with the `COPY` instructions and project references in the Dockerfiles. A version tag deliberately selects every image.
## Offline end-to-end acceptance
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes the real packaging, release-note, and publication 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 generated notes, immediate publication, archive hashes, manifest signature, checksums, asset uploads, and exact immutable image tags/digests. 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, 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 behavior changes, also run the required disposable source-built Compose recipe with unique generated secrets, ports, project name, and local image tags. Its EXIT trap must verify project containers, volumes, and networks are gone and remove and verify absence of only its exact image tags.
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.
This simulation proves local packaging/signing/orchestration only. It does not prove Actions secrets, runner network, Docker Hub/Gitea publication, production Central configuration, or native Agent hardware/OS behavior. Record actual remote evidence in the focused Gitea issue; do not mark it complete based on the offline simulation.
These simulations do not prove Actions secrets, runner network, Docker Hub/Gitea publication, Central production configuration, or native Agent hardware/OS behavior. Record actual remote evidence in the focused Gitea issue; do not mark it complete based on offline simulation.
+24
View File
@@ -0,0 +1,24 @@
---
name: site-agent-installer-ui
description: Maintain and accept the Heimdall site Agent installer panel using Pangolin's platform/method/configuration/commands interaction pattern.
---
# Site Agent installer UI
Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.razor`. Its interaction model follows Pangolin's `OptionSelect` and `CopyTextBox`: platform tiles, platform-specific method tiles, optional configuration, then titled command blocks with an inline copy control. Keep `docs/ui-pages.md` and the connected Penpot installer frames aligned with the shipped flow; cover desktop and narrow/mobile widths plus the signed-release-unavailable state. Always open Penpot and authenticate through the Orca browser before editing the design; follow [penpot-design-sync/SKILL.md](../penpot-design-sync/SKILL.md) for the full workflow and evidence requirements.
## Project-specific rules
- 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.
- 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.
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
- Match Pangolin's control hierarchy and compact copy affordance while using Heimdall's MudBlazor theme and supported installation choices. Keep selection and copy feedback accessible with selected styling, tooltips/aria labels, and a check icon after copying.
## Acceptance workflow
1. Run the focused component suite: `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SiteDetailTests`.
2. Inspect rendered coverage for each platform and method, including the release-unavailable state and Docker image-unavailable state. Verify localization resources parse and `git diff --check` is clean.
3. For UI or install behavior changes, follow `compose-disposable-recipe/SKILL.md`: build from the changed source in an isolated Compose project, record exact generated image tags, then tear down only that project and verify its containers, volumes, network, and exact image tags are absent. Keep shared base images.
4. Update the linked Gitea issue with the observed results; distinguish component/local Compose evidence from real release, registry, or host installation evidence.
@@ -2,6 +2,14 @@
@using MudBlazor
@inject Heimdall.Web.Services.UiText Text
<style>
.installer-option { min-height: 3.25rem; justify-content: center; gap: .6rem; text-transform: none; }
.installer-option-selected { background: color-mix(in srgb, var(--mud-palette-primary) 10%, transparent); }
.installer-copy-box { position: relative; border: 1px solid var(--mud-palette-lines-default); border-radius: 6px; background: var(--mud-palette-surface); overflow: hidden; }
.installer-copy-box pre { margin: 0; padding: 1rem 3.5rem 1rem 1rem; overflow-x: auto; white-space: pre; font-size: .875rem; }
.installer-copy-button { position: absolute; top: .25rem; right: .25rem; background: var(--mud-palette-surface); }
</style>
<MudText Typo="Typo.h6" Class="mb-1">
<MudIcon Icon="@Icons.Material.Filled.Download" Size="Size.Small" Class="mr-1" />
@Text["SiteInstallPanel_Title"]
@@ -10,27 +18,51 @@
@Text["SiteInstallPanel_Description"]
</MudText>
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
<MudGrid Class="mb-3">
@if (_releaseLoading)
{
<MudProgressLinear Indeterminate="true" Color="Color.Primary" Class="mb-3" />
}
else if (_releaseReady)
{
<MudAlert Severity="Severity.Info" Class="mb-3">
@string.Format(Text["SiteInstallPanel_ReleaseReady"], _releaseVersion)
</MudAlert>
}
else
{
<MudAlert Severity="Severity.Error" Class="mb-3">
@Text["SiteInstallPanel_ReleaseUnavailable"]
</MudAlert>
}
<MudText Typo="Typo.subtitle1" Class="mb-3">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
<MudGrid Class="mb-4">
@foreach (var os in OperatingSystems)
{
<MudItem xs="12" sm="4" @key="os.Id">
<MudButton FullWidth="true" Variant="@(_operatingSystem == os.Id ? Variant.Filled : Variant.Outlined)"
<MudButton FullWidth="true" Variant="Variant.Outlined"
Color="@(_operatingSystem == os.Id ? Color.Primary : Color.Default)"
OnClick="@(() => SelectOperatingSystem(os.Id))">@os.Icon @Text[os.Label]</MudButton>
Class="@OptionClass(_operatingSystem == os.Id)"
OnClick="@(() => SelectOperatingSystem(os.Id))">
<MudIcon Icon="@os.Icon" Size="Size.Small" />
<span>@Text[os.Label]</span>
</MudButton>
</MudItem>
}
</MudGrid>
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Method"]</MudText>
<MudText Typo="Typo.subtitle1" Class="mb-3">@Text["SiteInstallPanel_Method"]</MudText>
<MudGrid Class="mb-4">
@foreach (var method in AvailableMethods)
{
var selectedMethod = method.Id;
<MudItem xs="12" sm="6" @key="method.Id">
<MudButton FullWidth="true" Variant="@(_method == method.Id ? Variant.Filled : Variant.Outlined)"
<MudButton FullWidth="true" Variant="Variant.Outlined"
Color="@(_method == method.Id ? Color.Primary : Color.Default)"
OnClick="@(() => _method = selectedMethod)">@Text[method.Label]</MudButton>
Class="@OptionClass(_method == method.Id)"
OnClick="@(() => _method = selectedMethod)">
@Text[method.Label]
</MudButton>
</MudItem>
}
</MudGrid>
@@ -38,9 +70,11 @@
@if ((_method == "docker-compose" || _method == "docker-run") && CanGenerateDocker &&
!string.IsNullOrWhiteSpace(_agentGpuImageReference))
{
<MudSwitch @bind-Value="_useGpuImage" Color="Color.Primary" Class="mb-2">
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudCheckBox @bind-Value="_useGpuImage" Color="Color.Primary" Class="mb-1">
@Text["SiteInstallPanel_NvidiaInference"]
</MudSwitch>
</MudCheckBox>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_NvidiaDescription"]</MudText>
@if (_useGpuImage)
{
<MudAlert Severity="Severity.Warning" Class="mb-3">@Text["SiteInstallPanel_NvidiaRequirement"]</MudAlert>
@@ -49,16 +83,7 @@
@if (_method == "docker-compose" && CanGenerateDocker)
{
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
<MudText Typo="Typo.subtitle2" Class="mb-2">@Text["SiteInstallPanel_Install"]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@ComposeYaml</code></pre>
</MudPaper>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCompose"]
</MudButton>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudText>
}
else if (_method == "docker-compose" && !CanGenerateDocker)
{
@@ -73,19 +98,32 @@ else if (_method == "docker-run")
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
@if (_method != "docker-run" || CanGenerateDocker)
@if (CanGenerateSelectedMethod)
{
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
<MudText Typo="Typo.subtitle1" Class="mb-3 mt-5">@Text["SiteInstallPanel_Commands"]</MudText>
@if (_method == "docker-compose")
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudPaper Class="installer-copy-box mb-3">
<pre><code>@ComposeYaml</code></pre>
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
<MudIconButton Icon="@CopyIconFor(ComposeYaml)" Color="Color.Default" Size="Size.Small"
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
OnClick="@(() => CopyCode(ComposeYaml))" />
</MudTooltip>
</MudPaper>
}
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
<MudPaper Class="installer-copy-box">
<pre><code>@command.Value</code></pre>
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
<MudIconButton Icon="@CopyIconFor(command.Value)" Color="Color.Default" Size="Size.Small"
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
OnClick="@(() => CopyCode(command.Value))" />
</MudTooltip>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
}
}
@@ -109,9 +147,9 @@ else if (_method == "windows-service")
private static readonly (string Id, string Label, string Icon)[] OperatingSystems =
[
("linux", "SiteInstallPanel_Linux", "🐧"),
("windows", "SiteInstallPanel_Windows", "⊞"),
("docker", "SiteInstallPanel_Docker", "🐳")
("linux", "SiteInstallPanel_Linux", Icons.Material.Filled.Terminal),
("windows", "SiteInstallPanel_Windows", Icons.Material.Filled.Window),
("docker", "SiteInstallPanel_Docker", Icons.Material.Filled.ViewInAr)
];
private string _operatingSystem = "linux";
@@ -119,10 +157,21 @@ else if (_method == "windows-service")
private string? _agentImageReference;
private string? _agentGpuImageReference;
private string? _updatePublicKeyPem;
private string? _releaseVersion;
private bool _releaseLoading = true;
private bool _releaseReady;
private bool _useGpuImage;
private string? _copiedCode;
private string CopyIconFor(string code) => _copiedCode == code ? Icons.Material.Filled.Check : Icons.Material.Filled.ContentCopy;
private static string OptionClass(bool selected) => selected ? "installer-option installer-option-selected" : "installer-option";
private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) &&
!string.IsNullOrWhiteSpace(_updatePublicKeyPem);
!string.IsNullOrWhiteSpace(_updatePublicKeyPem) && _releaseReady;
private bool CanGenerateSelectedMethod => _method switch
{
"docker-compose" or "docker-run" => CanGenerateDocker,
_ => _releaseReady
};
private IReadOnlyList<(string Id, string Label)> AvailableMethods => _operatingSystem switch
{
@@ -190,6 +239,11 @@ else if (_method == "windows-service")
try
{
var release = await Api.GetLatestUpdateAsync();
_releaseVersion = release?.Version;
_releaseReady = !string.IsNullOrWhiteSpace(release?.UpdatePublicKeyPem) &&
!string.IsNullOrWhiteSpace(release?.SignedManifest) &&
!string.IsNullOrWhiteSpace(release?.ManifestSignature) &&
release?.Assets.Count > 0;
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
@@ -202,6 +256,10 @@ else if (_method == "windows-service")
{
// Native installers fetch signed release metadata directly; Docker needs a verified image reference and key.
}
finally
{
_releaseLoading = false;
}
}
private string ComposeYaml
@@ -405,7 +463,13 @@ else if (_method == "windows-service")
private async Task CopyCode(string code)
{
await JsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", code);
_copiedCode = code;
StateHasChanged();
Snackbar.Add(Text["SiteInstallPanel_Copied"], Severity.Success);
await Task.Delay(TimeSpan.FromSeconds(2));
if (_copiedCode == code)
_copiedCode = null;
await InvokeAsync(StateHasChanged);
}
private static string Slugify(string value)
@@ -2640,6 +2640,12 @@
<data name="SiteInstallPanel_Description" xml:space="preserve">
<value>Deploy the Heimdall agent connector on the machine that will monitor this site.</value>
</data>
<data name="SiteInstallPanel_ReleaseReady" xml:space="preserve">
<value>Release available: {0}. The required installation files were found.</value>
</data>
<data name="SiteInstallPanel_ReleaseUnavailable" xml:space="preserve">
<value>No usable signed release is configured in Central. Configure the release API and publish a version before generating installation commands.</value>
</data>
<data name="SiteInstallPanel_ImageUnavailable" xml:space="preserve">
<value>The agent image manifest from Central is unavailable. Retry before copying the compose file.</value>
</data>
@@ -4095,6 +4101,9 @@
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
<data name="SiteInstallPanel_NvidiaDescription" xml:space="preserve">
<value>Use the CUDA agent image when a compatible NVIDIA GPU and Container Toolkit are available.</value>
</data>
<data name="SiteInstallPanel_NvidiaRequirement" xml:space="preserve">
<value>Requires an NVIDIA GPU, NVIDIA Container Toolkit, and a compatible host driver. Inference falls back to CPU if CUDA cannot be initialized.</value>
</data>
@@ -2640,6 +2640,12 @@
<data name="SiteInstallPanel_Description" xml:space="preserve">
<value>Déployez le connecteur Heimdall sur la machine qui surveillera ce site.</value>
</data>
<data name="SiteInstallPanel_ReleaseReady" xml:space="preserve">
<value>Release disponible : {0}. Les fichiers requis pour l’installation ont été trouvés.</value>
</data>
<data name="SiteInstallPanel_ReleaseUnavailable" xml:space="preserve">
<value>Aucune release signée exploitable n’est configurée dans Central. Configurez l’API des releases et publiez une version avant de générer les commandes d’installation.</value>
</data>
<data name="SiteInstallPanel_ImageUnavailable" xml:space="preserve">
<value>Le manifeste d’image de l’agent fourni par Central est indisponible. Réessayez avant de copier le compose.</value>
</data>
@@ -4095,6 +4101,9 @@
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Utiliser l’inférence GPU NVIDIA</value>
</data>
<data name="SiteInstallPanel_NvidiaDescription" xml:space="preserve">
<value>Utilise l’image CUDA de l’agent si un GPU NVIDIA compatible et le Container Toolkit sont disponibles.</value>
</data>
<data name="SiteInstallPanel_NvidiaRequirement" xml:space="preserve">
<value>Nécessite un GPU NVIDIA, le NVIDIA Container Toolkit et un pilote hôte compatible. L’inférence repasse sur le CPU si CUDA ne peut pas démarrer.</value>
</data>
@@ -2640,6 +2640,12 @@
<data name="SiteInstallPanel_Description" xml:space="preserve">
<value>Déployez le connecteur Heimdall sur la machine qui surveillera ce site.</value>
</data>
<data name="SiteInstallPanel_ReleaseReady" xml:space="preserve">
<value>Release disponible : {0}. Les fichiers requis pour l’installation ont été trouvés.</value>
</data>
<data name="SiteInstallPanel_ReleaseUnavailable" xml:space="preserve">
<value>Aucune release signée exploitable n’est configurée dans Central. Configurez l’API des releases et publiez une version avant de générer les commandes d’installation.</value>
</data>
<data name="SiteInstallPanel_ImageUnavailable" xml:space="preserve">
<value>Le manifeste d’image de l’agent fourni par Central est indisponible. Réessayez avant de copier le compose.</value>
</data>
@@ -4095,6 +4101,9 @@
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
<data name="SiteInstallPanel_NvidiaDescription" xml:space="preserve">
<value>Use the CUDA agent image when a compatible NVIDIA GPU and Container Toolkit are available.</value>
</data>
<data name="SiteInstallPanel_NvidiaRequirement" xml:space="preserve">
<value>Requires an NVIDIA GPU, NVIDIA Container Toolkit, and a compatible host driver. Inference falls back to CPU if CUDA cannot be initialized.</value>
</data>
@@ -1523,7 +1523,7 @@ public record CreateApiKeyResult(
[property: JsonPropertyName("siteId")] Guid? SiteId,
[property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt);
public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary<string, PlatformAssetInfo> Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; set; } [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } }
public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary<string, PlatformAssetInfo> Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; set; } [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } [JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; } [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; } }
public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } }
public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount);
@@ -98,6 +98,25 @@ public class SiteDetailTests : PageTestBase
});
}
[Fact]
public void SiteDetail_ReleaseAbsente_MasqueLesCommandesDInstallationNative()
{
Handler.OnGet("api/updates/latest", System.Net.HttpStatusCode.BadGateway);
Handler.OnGet("api/sites/", new SiteItem(
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10)));
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-no-release", DateTime.UtcNow.AddHours(24)));
LoginAs();
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Générer un token"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-no-release"));
cut.Markup.ShouldContain("Aucune release signée exploitable n’est configurée dans Central");
cut.Markup.ShouldNotContain("install-agent.sh");
cut.Markup.ShouldNotContain("install-agent.ps1");
}
[Fact]
public void SiteDetail_ChoisirImageNvidia_GenereComposeAvecGpuEtProviderCuda()
{
@@ -159,9 +178,9 @@ public class SiteDetailTests : PageTestBase
cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-detail-42"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Docker", StringComparison.OrdinalIgnoreCase)).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Copier le docker-compose.yml"));
cut.WaitForAssertion(() => cut.Find(".installer-copy-box").ShouldNotBeNull());
cut.FindAll("button").Single(b => b.TextContent.Contains("Copier le docker-compose.yml")).Click();
cut.Find(".installer-copy-box button").Click();
cut.WaitForAssertion(() =>
{
@@ -206,7 +225,13 @@ public class SiteDetailTests : PageTestBase
Version = "1.0.0",
ContainerImage = "registry.example/heimdall-agent",
ContainerImageDigest = "sha256:" + new string('a', 64),
UpdatePublicKeyPem = "test-public-key"
UpdatePublicKeyPem = "test-public-key",
SignedManifest = "eyJ2ZXJzaW9uIjoiMS4wLjAifQ==",
ManifestSignature = "c2lnbmF0dXJl",
Assets = new Dictionary<string, PlatformAssetInfo>
{
["portable"] = new() { Url = "https://registry.example/agent.tar.gz", Sha256 = new string('c', 64), Size = 1 }
}
};
private static LatestReleaseInfo AgentReleaseWithGpu() => new()
@@ -216,7 +241,13 @@ public class SiteDetailTests : PageTestBase
ContainerImageDigest = "sha256:" + new string('a', 64),
ContainerImageGpu = "registry.example/heimdall-agent-gpu",
ContainerImageGpuDigest = "sha256:" + new string('b', 64),
UpdatePublicKeyPem = "test-public-key"
UpdatePublicKeyPem = "test-public-key",
SignedManifest = "eyJ2ZXJzaW9uIjoiMS4wLjAifQ==",
ManifestSignature = "c2lnbmF0dXJl",
Assets = new Dictionary<string, PlatformAssetInfo>
{
["portable"] = new() { Url = "https://registry.example/agent.tar.gz", Sha256 = new string('c', 64), Size = 1 }
}
};
private static YamlMappingNode ParseCompose(string compose)