feat(release): publish a signed release on every main merge #312

Merged
arnaud.dartois merged 1 commits from feat/continuous-delivery-main-releases into main 2026-11-09 10:10:23 +01:00
14 changed files with 252 additions and 111 deletions

No files matched your search

+1 -1
View File
@@ -19,6 +19,6 @@ Refs #
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
- [ ] Revue des changements de contrats/migrations/configuration
- [ ] Si tag : publication des images et release brouillon vérifiées
- [ ] Après merge `main` : release publiée automatiquement, assets complets et version courante vérifiée
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.
+34 -29
View File
@@ -3,22 +3,6 @@ on:
pull_request:
push:
branches: [main]
tags: ['v*']
paths:
- 'src/**'
- 'tests/**'
- 'Heimdall.slnx'
- 'global.json'
- 'Directory.Build.*'
- 'GitVersion*.yml'
- '.dockerignore'
- '.env.example'
- '.gitea/workflows/**'
- 'scripts/ci/**'
- 'docker/**'
- 'install/**'
- 'models/**'
- 'Makefile'
permissions:
contents: read
env:
@@ -43,15 +27,12 @@ jobs:
PUSH_BEFORE_SHA: ${{ gitea.event.before }}
CURRENT_SHA: ${{ gitea.sha }}
EVENT_NAME: ${{ gitea.event_name }}
IS_RELEASE_TAG: ${{ startsWith(gitea.ref, 'refs/tags/v') }}
REF: ${{ gitea.ref }}
run: |
set -eu
if [ "$EVENT_NAME" = pull_request ]; then
changed_files="$(git diff --name-only "$PR_BASE_SHA...HEAD")"
elif [ "$IS_RELEASE_TAG" = true ]; then
echo 'run_validation=true' >> "$GITEA_OUTPUT"
exit 0
elif [ -n "$PUSH_BEFORE_SHA" ] && [ "$PUSH_BEFORE_SHA" != 0000000000000000000000000000000000000000 ]; then
changed_files="$(git diff --name-only "$PUSH_BEFORE_SHA" "$CURRENT_SHA")"
else
@@ -59,6 +40,11 @@ jobs:
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
@@ -111,8 +97,6 @@ jobs:
test "$AGENT_IMAGE_RESULT" = success
test "$AGENT_GPU_IMAGE_RESULT" = success
test "$DOCKERHUB_RESULT" = success
;;
push:refs/tags/v*)
test "$RELEASE_RESULT" = success
;;
esac
@@ -349,6 +333,8 @@ jobs:
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
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -361,9 +347,9 @@ jobs:
bash scripts/ci/cleanup-docker.sh after
fi
publish:
name: Publish versioned release
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/v')
needs: [changes, verify]
name: Publish signed main release
if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main'
needs: [changes, verify, server_image, agent_image, agent_gpu_image]
runs-on: [ubuntu-latest, build-agent]
container:
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
@@ -387,15 +373,30 @@ jobs:
fetch-depth: 0
persist-credentials: false
- run: bash scripts/ci/bootstrap.sh
- name: Require a release from main history
run: git merge-base --is-ancestor HEAD origin/main
- name: Rebuild release archives from verified commit
- name: Rebuild release archives from verified merge
env:
BUILD_REF: ${{ gitea.ref }}
BUILD_REPOSITORY: ${{ gitea.repository }}
BUILD_RUN_ID: ${{ gitea.run_id }}
run: bash scripts/ci/package.sh
- name: Publish immutable images and draft release
- name: Generate merged pull request release notes
env:
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
env:
BUILD_REF: ${{ gitea.ref }}
BUILD_REPOSITORY: ${{ gitea.repository }}
@@ -405,4 +406,8 @@ jobs:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }}
EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }}
RELEASE_NOTES_FILE: artifacts/release-notes.md
run: bash scripts/ci/publish.sh
- name: Reclaim build storage after release
if: always()
run: bash scripts/ci/cleanup-docker.sh after
+1 -1
View File
@@ -18,7 +18,7 @@ Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’or
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é.
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. Les builds de `main` publient les images continues, mais ne créent pas de release Agent; il faut pousser un tag SemVer, attendre le brouillon, puis le promouvoir pour que l’API `latest` le serve.
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>`.
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.
+2 -2
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`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version.
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.
## Sélection des runners
@@ -25,7 +25,7 @@ Après validation de `verify` sur `main`, chaque job d'image publie son tag immu
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.
Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` lancent le job séparé de release, après validation de `verify`. Un build réussi sur `main` ne crée pas de release Gitea : il publie les images `latest` et `sha-*` seulement. Pour préparer une version depuis le commit validé de `main`, créer et pousser un tag, par exemple `git tag -a v1.2.3 -m "Heimdall v1.2.3" && git push origin v1.2.3`. Le tag doit respecter la forme SemVer et viser un commit de `main`. Le job reconstruit et scanne les trois images, puis publie les images CPU et CUDA de l’Agent et joint leurs manifestes au manifeste ECDSA signé. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release Gitea reste en brouillon jusqu'à promotion explicite. Aucun tag n’existe encore sur le dépôt; aucun run de release tagué n’a donc eu lieu.
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.
## Renovate
+48 -17
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Offline acceptance for package.sh and publish.sh using synthetic credentials and API doubles."""
"""Offline acceptance for packaging, release notes, and publication with synthetic doubles."""
import base64
import email
import hashlib
@@ -19,7 +19,6 @@ from urllib.parse import parse_qs, urlsplit
ROOT = Path(__file__).resolve().parents[2]
REPOSITORY = 'arnaud.dartois/Heimdall'
TAG = 'v1.2.3'
DOCKER_TOKEN = 'offline-docker-token-not-valid'
RELEASE_TOKEN = 'offline-gitea-token-not-valid'
SERVER_DIGEST = 'sha256:' + '1' * 64
@@ -51,7 +50,7 @@ def main():
fakebin = temp / 'bin'
fakebin.mkdir()
docker_log = temp / 'docker-commands.jsonl'
release_state = {'draft': None, 'assets': {}, 'authorized': 0}
release_state = {'release': None, 'assets': {}, 'authorized': 0}
subprocess.run([
'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes',
@@ -137,7 +136,15 @@ sys.exit(12)
self._json(401, {})
return
path = urlsplit(self.path).path
if path.endswith('/releases/tags/' + TAG):
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
if '/compare/' in path:
self._json(200, {'commits': [{'sha': 'synthetic-merge-commit'}]})
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):
self._json(404, {'message': 'not found'})
elif path.endswith('/releases/7301/assets'):
self._json(200, [])
@@ -152,12 +159,16 @@ 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'] == TAG
assert release['tag_name'] == 'ci-' + subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
assert release['draft'] is True
assert release['prerelease'] is True
assert 'Offline acceptance feature' in release['body']
assert release['target_commitish'] == subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
release_state['draft'] = release
self._json(201, {'id': 7301, 'draft': True,
release_state['release'] = release
self._json(201, {'id': 7301, 'draft': True, 'prerelease': True,
'tag_name': release['tag_name'],
'html_url': 'https://gitea.test/releases/7301'})
return
if path.endswith('/releases/7301/assets'):
@@ -175,6 +186,20 @@ sys.exit(12)
return
self._json(404, {'message': 'unexpected request'})
def do_PATCH(self):
if not self._authorized():
self._json(401, {})
return
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'}
release_state['release']['draft'] = body['draft']
release_state['release']['prerelease'] = body['prerelease']
self._json(200, release_state['release'])
return
self._json(404, {'message': 'unexpected request'})
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, private_cert_key)
@@ -190,7 +215,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/tags/' + TAG,
'BUILD_REF': 'refs/heads/main',
'BUILD_REPOSITORY': REPOSITORY,
'BUILD_RUN_ID': 'offline-acceptance',
'BUILD_SERVER_URL': origin,
@@ -203,8 +228,14 @@ sys.exit(12)
'OFFLINE_SERVER_DIGEST': SERVER_DIGEST,
'OFFLINE_AGENT_DIGEST': AGENT_DIGEST,
'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST,
'RELEASE_NOTES_FILE': str(artifacts_dir/'release-notes.md'),
})
run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh')
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')
run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh')
packages = ROOT / 'artifacts/packages'
@@ -214,20 +245,19 @@ 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'] == TAG
assert manifest['version'] == '0.0.0-ci.' + commit[:12]
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'])
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/' + TAG
assert provenance['commit'] == commit and provenance['ref'] == 'refs/heads/main'
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}-{TAG.removeprefix("v")}.tar.gz'
archive = f'heimdall-agent-{platform}-0.0.0-ci.{commit[:12]}.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')],
@@ -248,15 +278,16 @@ sys.exit(12)
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:1.2.3',
f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:1.2.3',
f'eltruncho/heimdall-agent-gpu:sha-{commit}', f'eltruncho/heimdall-agent-gpu:1.2.3',
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 sum(call[:1] == ['login'] for call in docker_calls) == 1
assert release_state['draft']['draft'] is True
assert release_state['release']['draft'] is False
assert release_state['release']['prerelease'] is False
assert len(release_state['assets']) >= 9
assert release_state['authorized'] >= 7
print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, CPU/GPU image digests, and six simulated pushes.')
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.')
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
finally:
server.shutdown()
-5
View File
@@ -3,11 +3,6 @@ set -euo pipefail
sha=$(git rev-parse HEAD)
ref=${BUILD_REF:-}
version="0.0.0-ci.${sha:0:12}"
if [[ "$ref" == refs/tags/* ]]; then
tag=${ref#refs/tags/}
[[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z]+([.-][0-9A-Za-z]+)*)?)$ ]] || { echo 'Expected vMAJOR.MINOR.PATCH[-prerelease]' >&2; exit 1; }
version=${BASH_REMATCH[1]}
fi
mkdir -p artifacts/packages
for component in Web Agent; do
rid=portable
+8 -7
View File
@@ -33,16 +33,17 @@ 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)
tag=${BUILD_REF#refs/tags/}
[[ "$BUILD_REF" == refs/tags/v* ]] || exit 1
[[ "$BUILD_REF" == refs/heads/main ]] || { echo 'Release publication is restricted to verified main merges' >&2; exit 1; }
tag="ci-$sha"
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 'v'+p['version'] != sys.argv[2]:
raise SystemExit('Artifact provenance does not match checkout/tag')
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')
PY
(cd artifacts/packages && sha256sum --check SHA256SUMS)
printf '%s' "${tag#v}" > artifacts/version
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"
@@ -66,7 +67,7 @@ for component in server agent agent-gpu; do
else
image=$server_image
fi
for image_tag in "sha-$sha" "${tag#v}"; do
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"}}')
@@ -121,7 +122,7 @@ root=Path('artifacts/packages')
image=json.loads((root/'agent-image.json').read_text())
gpu_image=json.loads((root/'agent-image-gpu.json').read_text())
package_version=Path('artifacts/version').read_text().strip()
version='v'+package_version
version=package_version
assets={}
for path in root.glob('heimdall-agent-*.tar.gz'):
suffix=f'-{package_version}.tar.gz'
+42 -19
View File
@@ -1,4 +1,4 @@
"""Create/update only a draft Gitea release; never log auth or response bodies."""
"""Create/update the published Gitea release for one verified main commit."""
import json
import os
import uuid
@@ -8,9 +8,9 @@ import urllib.parse
import urllib.request
base = os.environ['BUILD_SERVER_URL'] + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
tag = os.environ['BUILD_REF'].removeprefix('refs/tags/')
token = os.environ['RELEASE_TOKEN']
provenance = json.loads(Path('artifacts/packages/provenance.json').read_text())
tag = 'ci-' + provenance['commit']
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,23 +26,46 @@ 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())
if release is None:
release = request('/releases', 'POST', {
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': tag,
'draft': True, 'prerelease': '-' in tag,
'body': f"Commit: `{provenance['commit']}`\nActions run: {provenance['run_id']}\n"
'Server/PWA and agent only; checksums and image digests attached.\n'
'Draft: promote explicitly after reviewing publication evidence.'})
if not release['draft']:
raise SystemExit('Refusing to mutate an already public release')
# Reruns replace draft assets; published releases remain immutable.
for asset in request(f"/releases/{release['id']}/assets"):
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
'draft': True, 'prerelease': True,
'body': f"Automated continuous delivery for merge `{provenance['commit']}`.\n"
f"Actions run: {provenance['run_id']}\n\n"
'## Changes\n'
+ Path(os.environ['RELEASE_NOTES_FILE']).read_text()})
if release.get('tag_name') != tag:
raise SystemExit('Refusing to mutate a release not owned by this commit')
assets_path = f"/releases/{release['id']}/assets"
assets = request(assets_path)
expected_names = {path.name for path in package_files}
if not release.get('draft'):
if {asset.get('name') for asset in assets} != expected_names:
raise SystemExit('Published release has incomplete assets; refusing to mutate it')
print('Release already published: '+release['html_url'])
raise SystemExit(0)
# Keep the release invisible to `/releases/latest` until all signed assets are present.
for asset in assets:
request(f"/releases/{release['id']}/assets/{asset['id']}", 'DELETE')
for path in sorted(Path('artifacts/packages').iterdir()):
if path.is_file():
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
'POST', payload, 'multipart/form-data; boundary='+boundary)
print('Draft release: '+release['html_url'])
for path in package_files:
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
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
published = request(f"/releases/{release['id']}", 'PATCH', {
'draft': False,
'prerelease': expected_prerelease,
})
if published.get('draft') is not False or published.get('prerelease') is not expected_prerelease:
raise SystemExit('Gitea did not publish the completed release with the expected latest status')
print('Published release: '+release['html_url'])
+48
View File
@@ -0,0 +1,48 @@
"""Generate release notes from pull requests merged by one main push."""
import json
import os
from pathlib import Path
import urllib.error
import urllib.parse
import urllib.request
base = os.environ['BUILD_SERVER_URL'].rstrip('/') + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
token = os.environ['GITEA_TOKEN']
before = os.environ['BEFORE_SHA']
current = os.environ['CURRENT_SHA']
def get(path):
request = urllib.request.Request(base + path, headers={
'Authorization': 'token ' + token,
'Accept': 'application/json',
})
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
if error.code == 404:
return None
raise SystemExit(f'Gitea release notes API failed: HTTP {error.code}') from None
comparison = get('/compare/' + urllib.parse.quote(before, safe='') + '...' + urllib.parse.quote(current, safe=''))
if comparison is None:
raise SystemExit('Gitea could not compare the previous and current main commits')
pulls = {}
for commit in comparison.get('commits', []):
pull = get('/commits/' + urllib.parse.quote(commit['sha'], safe='') + '/pull')
if pull and pull.get('merged') and pull.get('number'):
pulls[pull['number']] = pull
lines = []
for number, pull in sorted(pulls.items()):
title = pull.get('title') or f'Pull request #{number}'
url = pull.get('html_url') or f"{base.removesuffix('/api/v1/repos/' + os.environ['BUILD_REPOSITORY'])}/pulls/{number}"
lines.append(f'- {title} ([#{number}]({url}))')
if not lines:
lines = [f'- Changes merged in commit `{current}`.']
Path('artifacts/release-notes.md').write_text('\n'.join(lines) + '\n')
print(f'Generated release notes for {len(pulls)} merged pull request(s).')
+17 -18
View File
@@ -1,4 +1,4 @@
"""Contract tests for security gates and draft release uploads, without network."""
"""Contract tests for security gates and automatic release uploads, without network."""
import contextlib
import io
import importlib.util
@@ -163,7 +163,7 @@ class AdvisoryTests(unittest.TestCase):
self.assertNotEqual(self.check(report), 0)
class ReleaseTests(unittest.TestCase):
def execute(self, public=False):
def execute(self):
calls = []
class Response(io.BytesIO):
def __enter__(self): return self
@@ -171,40 +171,39 @@ 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': not public,
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': 'ci-abc123',
'html_url': 'https://example.test/releases/7'}).encode())
if req.method == 'GET':
return Response(b'[{"id":8}]')
return Response(b'[{"id":8,"name":"package.tar.gz"},{"id":9,"name":"provenance.json"}]')
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'}))
(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')
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/tags/v1.2.3','RELEASE_TOKEN':'dummy'}), \
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/heads/main','RELEASE_TOKEN':'dummy',
'RELEASE_NOTES_FILE':str(notes)}), \
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
try:
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
except SystemExit as result:
if result.code != 0:
raise
finally:
os.chdir(original)
return calls
def test_draft_assets_use_multipart_and_delete_accepts_204(self):
def test_complete_published_release_is_not_mutated_on_rerun(self):
calls = self.execute()
uploads = [x for x in calls if x.method == 'POST']
self.assertEqual(len(uploads), 2)
for request in uploads:
self.assertTrue(request.get_header('Content-type').startswith('multipart/form-data; boundary='))
self.assertIn(b'name="attachment"', request.data)
self.assertEqual(sum(x.method == 'DELETE' for x in calls), 1)
def test_public_release_cannot_be_mutated(self):
with self.assertRaisesRegex(SystemExit, 'already public'):
self.execute(public=True)
self.assertTrue(any('/releases/tags/ci-abc123' in call.full_url for call in calls))
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
class OfflineReleaseAcceptanceTests(unittest.TestCase):
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
+15 -12
View File
@@ -1,23 +1,26 @@
---
name: release-automation
description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests.
description: Build, sign, and automatically publish one Heimdall release for each validated merge to main.
---
# Heimdall tagged release workflow
# Heimdall continuous delivery releases
Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gitea.py`, release signing, Docker image tags, or the Gitea release job.
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.
## Release invariants
## Delivery contract
- A release tag must be `vMAJOR.MINOR.PATCH[-prerelease]`, point to a commit on `main`, and pass the complete `verify` job before publication starts.
- `RELEASE_SERVER_URL` must be the expected HTTPS forge origin and must match `BUILD_SERVER_URL`; the publisher rejects paths, query strings, user info, and host/port mismatches.
- Use a dedicated Gitea `RELEASE_TOKEN`, Docker Hub credentials, and a base64 encoded ECDSA P-256 key only in the tagged release job. Never make them available to PR jobs or print them.
- Do not overwrite published image tags owned by another commit or mutate an already published Gitea release. Releases remain drafts until an operator promotes them.
- The release includes deterministic Web and Agent archives, provenance, checksums, the public key, immutable image digests, and a signed Agent update manifest.
- A successful `main` build publishes Docker `latest` and immutable `sha-*` images but does not create a Gitea release. An operator starts versioned publication by pushing a SemVer tag (`git tag -a vX.Y.Z ... && git push origin vX.Y.Z`) that points to a commit on `main`.
- 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.
## Offline end-to-end acceptance
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. The acceptance script invokes the real `package.sh` and `publish.sh`, but creates disposable ECDSA P-256 credentials and substitutes both publication boundaries: a local TLS Gitea API double records only draft release/assets, and a fake Docker CLI records tags and simulates registry digests. It verifies archive hashes, manifest signature, checksums, asset uploads, and expected image tags/digests. The fake CLI must never call a registry, and the API server must bind only to loopback, suppress request logging, and reject non-synthetic authorization.
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.
This simulation proves local packaging/signing/orchestration only. It does not prove the Actions secrets, runner network, Docker Hub/Gitea behavior, native Agent installation, or rollback. Keep the focused Gitea release issue open until a real tagged run and the relevant host validation have succeeded.
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.
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.
@@ -59,6 +59,10 @@
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never"
Breakpoint="Breakpoint.Sm" MiniVariantWidth="64px" @bind-MiniVariant="_miniVariant">
<MudNavMenu>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="px-4 py-2" data-testid="server-version">
Version @(_serverVersion ?? "—")
</MudText>
<MudDivider />
@if (Auth.IsLoggedIn)
{
<MudText Typo="Typo.overline" Color="Color.Secondary" Class="px-4 py-2">@Text["Navigation"]</MudText>
@@ -140,6 +144,7 @@
private bool _miniVariant;
private bool _darkMode = true;
private string _searchQuery = "";
private string? _serverVersion;
/// <summary>Sous-menu « Gestion des utilisateurs » : replié par défaut,
/// déplié automatiquement quand on est déjà sur une de ses pages.</summary>
@@ -156,6 +161,13 @@
protected override async Task OnInitializedAsync()
{
try
{
var version = await Api.GetServerVersionAsync();
_serverVersion = version?.Version;
}
catch { /* Keep the navigation usable while version metadata is unavailable. */ }
if (!Auth.IsLoggedIn) return;
try
{
@@ -50,6 +50,12 @@ public class HeimdallApiClient : IDisposable
return client;
}
public async Task<ServerVersionInfo?> GetServerVersionAsync(CancellationToken ct = default)
{
var client = _httpFactory.CreateClient("HeimdallApi");
return await client.GetFromJsonAsync<ServerVersionInfo>("api/version", Json, ct);
}
/// <summary>
/// Lit le message d'erreur renvoyé par l'API pour une réponse non-2xx.
/// Gère le format maison des controllers (<c>{ error = "..." }</c>) et les
@@ -1106,6 +1112,11 @@ public class HeimdallApiClient : IDisposable
}
}
public sealed class ServerVersionInfo
{
[JsonPropertyName("version")] public string Version { get; set; } = string.Empty;
}
public class CameraItem
{
public Guid Id { get; set; }
@@ -9,6 +9,19 @@ namespace Heimdall.Web.Tests.Components.Pages;
public class NavigationTests : PageTestBase
{
[Fact]
public void MainLayout_AfficheVersionDuServeur()
{
Handler.OnGet("api/version", new { version = "0.0.0-ci.abcdef123456" });
Services.GetRequiredService<BunitNavigationManager>()
.NavigateTo("http://localhost/dashboard");
var cut = Render<MainLayout>();
cut.WaitForAssertion(() => cut.Find("[data-testid='server-version']")
.TextContent.ShouldContain("0.0.0-ci.abcdef123456"));
}
[Fact]
public void MainLayout_Admin_VoitSousMenuGestionUtilisateurs()
{