Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95c73c3052 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: secure-env-secrets
|
||||
description: Store or retrieve a user-provided secret as a local environment variable outside repositories, without exposing its value in commands or output. Does not configure CI or remote services.
|
||||
---
|
||||
|
||||
# Secure local environment secrets
|
||||
|
||||
Use this skill only for secrets the user supplied or explicitly authorized you to retrieve. Keep values outside repositories and never repeat them in commentary, tool output, logs, diffs, or a final response.
|
||||
|
||||
## Choose scope and storage
|
||||
|
||||
- Prefer the operating system credential store or an existing secret manager, and expose a value only to the process that needs it.
|
||||
- A secret in an environment variable is available to same-user processes and is not a secure store. Do not add secrets to global shell startup files by default.
|
||||
- If the user needs persistence and no credential store is available, use a user-owned directory outside every repository, with directory permissions `0700` and file permissions `0600`. Explain that permissions restrict other accounts but do not encrypt the file. Avoid synced/shared locations unless requested.
|
||||
- Keep a persistent file inert data (for example, base64-encoded values keyed by validated variable names); do not source a file containing arbitrary shell code. Load a requested value only in the shell/process that needs it, without printing it.
|
||||
|
||||
## Read or write safely
|
||||
|
||||
1. Establish the variable name, intended scope (one command, one shell, or persistent local use), and destination. Ask only for details that change the safe implementation.
|
||||
2. Before writing, check for an existing value without displaying it. Preserve it unless the user explicitly requests replacement; do not silently delete credentials.
|
||||
3. Accept the secret through a masked prompt or credential-store protected input. Never place it in a command string, here-document, argument, URL, exported helper variable, or ordinary prompt. If the interface would expose input through tool history/output, ask the user to enter it locally and continue with metadata-only checks.
|
||||
4. Resolve and verify the destination is outside all involved repositories. Create owner-only directories and set owner-only file permissions before writing.
|
||||
5. Disable shell tracing and avoid commands that dump environment or variable values. Expose the variable only for the requested operation.
|
||||
6. Verify presence and permissions without printing or deriving information from the value. Report only the variable name, storage scope/path, and set/unset state.
|
||||
|
||||
Never use `env`, `printenv`, `set`, `echo "$SECRET"`, shell tracing, or a diff to inspect secret values. Do not place secrets in project `.env` files, Compose definitions, source code, CI workflows, or test fixtures. This skill does not configure remote CI, cloud, registry, or account secrets.
|
||||
|
||||
If a value appears in output or is committed, stop using it and tell the user it should be rotated. Do not rotate credentials in an external service unless separately authorized.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Secure Environment Secrets"
|
||||
short_description: "Keep user secrets outside repositories"
|
||||
default_prompt: "Safely read or store the user-provided secret as a local environment variable outside the repository."
|
||||
@@ -2,14 +2,13 @@
|
||||
name: "🐛 Bug"
|
||||
about: "Comportement incorrect, régression ou risque fonctionnel détecté"
|
||||
title: "BUG: "
|
||||
labels: ["type:bug"]
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Bug — à remplir avant de commencer
|
||||
> Si le bug est un écart par rapport à la spec, citer `docs/MASTER_SPECIFICATION.md`.
|
||||
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -23,7 +22,7 @@ body:
|
||||
id: observe
|
||||
attributes:
|
||||
label: "🐞 Comportement observé"
|
||||
description: "Ce qui se passe réellement (avec logs/erreurs expurgés de toute donnée sensible)"
|
||||
description: "Ce qui se passe réellement (avec logs/erreurs si dispo)"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -39,7 +38,7 @@ body:
|
||||
id: repro
|
||||
attributes:
|
||||
label: "🔁 Reproduction"
|
||||
description: "Étapes pour reproduire + environnement (dev/prod, Docker, noms de variables sans leurs valeurs)"
|
||||
description: "Étapes pour reproduire + environnement (dev/prod, docker, env vars)"
|
||||
placeholder: "1. …\n2. …\n3. …"
|
||||
|
||||
- type: input
|
||||
@@ -70,4 +69,5 @@ body:
|
||||
options:
|
||||
- label: "Bug reproduit avant fix (test qui échoue)"
|
||||
- label: "Fix implémenté + tests verts (`make test`)"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
@@ -2,13 +2,12 @@
|
||||
name: "🔧 Maintenance / Chore"
|
||||
about: "Tâche de maintenance, mise à jour de dépendance, CI, outillage"
|
||||
title: "CHORE: "
|
||||
labels: ["type:maintenance"]
|
||||
labels: ["chore"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Maintenance / Chore
|
||||
Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -45,4 +44,4 @@ body:
|
||||
label: "✅ Definition of Done"
|
||||
options:
|
||||
- label: "Tâche réalisée + vérifiée"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
@@ -2,14 +2,13 @@
|
||||
name: "✨ Feature"
|
||||
about: "Nouvelle fonctionnalité ou implémentation manquante par rapport à la spécification"
|
||||
title: "FEAT: "
|
||||
labels: ["type:feature"]
|
||||
labels: ["feature"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Feature — à remplir avant de commencer
|
||||
> Décrire le résultat attendu à partir de la documentation produit actuelle pertinente; les documents marqués historiques ne décrivent pas nécessairement le comportement livré.
|
||||
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
|
||||
> Source de vérité : `docs/MASTER_SPECIFICATION.md` (v2.0). Citer les numéros de partie/phase/étape.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -76,4 +75,5 @@ body:
|
||||
- label: "Code implémenté + tests verts (`make test`)"
|
||||
- label: "Migration EF ajoutée si le schéma change"
|
||||
- label: "Documentation/readme mis à jour si pertinent"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
@@ -2,13 +2,12 @@
|
||||
name: "🧹 Dette technique"
|
||||
about: "Dette technique, obsolescence, drift documentation, amélioration de code"
|
||||
title: "TECH: "
|
||||
labels: ["type:maintenance"]
|
||||
labels: ["tech-debt"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Dette technique — à remplir avant de commencer
|
||||
Ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -54,4 +53,5 @@ body:
|
||||
label: "✅ Definition of Done"
|
||||
options:
|
||||
- label: "Correctif appliqué + vérifié"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
@@ -1,33 +1,24 @@
|
||||
## Résultat et périmètre
|
||||
## Problème et résultat
|
||||
|
||||
<!-- Décrire le besoin, le résultat et les critères de l'issue couverts par cette PR. -->
|
||||
<!-- Décrire le déclencheur, le comportement corrigé et le périmètre. -->
|
||||
|
||||
Refs #
|
||||
|
||||
## Vérification
|
||||
|
||||
<!-- Commandes, preuves observées, limites et SHA du commit vérifié. Pour un diff Markdown-only, noter les contrôles de diff/liens; ne pas lancer de build ou de stack applicative sans raison. -->
|
||||
<!-- Liens des runs Gitea, suites exécutées, résultats et item actualisé dans todo.md. -->
|
||||
|
||||
- [ ] Issue Gitea liée et critères satisfaits/restants précisés
|
||||
- [ ] Contrôles pertinents exécutés; commandes et résultats indiqués
|
||||
- [ ] Recette Compose indépendante indiquée lorsqu'elle est requise, avec preuves de nettoyage
|
||||
- [ ] Limites et validations externes non réalisées explicitement documentées
|
||||
- [ ] Aucun secret dans le diff, les logs ou les artefacts
|
||||
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
|
||||
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
|
||||
- [ ] Limites et tests non exécutés explicitement documentés
|
||||
- [ ] Aucun secret dans les logs/artefacts
|
||||
|
||||
## Évaluation de release
|
||||
## Livraison
|
||||
|
||||
<!-- Appliquer la skill globale release-assessment et la politique de version Heimdall. -->
|
||||
<!-- Voir docs/gitea-builds.md. Pas de merge/déploiement implicite. -->
|
||||
|
||||
Release assessment: <none|patch|minor|major> — <rationale>
|
||||
- [ ] 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
|
||||
|
||||
<!-- Remplacer les deux placeholders. Pour une release, conserver le format exact et expliquer l'impact. -->
|
||||
|
||||
## Livraison Heimdall
|
||||
|
||||
<!-- Voir docs/gitea-builds.md si la PR touche CI, publication ou assets de release. -->
|
||||
|
||||
- [ ] Compatibilité contrats/migrations/configuration revue si concernée
|
||||
- [ ] Si le graphe d'image change : images affectées construites/scannées; publication Docker Hub observée après merge
|
||||
- [ ] Si les assets changent : noms, SHA-256/signature et format de release documentés; aucun claim externe sans run réel
|
||||
|
||||
SonarQube, runner, matériel, registre, site et stockage distant ne sont considérés validés que si une preuve réelle est jointe. Aucun merge ou déploiement n'est implicite.
|
||||
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.
|
||||
+117
-103
@@ -3,12 +3,24 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['*.*.*']
|
||||
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
|
||||
concurrency:
|
||||
group: heimdall-${{ gitea.ref }}
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
@@ -18,28 +30,52 @@ 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 changed projects and images
|
||||
- name: Detect changes that need validation
|
||||
id: filter
|
||||
env:
|
||||
PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ gitea.event.before }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
REF: ${{ gitea.ref }}
|
||||
run: python3 scripts/ci/change_scope.py
|
||||
IS_RELEASE_TAG: ${{ startsWith(gitea.ref, 'refs/tags/v') }}
|
||||
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
|
||||
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"
|
||||
policy:
|
||||
name: CI policy
|
||||
if: always()
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image, publish]
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image, dockerhub_latest, publish]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
steps:
|
||||
- name: Require all applicable validation jobs to pass
|
||||
@@ -50,6 +86,7 @@ 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 }}
|
||||
@@ -63,52 +100,29 @@ 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
|
||||
push:refs/tags/*) test "$RELEASE_RESULT" = success ;;
|
||||
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
|
||||
;;
|
||||
push:refs/tags/v*)
|
||||
test "$RELEASE_RESULT" = success
|
||||
;;
|
||||
esac
|
||||
create_release_tag:
|
||||
name: Create version tag after successful main CI
|
||||
if: always() && gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' && needs.policy.result == 'success'
|
||||
needs: [policy]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
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 full history and version tags
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Create immutable release tag for merged PR
|
||||
env:
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 scripts/ci/auto-tag-release.py
|
||||
verify:
|
||||
name: Build and tests
|
||||
if: needs.changes.outputs.run_validation == 'true'
|
||||
needs: [changes]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine@sha256:b0f9560a2de083e2cc7382e75f808c7381a32852a7ec49117deedb300e552b24
|
||||
@@ -154,16 +168,15 @@ jobs:
|
||||
run: |
|
||||
python3 -m unittest discover -s scripts/ci -p 'test_*.py'
|
||||
python3 scripts/ci/check-efcore-usage.py
|
||||
- name: Validate Compose and restore .NET solution
|
||||
- name: Validate Compose and build .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
|
||||
@@ -182,6 +195,8 @@ 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
|
||||
@@ -192,11 +207,11 @@ jobs:
|
||||
fi
|
||||
server_image:
|
||||
name: Build and scan server image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_server == 'true'
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -217,17 +232,14 @@ 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.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
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()
|
||||
@@ -237,11 +249,11 @@ jobs:
|
||||
fi
|
||||
agent_image:
|
||||
name: Build and scan agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent == 'true'
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -262,17 +274,14 @@ 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.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
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()
|
||||
@@ -282,11 +291,11 @@ jobs:
|
||||
fi
|
||||
agent_gpu_image:
|
||||
name: Build and scan NVIDIA Agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent_gpu == 'true'
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -307,18 +316,44 @@ 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: Push immutable NVIDIA Agent image to Docker Hub
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
- 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: Move latest tags after both image scans pass
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh agent-gpu
|
||||
run: bash scripts/ci/push-images.sh latest
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
@@ -326,15 +361,14 @@ jobs:
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
publish:
|
||||
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]
|
||||
name: Publish versioned release
|
||||
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/v')
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
contents: read
|
||||
actions: read
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
@@ -353,42 +387,22 @@ jobs:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- run: bash scripts/ci/bootstrap.sh
|
||||
- name: Build versioned installer and Agent archives
|
||||
- name: Require a release from main history
|
||||
run: git merge-base --is-ancestor HEAD origin/main
|
||||
- name: Rebuild release archives from verified commit
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_RUN_ID: ${{ gitea.run_id }}
|
||||
run: bash scripts/ci/package.sh
|
||||
- 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.GITEA_TOKEN }}
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
- name: Publish signed release assets
|
||||
- name: Publish immutable images and draft release
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
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
|
||||
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||
run: bash scripts/ci/publish.sh
|
||||
- name: Reclaim build storage after release
|
||||
if: always()
|
||||
run: bash scripts/ci/cleanup-docker.sh after
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
image: renovate/renovate:44.133.0
|
||||
env:
|
||||
RENOVATE_PLATFORM: gitea
|
||||
RENOVATE_ENDPOINT: ${{ vars.FORGEJO_API_ENDPOINT }}
|
||||
RENOVATE_ENDPOINT: ${{ vars.GITEA_API_ENDPOINT }}
|
||||
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
||||
RENOVATE_ONBOARDING: 'false'
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Heimdall contributor rules
|
||||
|
||||
- For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance.
|
||||
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, project names, and unique tags for locally built acceptance images; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes/networks are gone, then remove and verify absence of only the exact image tags built by that recipe. Keep shared upstream/base images. Never use broad image pruning. Do not skip this recipe silently when Docker is unavailable.
|
||||
- Use Gitea project issues as the sole backlog and work-status source. Before changing code, find or create the focused issue, keep its acceptance evidence current, and link the issue from the PR (`Closes #N` only when all criteria are complete; otherwise `Refs #N`). Follow [skills/gitea-ticket-workflow/SKILL.md](skills/gitea-ticket-workflow/SKILL.md). Do not create or maintain a `todo.md` backlog.
|
||||
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
|
||||
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
|
||||
- Use EF Core for production database reads and writes. Do not use direct ADO.NET or provider commands in production code; provider-specific EF SQL is allowed only for capabilities LINQ cannot express, with a nearby rationale and a test. The CI persistence policy enforces this boundary. Preserve PostgreSQL behavior, add migrations for schema changes, and verify translation, concurrency, and deletion semantics with relational tests. Never reuse a `DbContext` across concurrent operations.
|
||||
- Keep tenant/site and camera authorization checks at API and application boundaries. Do not log credentials, RTSP URLs, embeddings, or raw tokens.
|
||||
- CI jobs run only on `[ubuntu-latest, build-agent]`. Keep `runner-aaja` outside that label. Never use release credentials in pull request jobs.
|
||||
- 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 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).
|
||||
For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md).
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
# Server/PWA: restore the complete project graph from locked dependencies.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
@@ -8,7 +8,7 @@ COPY install/ ./install/
|
||||
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
WORKDIR /app
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
|
||||
+4
-11
@@ -1,6 +1,6 @@
|
||||
# CPU agent: use glibc for ONNX native dependencies. GPU variants need a
|
||||
# separately validated .NET/native-library runtime and are not published here.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
ARG TARGET_RUNTIME=cpu
|
||||
@@ -10,21 +10,14 @@ COPY src/ ./src/
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
WORKDIR /app
|
||||
ARG DOCKER_CLI_VERSION=29.9.3
|
||||
ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
|
||||
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl ffmpeg wget libgomp1 tzdata \
|
||||
&& curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
|
||||
"https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \
|
||||
&& echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \
|
||||
&& tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \
|
||||
&& install -m 0755 /tmp/docker/docker /usr/local/bin/docker \
|
||||
&& rm -rf /tmp/docker /tmp/docker-cli.tgz /var/lib/apt/lists/*
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
|
||||
ENV ASPNETCORE_URLS=http://127.0.0.1:8080
|
||||
COPY --from=build /out/ ./
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Optional NVIDIA Agent image. ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9.
|
||||
# NVIDIA amd64 runtime image digest is pinned; it includes CUDA 12.8.1/cuDNN 9.8.0.87.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
@@ -9,12 +9,10 @@ RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRunti
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out \
|
||||
-p:HeimdallOnnxRuntime=GPU -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e AS dotnet-runtime
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee AS dotnet-runtime
|
||||
|
||||
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime
|
||||
WORKDIR /app
|
||||
ARG DOCKER_CLI_VERSION=29.9.3
|
||||
ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973
|
||||
ENV DOTNET_ROOT=/usr/share/dotnet \
|
||||
PATH=/usr/share/dotnet:$PATH \
|
||||
LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \
|
||||
@@ -26,13 +24,8 @@ RUN apt-get update -qq \
|
||||
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
|
||||
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \
|
||||
&& curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
|
||||
"https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \
|
||||
&& echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \
|
||||
&& tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \
|
||||
&& install -m 0755 /tmp/docker/docker /usr/local/bin/docker \
|
||||
&& rm -rf /tmp/docker /tmp/docker-cli.tgz /var/lib/apt/lists/* \
|
||||
ca-certificates ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
|
||||
COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/
|
||||
COPY --from=build /out/ ./
|
||||
|
||||
+4
-67
@@ -6,17 +6,11 @@ Sauvegarde automatisée de PostgreSQL (quotidien) et RustFS/S3 (hebdomadaire) av
|
||||
|
||||
| Composant | Fréquence | Script | Rétention |
|
||||
|---|---|---|---|
|
||||
| PostgreSQL `pg_dump` | Quotidien 02:00, heure du conteneur | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
|
||||
| Miroir RustFS/S3 (`aws s3 sync` dans le Compose livré) | Dimanche 03:00, heure du conteneur | `docker/scripts/backup-rustfs.sh` | 12 semaines |
|
||||
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15, heure du conteneur | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
|
||||
| PostgreSQL `pg_dump` | Quotidien 02:00 UTC | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
|
||||
| RustFS `mc mirror` | Hebdo dimanche 03:00 UTC | `docker/scripts/backup-rustfs.sh` | 12 semaines |
|
||||
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15 UTC | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
|
||||
| Test de restauration | Manuel / CI | `docker/scripts/test-backup-restore.sh` | — |
|
||||
|
||||
Le Compose backup définit `TZ` à `Europe/Paris` par défaut; ces horaires
|
||||
s'appliquent donc à l'heure locale de Paris, avec les changements saisonniers.
|
||||
Définir `TZ` avec un identifiant de fuseau IANA pour choisir un autre fuseau.
|
||||
Les scripts horodatent leurs archives en UTC; l'heure du nom d'archive peut donc
|
||||
différer de l'heure locale d'exécution.
|
||||
|
||||
## Activation
|
||||
|
||||
### Compose facultatif séparé
|
||||
@@ -31,10 +25,6 @@ rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
|
||||
avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils
|
||||
de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload
|
||||
RustFS/S3 est facultatif.
|
||||
Le service fourni installe AWS CLI, pas MinIO Client : `backup-rustfs.sh`
|
||||
utilise donc `aws s3 sync` avec l'endpoint configuré. Le script conserve un
|
||||
chemin de compatibilité `mc mirror` si `mc` est déjà présent dans une image ou
|
||||
un environnement personnalisé; il ne télécharge ni n'installe ce binaire.
|
||||
Le service monte aussi le volume `heimdall_data` du Compose Central : les
|
||||
objets stockés localement et les clés Data Protection sont archivés ensemble.
|
||||
Le nom par défaut est `docker_heimdall_data`, pour le projet Compose du dépôt.
|
||||
@@ -60,7 +50,6 @@ configurés. Garder l’application Central arrêtée pendant une restauration.
|
||||
| `BACKUP_RETENTION_DAYS` | `30` | Rétention jours (PostgreSQL) |
|
||||
| `BACKUP_RETENTION_WEEKS` | `12` | Rétention semaines (RustFS) |
|
||||
| `BACKUP_LOCAL_DIR` | `/backups` | Répertoire local dans le conteneur |
|
||||
| `TZ` | `Europe/Paris` | Fuseau utilisé par le planning cron du conteneur |
|
||||
|
||||
## Structure des backups
|
||||
|
||||
@@ -161,58 +150,6 @@ ne sont pas supprimés. L’archive contient le répertoire `dp-keys`, dont
|
||||
`dp-cert.pfx` protège les clés Data Protection. Protéger les sauvegardes locales
|
||||
et S3 comme des données sensibles.
|
||||
|
||||
### Conservation et rotation des clés Data Protection
|
||||
|
||||
Le volume Central contient le trousseau XML Data Protection et `dp-cert.pfx`,
|
||||
qui protège ces clés au repos. L’archive de données protégées doit conserver
|
||||
l’ensemble de `dp-keys`; restaurer PostgreSQL sans ce répertoire peut laisser
|
||||
les identifiants et autres charges utiles protégées impossibles à relire.
|
||||
|
||||
- Arrêter Central avant la restauration et restaurer l’archive protégée complète
|
||||
dans le volume correspondant. Ne remplacer ni supprimer `dp-cert.pfx` ou des
|
||||
fichiers de clés indépendamment.
|
||||
- Garder les archives comme des secrets : `dp-cert.pfx` contient la clé privée
|
||||
qui déchiffre le trousseau. Le script crée l’archive locale avec le mode
|
||||
`0600`; contrôler aussi les permissions et l’accès du bucket S3.
|
||||
- Le framework fait évoluer automatiquement le trousseau selon sa politique de
|
||||
durée de vie. Les clés expirées restent nécessaires pour lire les données
|
||||
protégées avec ces clés; ne pas purger les anciennes clés au seul motif
|
||||
qu’elles ont expiré.
|
||||
- Le certificat de protection `dp-cert.pfx` n’a pas de procédure de rotation
|
||||
manuelle validée dans Heimdall. Ne pas le remplacer lors d’une restauration.
|
||||
Toute rotation planifiée doit faire l’objet d’une procédure séparée et d’un
|
||||
essai sur copie isolée, avec vérification de lecture des anciennes et nouvelles
|
||||
charges utiles avant suppression de la clé précédente.
|
||||
|
||||
Voir [la gestion des clés Data Protection dans ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management)
|
||||
pour le cycle des clés; supprimer une clé qui protège encore des données rend
|
||||
ces données définitivement illisibles.
|
||||
|
||||
### Mesure RPO/RTO
|
||||
|
||||
Les horaires configurés ne constituent pas une mesure de RPO. Les sauvegardes
|
||||
PostgreSQL et du volume protégé sont prises séparément, et le miroir RustFS suit
|
||||
un autre intervalle; Heimdall ne fournit pas de point de restauration atomique.
|
||||
Le responsable d’exploitation doit définir les objectifs visés et le scénario
|
||||
avant un exercice réel.
|
||||
|
||||
Pour chaque exercice autorisé, consigner sans données personnelles :
|
||||
|
||||
1. La date UTC du changement connu le plus récent dans chaque stockage, la date
|
||||
de la panne simulée, et la date du changement le plus récent réellement
|
||||
restauré. Calculer le RPO séparément pour PostgreSQL, objets locaux/S3 et
|
||||
clés protégées; retenir le pire résultat pour le service.
|
||||
2. L’heure de début de la restauration, ses jalons (base, objets, démarrage de
|
||||
Central) et l’heure où les vérifications post-restauration réussissent. Cette
|
||||
durée est le RTO mesuré pour cet essai, pas un engagement universel.
|
||||
3. Versions des scripts/images, tailles et nombres d’objets, hôte/CPU/mémoire,
|
||||
stockage et réseau utilisés, étapes manuelles, erreurs et résultat final.
|
||||
Répéter l’exercice complet au moins deux fois avant de fixer une cible.
|
||||
|
||||
La recette synthétique de `test-backup-restore.sh` ne comprend pas le démarrage
|
||||
de Central, une connexion utilisateur ni un backend S3; son temps d’exécution
|
||||
ne doit jamais être présenté comme un RTO de production.
|
||||
|
||||
## Test de restauration (runbook)
|
||||
|
||||
### Prérequis
|
||||
@@ -332,6 +269,6 @@ docker compose -f docker/docker-compose.backup.yml exec backup ls -la /var/log/b
|
||||
|
||||
- **pg_dump --format=custom** nécessite `pg_restore` pour la restauration (pas `psql`)
|
||||
- Le conteneur backup utilise `postgres:17-alpine` pour avoir `pg_dump` et `pg_restore`
|
||||
- Le Compose livré installe `aws-cli`, Bash et GNU coreutils; il n'installe pas MinIO Client. Le script de miroir préfère `mc` s'il est déjà fourni, sinon utilise AWS CLI `s3 sync`.
|
||||
- mc (MinIO Client) est installé au démarrage du conteneur (curl depuis dl.min.io)
|
||||
- Si S3 n'est pas configuré, le backup est local uniquement (volume Docker)
|
||||
- La restauration DROP la base existante — toujours vérifier le `--dry-run` d'abord
|
||||
@@ -10,8 +10,6 @@ services:
|
||||
dockerfile: docker/Dockerfile.agent.gpu
|
||||
environment:
|
||||
Agent__InferenceExecutionProvider: CUDA
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
|
||||
@@ -7,8 +7,6 @@ services:
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
restart: unless-stopped
|
||||
user: "1654:1654"
|
||||
group_add:
|
||||
- "${DOCKER_GID:-0}"
|
||||
network_mode: host
|
||||
environment:
|
||||
ASPNETCORE_URLS: http://127.0.0.1:8081
|
||||
@@ -21,7 +19,6 @@ services:
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
|
||||
interval: 30s
|
||||
|
||||
@@ -1,45 +1,18 @@
|
||||
# Optional TURN relay for live view; Central uses its URL and shared secret to
|
||||
# issue short-lived browser credentials. Public reachability needs deployment
|
||||
# firewall/NAT validation.
|
||||
# Optional TURN relay, used only by a future/externally integrated WebRTC setup.
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
pull_policy: always
|
||||
# Local Compose secrets are read-only bind mounts and preserve the
|
||||
# installer's 0600 owner-only permissions. Read the mounted file as a
|
||||
# short-lived root initializer, write a private config into tmpfs, then
|
||||
# run turnserver as nobody. The upstream binary does not exec with a
|
||||
# reduced capability set; no-new-privileges still prevents elevation.
|
||||
user: "0:0"
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
ports:
|
||||
- "${COTURN_PORT:-3478}:3478/tcp"
|
||||
- "${COTURN_PORT:-3478}:3478/udp"
|
||||
- "${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}:${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}/udp"
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n'
|
||||
"$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}"
|
||||
"${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}"
|
||||
> /run/coturn/turnserver.conf;
|
||||
printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf;
|
||||
if [ -n "$$COTURN_EXTERNAL_IP" ]; then
|
||||
printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf;
|
||||
fi;
|
||||
chown 65534:65534 /run/coturn /run/coturn/turnserver.conf;
|
||||
exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody
|
||||
environment:
|
||||
COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-}
|
||||
command: >
|
||||
-n --use-auth-secret
|
||||
--static-auth-secret-file=/run/secrets/coturn_secret
|
||||
--realm=${COTURN_REALM:-heimdall.local}
|
||||
--fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout
|
||||
network_mode: host
|
||||
secrets:
|
||||
- coturn_secret
|
||||
restart: unless-stopped
|
||||
|
||||
secrets:
|
||||
coturn_secret:
|
||||
file: ./optional/secrets/coturn_secret
|
||||
file: ./secrets/coturn_secret
|
||||
@@ -5,34 +5,6 @@ services:
|
||||
image: rustfs/rustfs:latest
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
# Compose file secrets are read-only bind mounts locally. The installer
|
||||
# deliberately creates them mode 0600, owned by root; RustFS runs as UID
|
||||
# 10001 and cannot read that source directly. A small root init copies the
|
||||
# files into tmpfs, then drops privileges before starting the server.
|
||||
user: "0:0"
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
- DAC_OVERRIDE
|
||||
- SETGID
|
||||
- SETUID
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
- /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key;
|
||||
cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key;
|
||||
chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key;
|
||||
exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs
|
||||
ports:
|
||||
- "${RUSTFS_API_PORT:-9000}:9000"
|
||||
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
|
||||
@@ -41,8 +13,8 @@ services:
|
||||
RUSTFS_ADDRESS: 0.0.0.0:9000
|
||||
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
|
||||
RUSTFS_CONSOLE_ENABLE: "true"
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key
|
||||
RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
|
||||
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
|
||||
secrets:
|
||||
- rustfs_access_key
|
||||
- rustfs_secret_key
|
||||
@@ -58,9 +30,9 @@ volumes:
|
||||
|
||||
secrets:
|
||||
rustfs_access_key:
|
||||
file: ./optional/secrets/rustfs_access_key
|
||||
file: ./secrets/rustfs_access_key
|
||||
rustfs_secret_key:
|
||||
file: ./optional/secrets/rustfs_secret_key
|
||||
file: ./secrets/rustfs_secret_key
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
|
||||
+134
-137
@@ -1,9 +1,8 @@
|
||||
# Heimdall — Master Specification Technique
|
||||
|
||||
> **Version :** 2.0 | **Date :** 2026-07-16
|
||||
> **Stack de la baseline :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents)
|
||||
> **Statut :** baseline de conception historique datée du 2026-07-16; ce document n'est pas la source de vérité sur l'implémentation livrée.
|
||||
> **État livré :** voir [spécifications actuelles](specs.md), [hubs SignalR mappés](signalr-usage.md), [déploiement Compose et live view](docker-compose.md).
|
||||
> **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC
|
||||
> **Status :** SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts
|
||||
>
|
||||
> **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`,
|
||||
> `auth-roles.md`, `pwa.md`, `hangfire-usage.md`, `ui-pages.md`
|
||||
@@ -17,7 +16,7 @@
|
||||
|
||||
### D1 — Accès mobile via la PWA du serveur
|
||||
|
||||
Le client natif est retiré. L’application Blazor est la cible mobile installable. Le socle livré conserve Interactive Server et fournit une page statique hors connexion; Web Push et la consultation métier hors ligne restent des objectifs non implémentés. Voir [l’état livré et l’audit PWA](pwa.md).
|
||||
Le client natif est retiré. L’application Blazor devient la cible mobile installable ; la première version conserve Interactive Server avec une page hors connexion et Web Push. La consultation métier hors ligne nécessitera une couche cliente autonome. Voir [l’audit PWA](pwa.md).
|
||||
|
||||
### D2 — Topologie : API + Web fusionnés (1 conteneur)
|
||||
|
||||
@@ -28,29 +27,29 @@ Le client natif est retiré. L’application Blazor est la cible mobile installa
|
||||
|
||||
**Exception** : En scaling horizontal, on peut séparer les conteneurs avec un Redis backplane.
|
||||
|
||||
### D3 — TURN selon la connectivité du réseau (ancienne décision obligatoire retirée)
|
||||
### D3 — TURN/Coturn obligatoire (pas optionnel)
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **TURN est une option de déploiement** | Les connexions ICE directes peuvent suffire; déployer et configurer TURN lorsque le NAT ou le pare-feu empêche la connectivité directe. |
|
||||
| Pas de TURN universellement requis | La présence du Compose Coturn ne prouve ni sa configuration Central, ni son accessibilité publique; ces vérifications restent propres au déploiement. |
|
||||
| **Coturn REQUIS** | CGNAT (4G/5G), pare-feu entreprises, Starlink — toute installation derrière NAT |
|
||||
| Optionnel rejeté | WebRTC échoue silencieusement sans TURN → support impossible |
|
||||
|
||||
### D4 — Agents : Installation Docker uniquement
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **Docker uniquement** | FFmpeg et ONNX Runtime ont des dépendances natives et des besoins de cycle de vie qu'il faut distribuer avec l'Agent |
|
||||
| **Docker uniquement** | FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes |
|
||||
| Installation manuelle rejetée | Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation |
|
||||
|
||||
**Conséquence** : L'Agent est distribué exclusivement via `eltruncho/heimdall-agent` sur Docker Hub.
|
||||
Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par `docker pull` + redémarrage.
|
||||
|
||||
### D6 — Chemin live-view livré : relay Agent vers MediaMTX, lecture WHEP/WebRTC
|
||||
### D6 — SFU (MediaMTX) différé à v2
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **L'Agent publie le flux RTSP(S) vers MediaMTX; le navigateur lit par WHEP/WebRTC** | Ce chemin est implémenté dans le relay Agent et l'API/session Central. Il ne repose pas sur une PeerConnection SIPSorcery dans l'Agent. |
|
||||
| La capacité et la connectivité restent à valider par environnement | Les limites de sessions, codecs, NAT/TURN et latence dépendent du déploiement; voir `docs/docker-compose.md` et l'issue #161 pour la validation externe. |
|
||||
| **P2P uniquement en v1** (1 viewer/caméra max) | Complexité de transition P2P→SFU sous-estimée |
|
||||
| SFU repoussé à v2 | Renégociation SDP pendant flux actif = perte d'images, protocole non spécifié |
|
||||
|
||||
### D7 — CQRS avec MediatR in-process (pas de message broker)
|
||||
|
||||
@@ -74,11 +73,6 @@ Contrôleur → IMediator.Send(Command/Query) → [ValidationBehavior]
|
||||
|
||||
## PARTIE 1 : Architecture Globale
|
||||
|
||||
> **Schémas historiques (2026-07-16), non descriptifs du runtime actuel.** Les
|
||||
> schémas de conteneurs et les diagrammes détaillés ci-dessous gardent la
|
||||
> proposition d'origine; pour les composants livrés, suivre les liens d'état
|
||||
> courant dans l'en-tête.
|
||||
|
||||
### 1.1 Vision
|
||||
|
||||
Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, multi-site.
|
||||
@@ -91,15 +85,11 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
|
||||
| **Privacy First** | IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud |
|
||||
| **Multi-site** | 1 serveur Central + N Agents distants (sites physiques séparés) |
|
||||
| **Clean Architecture / CQRS** | Domain → Application → Infrastructure → Api/Web |
|
||||
| **Temps réel** | SignalR (5 hubs mappés : Config, Events, Monitoring, Notifications, Admin); vidéo en direct : Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC, sans seuil de latence revendiqué |
|
||||
| **Temps réel** | SignalR (5 hubs), WebRTC P2P < 500ms (LAN) |
|
||||
| **IA locale** | YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker |
|
||||
|
||||
### 1.3 Architecture Logique
|
||||
|
||||
> **Diagramme de conception historique (2026-07-16), pas le chemin vidéo livré.**
|
||||
> Il représente l'ancienne proposition SIPSorcery/P2P. Le chemin live actuel est
|
||||
> résumé en D6 et détaillé dans le [guide live-view](docker-compose.md).
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ HEIMDALL CENTRAL (1 container) │
|
||||
@@ -136,10 +126,6 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
|
||||
|
||||
### 1.4 Conteneurs Docker
|
||||
|
||||
> **Exemple de topologie historique, non équivalent aux Compose actuels.**
|
||||
> Coturn n'est pas obligatoire pour chaque installation; voir
|
||||
> [les services Compose maintenus](docker-compose.md).
|
||||
|
||||
```yaml
|
||||
services:
|
||||
heimdall-central: # Api + Web + Workers fusionnés (1 conteneur)
|
||||
@@ -158,11 +144,6 @@ services:
|
||||
|
||||
### 2.1 Définitions
|
||||
|
||||
> **Schéma de conception historique (2026-07-16).** Les champs de
|
||||
> notification ci-dessous, dont `GotifyEnabled` et `NotificationTemplate`, ne
|
||||
> sont pas l’inventaire du modèle livré. Voir le [guide actuel des
|
||||
> notifications](notifications.md) et le [modèle d’identité courant](auth-roles.md).
|
||||
|
||||
```
|
||||
Site Agent Camera
|
||||
├── Id (Guid) PK ├── Id (Guid) PK ├── Id (Guid) PK
|
||||
@@ -307,15 +288,12 @@ CREATE INDEX idx_license_plate ON license_plates USING GIN
|
||||
|
||||
### 3.1 Problème : Objets Stationnaires
|
||||
|
||||
> **Estimation théorique historique**, pas une mesure ni une description des
|
||||
> canaux livrés.
|
||||
|
||||
**Sans dédoublonnage** : une personne immobile 10 minutes génère :
|
||||
- 3000 snapshots (200ms × 600s)
|
||||
- 3000 inférences YOLOv8 nano
|
||||
- 3000 analyses IA (ONNX local ou via broker)
|
||||
- 3000 événements en base
|
||||
- 3000 notifications dans ce scénario théorique
|
||||
- 3000 notifications (email + gotify + in-app)
|
||||
|
||||
**Solution** : Architecture de dédoublonnage à 4 niveaux.
|
||||
|
||||
@@ -462,10 +440,6 @@ public class CameraDetectionProfile
|
||||
|
||||
## PARTIE 4 : Authentification, Rôles et Sécurité
|
||||
|
||||
> **Conception historique.** Les exemples ci-dessous incluent un `StreamingHub`
|
||||
> proposé qui n'est pas mappé. Les hubs et routes actuels sont listés dans
|
||||
> [le guide SignalR](signalr-usage.md).
|
||||
|
||||
### 4.1 Architecture Auth
|
||||
|
||||
```
|
||||
@@ -597,10 +571,7 @@ Agent se connecte à SignalR avec API Key
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 5 : Conception SignalR historique — 5 hubs projetés
|
||||
|
||||
> Cette proposition datée inclut `/hubs/streaming`, qui n'est pas livré. Voir
|
||||
> [les cinq routes actuellement mappées](signalr-usage.md).
|
||||
## PARTIE 5 : SignalR — 5 Hubs Détaillés
|
||||
|
||||
### 5.1 Hubs
|
||||
|
||||
@@ -677,12 +648,7 @@ builder.Services.AddSignalR()
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 6 : Conception historique P2P/SIPSorcery — remplacée pour le live view
|
||||
|
||||
> Les sections ci-dessous conservent l'ancienne proposition P2P/SIPSorcery et
|
||||
> ses objectifs de latence, pas le comportement livré. Le chemin actuel est
|
||||
> Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC; voir le
|
||||
> [guide Compose](docker-compose.md).
|
||||
## PARTIE 6 : WebRTC et Pipeline Vidéo
|
||||
|
||||
### 6.1 Stack
|
||||
|
||||
@@ -849,10 +815,6 @@ await storageProvider.DeleteBatchAsync(storagePaths, ct);
|
||||
|
||||
### 7.4 Hangfire Configuration
|
||||
|
||||
> **Exemple de queues historique.** Les queues `email`/`gotify` du bloc
|
||||
> suivant ne décrivent pas les jobs actuels; voir le [guide Hangfire](hangfire-usage.md)
|
||||
> et le [guide des notifications livrées](notifications.md).
|
||||
|
||||
```csharp
|
||||
// Central — with schema isolation
|
||||
builder.Services.AddHangfire(config =>
|
||||
@@ -864,7 +826,7 @@ builder.Services.AddHangfire(config =>
|
||||
});
|
||||
});
|
||||
|
||||
// Queue isolation (conception historique)
|
||||
// Queue isolation
|
||||
[Queue("email")]
|
||||
public class SendNotificationEmailJob { ... }
|
||||
|
||||
@@ -884,10 +846,6 @@ builder.Services.AddHangfireServer(options =>
|
||||
|
||||
### 7.5 Jobs Hangfire — Tous
|
||||
|
||||
> **Inventaire historique (2026-07-16), pas la liste des jobs actuellement
|
||||
> enregistrés.** Consulter le [guide Hangfire actuel](hangfire-usage.md) pour
|
||||
> les jobs et queues livrés.
|
||||
|
||||
**Central (PostgreSQL)**
|
||||
|
||||
| Job | Schedule | Queue | Description |
|
||||
@@ -914,19 +872,66 @@ builder.Services.AddHangfireServer(options =>
|
||||
|
||||
## PARTIE 8 : Notifications
|
||||
|
||||
> **Conception historique non livrée.** Les canaux Gotify, l’éditeur de
|
||||
> templates Scriban et les événements de ces tableaux ne décrivent pas le
|
||||
> produit actuel. Pour les canaux, réglages et jobs livrés, voir
|
||||
> [Notifications](notifications.md).
|
||||
### 8.1 Canaux
|
||||
|
||||
Le détail historique de cette partie a été retiré pour éviter de confondre
|
||||
les propositions de 2026-07-16 avec les fonctions livrées.
|
||||
| Canal | Usage | Priorité | Queue Hangfire |
|
||||
|---|---|---|---|
|
||||
| **Email (SMTP)** | Importants + résumés | P0 | `email` |
|
||||
| **Gotify** | Alertes temps réel | P0 | `gotify` |
|
||||
| **In-app (SignalR)** | Badge UI | P0 | Direct (pas Hangfire) |
|
||||
|
||||
### 8.2 Types d'Événements Notifiables
|
||||
|
||||
| EventType | Email | Gotify | In-App | Cooldown (secondes) |
|
||||
|---|---|---|---|---|
|
||||
| `PersonDetected` | ✅ | ✅ | ✅ | 30 |
|
||||
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | 300 (5 min) |
|
||||
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | 30 |
|
||||
| `VehicleDetected` | ✅ | ✅ | ✅ | 60 |
|
||||
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | 60 |
|
||||
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | 10 |
|
||||
| `CameraOffline` | ✅ | ✅ | ✅ | 600 (10 min) |
|
||||
| `CameraOnline` | 🟡 | 🟡 | ✅ | 600 |
|
||||
| `DailySummary` | ✅ | ❌ | ❌ | N/A |
|
||||
| `WeeklySummary` | ✅ | ❌ | ❌ | N/A |
|
||||
|
||||
### 8.3 Rate Limiting Notifications
|
||||
|
||||
```csharp
|
||||
public class NotificationRateLimiter
|
||||
{
|
||||
private readonly IMemoryCache _cache;
|
||||
|
||||
public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId)
|
||||
{
|
||||
var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}";
|
||||
var count = _cache.GetOrCreate(key, entry =>
|
||||
{
|
||||
entry.SlidingExpiration = TimeSpan.FromMinutes(1);
|
||||
return 0;
|
||||
});
|
||||
|
||||
if (count >= 20) return false; // Max 20 events/min/camera/type
|
||||
|
||||
_cache.Set(key, count + 1, TimeSpan.FromMinutes(1));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8.4 Templates
|
||||
|
||||
- Moteur : Scriban (Markdown → HTML pour email)
|
||||
- Stockés en DB (table `NotificationTemplate`)
|
||||
- Éditables depuis l'UI Admin
|
||||
- Fallback : fr → en → template par défaut hardcodé
|
||||
- Signature : `[Heimdall]` dans le sujet
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 9 : Application web installable (PWA)
|
||||
|
||||
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. À ce jour, le manifeste, le worker borné et la page statique hors connexion sont livrés; Web Push et la consultation métier hors ligne restent à implémenter. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans le socle actuel.
|
||||
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans la première étape.
|
||||
|
||||
Spécification actuelle : [audit et plan PWA](pwa.md).
|
||||
|
||||
@@ -934,15 +939,8 @@ Spécification actuelle : [audit et plan PWA](pwa.md).
|
||||
|
||||
## PARTIE 10 : Plan d'Implémentation Optimisé
|
||||
|
||||
> **Plan historique daté du 2026-07-16, pas un état d'avancement.** Les phases,
|
||||
> livrables et scénarios vidéo ci-dessous décrivent la proposition d'origine;
|
||||
> consulter les guides actuels liés en tête avant d'inférer ce qui est livré.
|
||||
|
||||
### 10.1 7 Étapes Incrémentales
|
||||
|
||||
> Chaque phase et son encadré « Fonctionnel à la fin » ci-dessous décrivent le
|
||||
> plan du 2026-07-16, pas un état vérifié de l'implémentation actuelle.
|
||||
|
||||
Le plan est structuré en **7 étapes**, chacune produisant un logiciel fonctionnel et testable.
|
||||
|
||||
| Étape | Phases | Nom | Livrable |
|
||||
@@ -1013,9 +1011,6 @@ Phase 3 — CI/CD
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 4 — Domain Model (entités multi-site uniquement)
|
||||
> **Inventaire du plan historique.** `NotificationTemplate` existe comme
|
||||
> entité, mais cette entrée ne décrit pas un éditeur livré ni une intégration
|
||||
> Gotify; voir le [guide des notifications actuelles](notifications.md).
|
||||
├── Entités CŒUR : Site, Agent (avec ApiKeyHash, ApiKeyPrefix)
|
||||
├── Entités AUTH : User, Role (Identity), UserSite, ApiKey, AuditLog
|
||||
├── Entités MÉTIER (définies mais migrations seules, pas de logique) :
|
||||
@@ -1395,10 +1390,6 @@ Phase 13 — API Caméras + ONVIF
|
||||
│ • Soft delete : caméra dans la corbeille, pas vraiment supprimée
|
||||
│ • Découverte ONVIF réseau : scan automatique des caméras
|
||||
|
||||
> **Phases 14 et 15 ci-dessous : plan historique, pas état de livraison.**
|
||||
> Le `StreamingHub` et le signaling SDP/ICE décrits ici ne sont pas mappés;
|
||||
> voir les [cinq routes SignalR actuelles](signalr-usage.md).
|
||||
|
||||
Phase 14 — SignalR Hubs (temps réel)
|
||||
├── 5 hubs : Events, Streaming, Monitoring, Notifications, Admin
|
||||
├── EventsHub :
|
||||
@@ -1457,9 +1448,6 @@ Phase 14 — SignalR Hubs (temps réel)
|
||||
│ • User voit UNIQUEMENT ses sites assignés
|
||||
│ • Le signaling WebRTC est prêt pour l'Étape 3
|
||||
|
||||
> **Scénarios de phase historiques, pas des contrats ou preuves d'exécution.**
|
||||
> Les exemples de `StreamingHub`, SDP/ICE, groupes et latence ne décrivent pas
|
||||
> les routes ni le transport vidéo livrés.
|
||||
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
ÉTAPE 3 — VIDÉO + IA
|
||||
@@ -1467,10 +1455,6 @@ Phase 14 — SignalR Hubs (temps réel)
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
Phase 15 — Agent Vidéo (capture + streaming)
|
||||
> **Scénario vidéo historique, non implémenté tel que décrit.** P2P SIPSorcery,
|
||||
> Coturn obligatoire et objectifs de latence ci-dessous ne sont pas des
|
||||
> comportements ni des mesures livrés. Le chemin actuel est décrit en D6.
|
||||
|
||||
├── FFmpeg capture (passthrough H264, zerolatency)
|
||||
│ ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0 \
|
||||
│ -i rtsp://... -g 1 -tune zerolatency \
|
||||
@@ -1726,14 +1710,68 @@ Phase 17 — API Events + Persons + Vehicles
|
||||
│ • Tout est filtré par site-scope (User voit ses sites)
|
||||
│ • Données accessibles via API pour l'UI (Étape 5)
|
||||
|
||||
> **Phase 18 — scénario historique (non état livré).** La conception initiale
|
||||
> Gotify/Scriban ci-dessous a été retirée; voir [l’état courant des
|
||||
> notifications](notifications.md).
|
||||
|
||||
Phase 18 — Notifications (historique)
|
||||
> Détails de cette proposition retirés : ils ne décrivent pas les services,
|
||||
> queues ni contrats actuellement livrés.
|
||||
|
||||
Phase 18 — Notifications
|
||||
├── SendNotificationEmailJob (SMTP, queue=email, retry 3x)
|
||||
├── SendNotificationGotifyJob (queue=gotify)
|
||||
├── NotificationRateLimiter (IMemoryCache, max 20 events/min/camera)
|
||||
├── DetectionCooldownService (cooldown par type d'événement)
|
||||
├── Scriban templates (DB + fallback hardcodé fr → en)
|
||||
├── Hiérarchie des notifications :
|
||||
│ ├── "PersonDetected" → Email + Gotify (si configuré)
|
||||
│ ├── "UnknownPerson" → Email + Gotify + In-app (badge rouge)
|
||||
│ ├── "VehicleDetected" → Email (si config) + Gotify
|
||||
│ ├── "CameraOffline" → Email + Gotify (alerte admin)
|
||||
│ └── "MotionDetected" → SILENCIEUX (in-app sans notif)
|
||||
├── Verify: notifications flows green
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ SCÉNARIO NOTIFICATION ──────────────────────────────────────┐
|
||||
│ │ │
|
||||
│ │ 1. Personne détectée devant la caméra "Entrée" │
|
||||
│ │ → Événement créé (Phase 16) │
|
||||
│ │ │
|
||||
│ │ 2. Central envoie SendNotificationJob à Hangfire │
|
||||
│ │ → Queue "email" : SendNotificationEmailJob │
|
||||
│ │ → Queue "gotify" : SendNotificationGotifyJob │
|
||||
│ │ │
|
||||
│ │ 3. SendNotificationEmailJob : │
|
||||
│ │ → Render template Scriban : "Personne détectée" │
|
||||
│ │ → Sujet : "[Heimdall] Personne détectée — Entrée" │
|
||||
│ │ → Corps : snapshot incluse (embed) + heure + lieu │
|
||||
│ │ → SMTP : envoi à tous les users configurés │
|
||||
│ │ │
|
||||
│ │ 4. SendNotificationGotifyJob : │
|
||||
│ │ → POST Gotify API : "Personne détectée - Entrée" │
|
||||
│ │ → Priorité : 5 (haute) │
|
||||
│ │ │
|
||||
│ │ 5. SignalR NotificationsHub envoie NewNotification │
|
||||
│ │ → Groupe "notif-{userId}" │
|
||||
│ │ → Badge dans l'UI : "3 notifications non lues" │
|
||||
│ │ │
|
||||
│ │ 6. RateLimiter : max 20 notifs/min/camera │
|
||||
│ │ → Si seuil atteint → pas de nouvelle notification │
|
||||
│ │ → Log "Rate limit atteint pour camera guid-cam-1" │
|
||||
│ │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ ┌─ CONFIGURER SES NOTIFICATIONS ───────────────────────────────┐
|
||||
│ │ PUT /api/auth/profile │
|
||||
│ │ { │
|
||||
│ │ "notificationConfig": { │
|
||||
│ │ "emailEnabled": true, │
|
||||
│ │ "gotifyEnabled": true, │
|
||||
│ │ "subscribedEvents": ["personDetected", "unknownPerson", │
|
||||
│ │ "vehicleDetected", "cameraOffline"],│
|
||||
│ │ "dailyDigest": true │
|
||||
│ │ } │
|
||||
│ │ } │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ • 3 canaux : Email, Gotify, In-app (SignalR)
|
||||
│ • Rate limiting : pas de spam même en rafale
|
||||
│ • Templates personnalisables par l'Admin
|
||||
│ • Chaque user choisit ses types d'événements
|
||||
|
||||
Phase 19 — Jobs Métier (retention, cleanup)
|
||||
├── RetentionCheckJob (quotidien 3h, queue=maintenance)
|
||||
@@ -1880,11 +1918,6 @@ Phase 21 — Blazor UI Dashboard + Sites
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 22 — Blazor UI Events + Persons + Live
|
||||
> **Maquette de conception historique, pas le routage ou les mesures actuels.**
|
||||
> La vidéo est intégrée à la page détail caméra; les estimations de latence et
|
||||
> le plafond P2P ci-dessous n'ont pas été validés et ne décrivent pas le relay
|
||||
> MediaMTX livré.
|
||||
|
||||
├── Events list (Route: /events)
|
||||
│ ├── Table paginée (50/page) avec filtres :
|
||||
│ │ Site (MudSelect), Type (MudSelect), Date (MudDateRangePicker)
|
||||
@@ -1909,10 +1942,6 @@ Phase 22 — Blazor UI Events + Persons + Live
|
||||
│ └── Timeline : barre des 30 dernières minutes
|
||||
├── Verify: Playwright events+live green
|
||||
│
|
||||
> **Maquette illustrative historique.** La route, les contrôles qualité,
|
||||
> snapshots/timeline, reconnexion et chiffres de latence ci-dessous ne sont
|
||||
> pas des affirmations sur l'UI ou les performances livrées.
|
||||
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ LIVE VIDÉO ─────────────────────────────────────────────────┐
|
||||
@@ -1939,11 +1968,6 @@ Phase 22 — Blazor UI Events + Persons + Live
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 23 — Blazor UI Admin
|
||||
> **Maquette historique, pas l’interface livrée.** Le dashboard/configuration
|
||||
> consolidés et le réglage Gotify ci-dessous ne sont pas des routes ou écrans
|
||||
> actuels. Consulter [`ui-pages.md`](ui-pages.md), [`auth-roles.md`](auth-roles.md)
|
||||
> et [les réglages de notification livrés](notifications.md).
|
||||
|
||||
├── Users management (tab Utilisateurs)
|
||||
│ ├── Liste des users avec rôle, email, 2FA status
|
||||
│ ├── [Modifier le rôle], [Reset 2FA], [Supprimer]
|
||||
@@ -1987,11 +2011,6 @@ Phase 23 — Blazor UI Admin
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
Phase 24 — Production Hardening
|
||||
> **Critères et scénarios historiques, pas des résultats d'acceptance.** Les
|
||||
> capacités, objectifs k6, seuils de latence, exemples de backup et assertions
|
||||
> « fonctionnel » ci-dessous ne prouvent pas l'implémentation actuelle, un
|
||||
> déploiement, ni un résultat de test.
|
||||
|
||||
├── Rate limiting (AspNetCoreRateLimit)
|
||||
│ ├── Auth : 5 tentatives/15min par IP
|
||||
│ ├── API : 100 requêtes/min par client
|
||||
@@ -2023,10 +2042,6 @@ Phase 24 — Production Hardening
|
||||
│ └── Pas de perte de snapshots sous charge normale
|
||||
├── Verify: k6 green, backup restore test OK
|
||||
│
|
||||
> **Résultats attendus de conception, jamais preuve de test/déploiement.** Les
|
||||
> valeurs k6 ci-dessus sont des objectifs; le scénario backup ci-dessous
|
||||
> précède le client réellement décrit dans `docker/backup/README.md`.
|
||||
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ HEALTH CHECKS ──────────────────────────────────────────────┐
|
||||
@@ -2048,9 +2063,6 @@ Phase 24 — Production Hardening
|
||||
│ │ "message": "Analyse IA unavailable"} │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
> **Exemple de backup historique, pas procédure actuelle ni résultat de restore.**
|
||||
> Voir le [guide backup livré](../docker/backup/README.md).
|
||||
|
||||
│ ┌─ BACKUP ─────────────────────────────────────────────────────┐
|
||||
│ │ Quotidien 2h : pg_dump → RustFS backup/heimdall_YYYY-MM-DD.sql.gz │
|
||||
│ │ Hebdomadaire dimanche 3h : mc mirror → backup/ (versionné) │
|
||||
@@ -2063,9 +2075,6 @@ Phase 24 — Production Hardening
|
||||
│ │ 5. Vérifier les sites, agents, events toujours présents │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
> **Objectifs de charge non mesurés et non validés.** Aucun seuil ci-dessous
|
||||
> n'est un SLO ou un résultat de production.
|
||||
|
||||
│ ┌─ LOAD TEST (k6) ─────────────────────────────────────────────┐
|
||||
│ │ objectif : 10 agents, 50 caméras, 20 viewers simultanés │
|
||||
│ │ │
|
||||
@@ -2124,10 +2133,6 @@ CPU; l'inférence GPU nécessite encore une image et un runtime dédiés.
|
||||
|
||||
## PARTIE 12 : Tests
|
||||
|
||||
> **Scénarios de test historiques (2026-07-16), pas résultats ni couverture
|
||||
> actuelle.** La référence `gotify` ci-dessous décrit une ancienne conception
|
||||
> de queue; voir [les canaux livrés](notifications.md) et [les jobs actuels](hangfire-usage.md).
|
||||
|
||||
### 12.1 Stack de Test
|
||||
|
||||
| Niveau | Technologie | Couverture |
|
||||
@@ -2228,13 +2233,10 @@ AnalysisWorker: concurrent requests from multiple cameras
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 14 : Historique de consolidation des documents sources
|
||||
## PARTIE 14 : Correctifs Applicables aux Documents Sources
|
||||
|
||||
Cette section conserve l'état éditorial de la consolidation du 2026-07-16.
|
||||
Le tableau décrit les observations faites à cette date sur les documents sources;
|
||||
il ne constitue pas un inventaire de leurs défauts actuels ni une liste de
|
||||
travail ouverte. Pour le comportement livré, utiliser les sources courantes
|
||||
liées dans l'en-tête de ce document.
|
||||
Les documents suivants contiennent des informations obsolètes ou erronées.
|
||||
**Ce document (`MASTER_SPECIFICATION.md`) fait foi.**
|
||||
|
||||
| Document source | Statut | Corrections nécessaires |
|
||||
|---|---|---|
|
||||
@@ -2251,11 +2253,6 @@ liées dans l'en-tête de ce document.
|
||||
|
||||
## Annexe A : Résumé des 36 Issues Critiques Résolues
|
||||
|
||||
> **Annexe historique de la baseline 2026-07-16**; ses résolutions et noms de
|
||||
> composants ne constituent pas une validation du runtime actuel. Pour les
|
||||
> notifications et queues livrées, voir le [guide notifications](notifications.md)
|
||||
> et le [guide Hangfire](hangfire-usage.md).
|
||||
|
||||
| # | Issue | Source | Résolution |
|
||||
|---|---|---|---|
|
||||
| C2 | Agent Registration ne retourne pas d'API Key | council-agent | ApiKey ajoutée à la réponse |
|
||||
|
||||
+14
-28
@@ -1,8 +1,7 @@
|
||||
# Heimdall — Documentation
|
||||
|
||||
Bienvenue dans la documentation technique de Heimdall, plateforme de
|
||||
vidéosurveillance multi-site auto-hébergée. L'analyse ONNX est locale par
|
||||
défaut sur l'Agent; un mode broker distant est configurable.
|
||||
vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
|
||||
---
|
||||
|
||||
@@ -12,7 +11,7 @@ défaut sur l'Agent; un mode broker distant est configurable.
|
||||
|---|---|
|
||||
| **Vue d'ensemble** du projet | `docs/specs.md` (Vision, Architecture, Stack) |
|
||||
| **État réel et travaux restants** | [Issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues) |
|
||||
| **Archive historique de l'implémentation** (MVP juillet 2026) | `docs/implementation.md` |
|
||||
| **Plan d'implémentation historique** (MVP juillet 2026) | `docs/implementation.md` |
|
||||
| **Maquettes UI Blazor** détaillées | `docs/ui-pages.md` |
|
||||
| **Application web installable (PWA)** | [Audit et plan PWA](pwa.md) |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) |
|
||||
@@ -21,25 +20,25 @@ défaut sur l'Agent; un mode broker distant est configurable.
|
||||
|
||||
| Domaine | Document | Contenu |
|
||||
|---|---|---|
|
||||
| **Sites & Agents** | [`docs/specs.md`](specs.md) (§5), [`docs/auth-roles.md`](auth-roles.md) | Création du site, enrôlement et heartbeat Agent |
|
||||
| **Caméras & IA** | [`docs/specs.md`](specs.md) (§5), [`docs/gpu-runtime.md`](gpu-runtime.md) | Découverte, analyse ONNX locale par défaut, CUDA NVIDIA optionnel et état de validation matérielle |
|
||||
| **Streaming live** | [`docs/specs.md`](specs.md) (§5), [`docs/ui-pages.md`](ui-pages.md), [`docs/signalr-usage.md`](signalr-usage.md) | Relay Agent vers MediaMTX en RTSP(S), lecture WHEP/WebRTC; validation caméra/réseau réelle suivie dans #161 et #341 |
|
||||
| **Enregistrements** | [`docs/ui-pages.md`](ui-pages.md), API `RecordingsController` | L’Agent segmente le flux principal, envoie les segments terminés au Central, qui les conserve dans le stockage configuré; lecture protégée dans la fiche caméra. Pas de validation caméra réelle revendiquée |
|
||||
| **Événements** | [`docs/specs.md`](specs.md) (§4), [`docs/ui-pages.md`](ui-pages.md), [`docs/notifications.md`](notifications.md) | Modèle d’événement caméra, pages événements et notifications |
|
||||
| **Notifications** | `docs/notifications.md` | Email SMTP, ntfy, centre in-app et préférences utilisateur |
|
||||
| **Sites & Agents** | `docs/specs.md` (§11-12) | Sites, tokens, registration, heartbeat, bootstrap |
|
||||
| **Caméras & IA** | `docs/specs.md` (§14-19) | ONVIF, Imou, FFmpeg, GPU, AI Pipeline, détection |
|
||||
| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | Architecture cible; consulter l'audit pour l'état livré |
|
||||
| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | Stockage cible; le pipeline d'enregistrement vidéo reste à raccorder |
|
||||
| **Événements** | `docs/specs.md` (§16-19) | Personnes, véhicules, plaques, notifications |
|
||||
| **Notifications** | `docs/notifications.md` | Email SMTP, Gotify, templates Markdown i18n |
|
||||
|
||||
## 🔧 Domaines techniques
|
||||
|
||||
| Domaine | Document | Contenu |
|
||||
|---|---|---|
|
||||
| **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope |
|
||||
| **IA (ONNX)** | [`docs/gpu-runtime.md`](gpu-runtime.md), [`docs/specs.md`](specs.md) (§5) | CPU par défaut, image CUDA NVIDIA optionnelle, limites d’inventaire et validation matérielle |
|
||||
| **IA (ONNX)** | `docs/specs.md` | Architecture cible; consulter l'audit pour distinguer les capacités livrées |
|
||||
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Configuration actuelle et jobs présents; vérifier l'état des parcours dans l'audit |
|
||||
| **Métriques et alertes** | [Métriques Prometheus](metrics.md) | Endpoints Web/Agent et signaux de santé exportés |
|
||||
| **SignalR (temps réel)** | `docs/signalr-usage.md` | Hubs et contrats documentés; état du streaming live dans l'audit |
|
||||
| **Déploiement Docker** | [`docs/specs.md`](specs.md) (§6), [`docs/docker-compose.md`](docker-compose.md) | Services requis et optionnels; l’inférence GPU NVIDIA est une variante Agent optionnelle |
|
||||
| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose |
|
||||
| **Docker Compose** | [Déploiement séparé](docker-compose.md) | Central + PostgreSQL requis; Agent et logiciels optionnels séparés |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Image CPU par défaut; image NVIDIA/CUDA amd64 optionnelle publiée avec manifeste signé; exécution CUDA physique à valider sur matériel |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Profils facultatifs; l'inférence ONNX publiée reste CPU |
|
||||
|
||||
## 📐 Structure du projet
|
||||
|
||||
@@ -66,19 +65,12 @@ Heimdall/
|
||||
| `implementation.md` | Plan historique du MVP (juillet 2026); statuts non représentatifs de l'état actuel |
|
||||
| `docker-compose.md` | Déploiement Central, Agents autonomes et logiciels facultatifs |
|
||||
| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états |
|
||||
| `pwa.md` | État livré de la PWA, limites hors ligne et feuille de route Web Push |
|
||||
| `auth-roles.md` | Auth : rôles Admin/Supervisor/Viewer, permissions et accès par site/caméra |
|
||||
| `notifications.md` | Canaux SMTP/ntfy, centre in-app, préférences et résumés planifiés |
|
||||
| `pwa.md` | Audit PWA du serveur Blazor, architecture cible et plan de réalisation |
|
||||
| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility |
|
||||
| `notifications.md` | Email (SMTP), Gotify, templates Markdown i18n, hangfile queue |
|
||||
| `hangfire-usage.md` | Description des jobs Hangfire présents au Central et à l’Agent |
|
||||
| `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites |
|
||||
| `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées |
|
||||
| `gpu-runtime.md` | Capacités GPU Agent, configuration et limites de validation matérielle |
|
||||
| `development-workflow.md` | Règles opérationnelles Heimdall, CI et recettes d'acceptance |
|
||||
|
||||
Les exigences produit supplémentaires pour l'installation et les mises à jour
|
||||
Agent sont décrites dans `agent-release-signing.md` et `docker-compose.md`.
|
||||
Le parcours et les états visibles du panneau d'installation sont décrits dans
|
||||
`ui-pages.md`. Les procédures exécutables restent dans `scripts/acceptance/`.
|
||||
|
||||
L'audit est la source de vérité pour les constats actuels, leur statut et les travaux
|
||||
restants. Les documents de spécification décrivent parfois la cible initiale; leurs
|
||||
@@ -86,12 +78,6 @@ mentions de fonctionnalités ne prouvent pas leur livraison.
|
||||
|
||||
**Total : ~5 600 lignes de documentation**
|
||||
|
||||
Les règles et critères d’acceptation propres au produit sont maintenus dans ces
|
||||
guides et les autres documents de ce répertoire. Les pratiques génériques sont
|
||||
fournies par le catalogue partagé installé au niveau utilisateur; ce dépôt ne
|
||||
contient aucune skill locale. Les recettes exécutables sont rangées sous
|
||||
`scripts/acceptance/` et les contrôles automatisés sous `scripts/ci/`.
|
||||
|
||||
## Audit du 20 octobre 2026
|
||||
|
||||
- [Issues et preuves courantes](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues)
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
# Signatures des mises à jour Agent
|
||||
|
||||
## Installation et mises à jour Agent
|
||||
|
||||
Linux and Windows installers verify the signed manifest and archive checksums
|
||||
before activation. An update preserves the previous release until the candidate
|
||||
reports the expected version and remains healthy for the stability interval; a
|
||||
startup failure restores the previous release. Linux metadata lookup retries
|
||||
transport errors, HTTP 408/425/429, and 5xx at most three times with bounded
|
||||
delays; other HTTP errors fail immediately. A published release must include
|
||||
the signed manifest, asset checksums, and required image digest; building a
|
||||
`main` image alone does not produce release metadata. Windows service paths
|
||||
and update/rollback still require validation on a real Windows host.
|
||||
|
||||
Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. La release publie aussi la clé publique ECDSA P-256. Pour le premier déploiement, l’installateur la récupère via Central sur HTTPS; l’Agent la conserve ensuite localement (Linux) ou dans la configuration générée par l’IHM (Docker/Windows). Central ne peut donc pas remplacer silencieusement la clé déjà épinglée par un Agent existant.
|
||||
|
||||
## Préparer les clés
|
||||
@@ -24,15 +12,11 @@ openssl pkey -in agent-release-private.pem -pubout -out agent-release-public.pem
|
||||
base64 -w0 agent-release-private.pem
|
||||
```
|
||||
|
||||
La dernière sortie est la valeur du secret Gitea Actions du dépôt `RELEASE_SIGNING_KEY_B64` (Settings → Actions → Secrets). Ne pas ajouter la clé privée au dépôt ni aux images. Le job de publication dérive la clé publique depuis ce secret et l’attache à chaque release. La publication d’une release échoue si le secret de signature manque. Au premier bootstrap, lorsqu’aucun Agent ni manifeste signé n’a encore été distribué, cette paire devient la racine de confiance de la première release; conserver une copie de sauvegarde privée dans un coffre sécurisé. Le jeton Gitea de publication est éphémère et limité au job déclenché par un tag SemVer; aucun PAT `RELEASE_TOKEN` n’est nécessaire.
|
||||
La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Le job de publication dérive la clé publique depuis ce secret et l’attache à chaque release. La publication d’une release échoue si le secret de signature manque.
|
||||
|
||||
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 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.forgepublicurl` avec l’origine HTTPS publique de Forgejo, par exemple `https://sources.tordais.cc`. Central construit l’endpoint fixe `https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest`; l’endpoint calculé est affiché en lecture seule dans l’IHM. Les anciennes valeurs `updates.releaseapiurl` sont migrées automatiquement vers leur origine Forgejo. 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.
|
||||
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é.
|
||||
|
||||
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.
|
||||
|
||||
@@ -42,18 +26,16 @@ Central affiche une commande Bash ou PowerShell qui télécharge et exécute l
|
||||
|
||||
```sh
|
||||
sudo bash install/install-agent.sh \
|
||||
--central-url-file /chemin/protege/central-url \
|
||||
--site-token-file /chemin/protege/site-token \
|
||||
--central-url https://central.example.org \
|
||||
--site-token 'JETON_DE_SITE' \
|
||||
--update-public-key /chemin/local/agent-release-public.pem
|
||||
```
|
||||
|
||||
Les deux fichiers d’enrôlement doivent être réguliers, non-symlinks et en mode `0600` ou plus restrictif; placez-les dans un répertoire privé. N’inscrivez jamais l’URL ou le jeton dans les arguments de processus.
|
||||
|
||||
L’installateur Linux est servi par Central avec son superviseur. Il installe la release sous `/opt/heimdall/agent/releases/`; le service systemd utilise le lien `current`. Après téléchargement vérifié, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue.
|
||||
|
||||
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
|
||||
|
||||
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM épinglent l’image CPU ou GPU au digest vérifié du manifeste signé (`repository@sha256:digest`). Compose et `docker run` récupèrent cette référence immuable au démarrage (`pull_policy: always` et `--pull always`). Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
|
||||
Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
|
||||
|
||||
## Rotation
|
||||
|
||||
|
||||
+212
-126
@@ -8,68 +8,61 @@
|
||||
|
||||
---
|
||||
|
||||
## 1. Rôles disponibles
|
||||
## 1. Types d'utilisateurs
|
||||
|
||||
Heimdall définit trois rôles (`Admin`, `Supervisor`, `Viewer`), listés dans
|
||||
[`AppRoles.All`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs) et
|
||||
[`UserRole`](../src/Heimdall.Domain/Enums/UserRole.cs). Les permissions par
|
||||
défaut viennent de [`AppPermissions.RolePermissions`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs); les
|
||||
permissions des rôles non-Admin peuvent être ajustées par un administrateur.
|
||||
Le rôle détermine les capacités, tandis que l’accès effectif aux sites et aux
|
||||
caméras est vérifié séparément par les services d’accès aux ressources.
|
||||
### Admin
|
||||
|
||||
| Rôle | Capacités par défaut |
|
||||
| Propriété | Valeur |
|
||||
|---|---|
|
||||
| **Admin** | Toutes les permissions, y compris l’administration globale. |
|
||||
| **Supervisor** | Lecture des sites, caméras, événements, personnes et véhicules; live, enregistrement et snapshots caméra; écriture caméra/personne/véhicule. Aucun droit `Admin.*` par défaut. |
|
||||
| **Viewer** | Lecture des sites, caméras, live, événements, personnes et véhicules. Aucun droit d’écriture, d’enregistrement, de snapshot ni `Admin.*` par défaut. |
|
||||
| Accès | **Tous les sites** sans restriction |
|
||||
| Configuration | Peut tout configurer (sites, caméras, IA, stockage, notifications) |
|
||||
| Administration | Gère les users, les rôles, les clés API, les jobs Hangfire |
|
||||
| Visibilité UI | **Toutes les pages** (y compris Admin) |
|
||||
| Permissions | Toutes les permissions automatiquement |
|
||||
| Sites | Non restreint — voit tous les sites, toutes les caméras |
|
||||
|
||||
Les rôles Supervisor et Viewer n’impliquent pas l’accès à tous les sites : les
|
||||
endpoints et handlers appliquent les affectations et contrôles de ressource via
|
||||
[`ICameraAccessService`](../src/Heimdall.Application/Services/ICameraAccessService.cs).
|
||||
Voir la matrice de permissions et la section sur `ICameraAccessService` ci-dessous.
|
||||
### User
|
||||
|
||||
| Propriété | Valeur |
|
||||
|---|---|
|
||||
| Accès | **1 ou N sites** assignés par l'Admin |
|
||||
| Configuration | Aucune — lecture seule ou actions limitées |
|
||||
| Administration | Aucun accès |
|
||||
| Visibilité UI | Pages selon ses permissions + uniquement ses sites |
|
||||
| Permissions | Définies par rôle + site |
|
||||
| Scope | Restreint aux sites qui lui sont assignés |
|
||||
|
||||
---
|
||||
|
||||
## 2. Modèle de données
|
||||
|
||||
```csharp
|
||||
// Infrastructure/Identity/IdentityAppUser.cs
|
||||
// La classe Identity et ses dépendances restent dans Infrastructure.
|
||||
public sealed class IdentityAppUser : IdentityUser<Guid>
|
||||
// IdentityUser de base — pas de modification
|
||||
public class User : IdentityUser<Guid>
|
||||
{
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public string? Theme { get; set; } = "Auto";
|
||||
public ThemeMode Theme { get; set; } = ThemeMode.Auto;
|
||||
public string Language { get; set; } = "fr";
|
||||
public bool TwoFactorEnabled { get; set; } = false; // TOTP
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool MustChangePassword { get; set; }
|
||||
}
|
||||
|
||||
// Domain/Entities/UserSite.cs — aucune navigation vers le type Identity.
|
||||
// Relation User → Sites (N-N)
|
||||
public class UserSite
|
||||
{
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid SiteId { get; private set; }
|
||||
public Site Site { get; private set; } = null!;
|
||||
public Guid UserId { get; set; }
|
||||
public User User { get; set; } = null!;
|
||||
|
||||
private UserSite() { } // EF Core
|
||||
|
||||
public UserSite(Guid userId, Guid siteId)
|
||||
{
|
||||
UserId = userId;
|
||||
SiteId = siteId;
|
||||
}
|
||||
public Guid SiteId { get; set; }
|
||||
public Site Site { get; set; } = null!;
|
||||
}
|
||||
|
||||
// Infrastructure/Data/Configurations/UserSiteConfiguration.cs — relation seulement.
|
||||
builder.HasOne<IdentityAppUser>().WithMany().HasForeignKey(us => us.UserId);
|
||||
|
||||
// Rôles prédéfinis
|
||||
public static class AppRoles
|
||||
{
|
||||
public const string Admin = "Admin";
|
||||
public const string Supervisor = "Supervisor"; // libellé UI français : Superviseur
|
||||
public const string Viewer = "Viewer"; // lecture seule
|
||||
public const string Superviseur = "Superviseur"; // peut voir + agir
|
||||
public const string Viewer = "Viewer"; // lecture seule
|
||||
}
|
||||
```
|
||||
|
||||
@@ -98,20 +91,19 @@ public static class AppPermissions
|
||||
public const string EventRead = "Event.Read";
|
||||
public const string PersonRead = "Person.Read";
|
||||
public const string PersonWrite = "Person.Write";
|
||||
public const string VehicleRead = "Vehicle.Read";
|
||||
public const string VehicleWrite = "Vehicle.Write";
|
||||
|
||||
// Administration
|
||||
public const string AdminManage = "Admin.Manage";
|
||||
public const string AdminUsers = "Admin.Users";
|
||||
public const string AdminApiKeys = "Admin.ApiKeys";
|
||||
public const string AdminJobs = "Admin.Jobs"; // Hangfire dashboard
|
||||
public const string AdminManage = "Administration.Manage";
|
||||
public const string AdminUsers = "Administration.Users";
|
||||
public const string AdminApiKeys = "Administration.ApiKeys";
|
||||
public const string AdminJobs = "Administration.Jobs"; // Hangfire dashboard
|
||||
public const string AdminNotifications = "Administration.Notifications"; // templates
|
||||
}
|
||||
```
|
||||
|
||||
### Mapping Rôle → Permissions
|
||||
|
||||
| Permission | Admin | Supervisor | Viewer |
|
||||
| Permission | Admin | Superviseur | Viewer |
|
||||
|---|---|---|---|
|
||||
| Site.Read | ✅ | ✅ | ✅ |
|
||||
| Site.Write | ✅ | ❌ | ❌ |
|
||||
@@ -124,12 +116,11 @@ public static class AppPermissions
|
||||
| Event.Read | ✅ | ✅ | ✅ |
|
||||
| Person.Read | ✅ | ✅ | ✅ |
|
||||
| Person.Write | ✅ | ✅ | ❌ |
|
||||
| Vehicle.Read | ✅ | ✅ | ✅ |
|
||||
| Vehicle.Write | ✅ | ✅ | ❌ |
|
||||
| Admin.Manage | ✅ | ❌ | ❌ |
|
||||
| Admin.Users | ✅ | ❌ | ❌ |
|
||||
| Admin.ApiKeys | ✅ | ❌ | ❌ |
|
||||
| Admin.Jobs | ✅ | ❌ | ❌ |
|
||||
| Admin.Notifications | ✅ | ❌ | ❌ |
|
||||
|
||||
---
|
||||
|
||||
@@ -138,30 +129,68 @@ public static class AppPermissions
|
||||
### Enregistrement
|
||||
|
||||
```csharp
|
||||
// Heimdall.Web/Program.cs — ConfigureAuthorizationPolicies
|
||||
builder.Services.AddAuthorizationCore(options =>
|
||||
// Program.cs
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct();
|
||||
foreach (var permission in allPermissions)
|
||||
options.AddPolicy(permission, policy =>
|
||||
// Permission directe
|
||||
foreach (var permission in typeof(AppPermissions).GetFields(
|
||||
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
|
||||
.Where(f => f.IsLiteral && !f.IsInitOnly)
|
||||
.Select(f => f.GetRawConstantValue() as string)
|
||||
.Where(v => v != null))
|
||||
{
|
||||
options.AddPolicy(permission!, policy =>
|
||||
policy.RequireClaim("permission", permission));
|
||||
}
|
||||
|
||||
// Legacy role-based policy retained for administrative endpoints.
|
||||
options.AddPolicy("AdminUsers", policy =>
|
||||
// Admin a toutes les permissions automatiquement
|
||||
options.AddPolicy("AdminOnly", policy =>
|
||||
policy.RequireRole(AppRoles.Admin));
|
||||
});
|
||||
```
|
||||
|
||||
### Vérification site et caméra
|
||||
### Vérification site-scope
|
||||
|
||||
Les endpoints déclarent une policy comme `Camera.Read`, puis transmettent
|
||||
l'identité utilisateur aux queries ou à `ResourceAccess` pour filtrer la
|
||||
ressource demandée. Par exemple, `GET /api/cameras/by-site/{siteId}` est mappé
|
||||
par `CamerasController.ListBySite`; il crée un `GetCamerasBySiteQuery` avec le
|
||||
`userId`. Le handler appelle `ICameraAccessService` et ne retourne que les
|
||||
caméras auxquelles cet utilisateur a accès. Il n'existe pas de route
|
||||
`/api/sites/{siteId}/cameras` dans ce contrôleur ni de handler générique
|
||||
`SiteAuthorizationHandler`.
|
||||
Pour les Users non-Admin, chaque requête sur un site doit vérifier
|
||||
que l'User a accès à ce site :
|
||||
|
||||
```csharp
|
||||
public class SiteAuthorizationHandler : AuthorizationHandler<SiteRequirement, Guid>
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
protected override async Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context,
|
||||
SiteRequirement requirement,
|
||||
Guid siteId)
|
||||
{
|
||||
if (context.User.IsInRole(AppRoles.Admin))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = context.User.GetUserId();
|
||||
var hasAccess = await _db.UserSites
|
||||
.AnyAsync(us => us.UserId == userId && us.SiteId == siteId);
|
||||
|
||||
if (hasAccess) context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
|
||||
public record SiteRequirement : IAuthorizationRequirement;
|
||||
|
||||
// Usage dans un endpoint :
|
||||
[HttpGet("/api/sites/{siteId}/cameras")]
|
||||
public async Task<IActionResult> GetCameras(
|
||||
Guid siteId,
|
||||
[FromServices] IAuthorizationService auth)
|
||||
{
|
||||
var authResult = await auth.AuthorizeAsync(User, siteId, "SiteAccess");
|
||||
if (!authResult.Succeeded) return Forbid();
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -175,90 +204,147 @@ caméras auxquelles cet utilisateur a accès. Il n'existe pas de route
|
||||
| Dashboard | `/` | ✅ Tous sites | ✅ Ses sites | ✅ Ses sites |
|
||||
| Sites liste | `/sites` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
|
||||
| Site détail | `/sites/{id}` | ✅ | ✅ (si assigné) | ✅ (si assigné) |
|
||||
| Détail caméra (live-view intégré) | `/cameras/{id}` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
|
||||
| Caméra live | `/cameras/{id}/live` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
|
||||
| Events | `/events` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
|
||||
| Persons | `/persons` | ✅ | ✅ | ✅ |
|
||||
| Paramètres (dont notifications) | `/settings` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Utilisateurs | `/users` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Rôles | `/admin/roles` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Groupes | `/admin/groups` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Agents | `/admin/agents` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Clés API | `/admin/api-keys` | ✅ Admin.ApiKeys | ❌ | ❌ |
|
||||
| Claims | `/admin/claims` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Journaux d'audit | `/audit-logs` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Hangfire | `/hangfire` | ✅ Admin.Jobs | ❌ | ❌ |
|
||||
|
||||
La page détail caméra requiert une session authentifiée; les API de données et
|
||||
de live-view appliquent `Camera.Read` et vérifient aussi l'accès effectif à la
|
||||
caméra et à son site. La session live utilise
|
||||
`POST /api/live-media/cameras/{cameraId}/session` et
|
||||
`DELETE /api/live-media/cameras/{cameraId}/session/{sessionId}`. `Camera.Live`
|
||||
reste dans le catalogue des permissions attribuées aux rôles, mais n'est pas la
|
||||
policy appliquée à ces deux endpoints dans le contrôleur actuel.
|
||||
| Admin | `/admin` | ✅ | ❌ Redirection | ❌ Redirection |
|
||||
| Admin Users | `/admin/users` | ✅ | ❌ | ❌ |
|
||||
| Admin API Keys | `/admin/api-keys` | ✅ | ❌ | ❌ |
|
||||
| Admin Hangfire | `/admin/jobs` | ✅ | ❌ | ❌ |
|
||||
| Admin Notifications | `/admin/notifications` | ✅ | ❌ | ❌ |
|
||||
|
||||
### Implementation Blazor
|
||||
|
||||
```csharp
|
||||
// MainLayout — le groupe Administration apparaît avec l’une de ces permissions.
|
||||
@if (Auth.HasPermission("Admin.Users") || Auth.HasPermission("Admin.Manage"))
|
||||
// Layout — masquer le menu Admin si pas Admin
|
||||
@if (await AuthorizeService.HasPermissionAsync(AppPermissions.AdminManage))
|
||||
{
|
||||
<MudText Typo="Typo.overline">Administration</MudText>
|
||||
|
||||
@if (Auth.HasPermission("Admin.Users"))
|
||||
{
|
||||
<MudNavLink Href="/users">Utilisateurs</MudNavLink>
|
||||
<MudNavLink Href="/admin/groups">Groupes</MudNavLink>
|
||||
<MudNavLink Href="/admin/roles">Rôles</MudNavLink>
|
||||
}
|
||||
|
||||
@if (Auth.HasPermission("Admin.Manage"))
|
||||
{
|
||||
<MudNavLink Href="/admin/claims">Claims</MudNavLink>
|
||||
}
|
||||
<MudNavLink Href="/admin">⚙️ Administration</MudNavLink>
|
||||
}
|
||||
|
||||
// Page Events — filtrer par site si User non-Admin
|
||||
@code {
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (await AuthorizeService.IsAdminAsync())
|
||||
{
|
||||
_sites = await SiteService.GetAllAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_sites = await SiteService.GetMySitesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Les pages authentifiées sont enveloppées par `AuthorizeRouteView` dans
|
||||
[`Routes.razor`](../src/Heimdall.Web/Components/Routes.razor); par exemple,
|
||||
[`EventsPage.razor`](../src/Heimdall.Web/Components/Pages/EventsPage.razor)
|
||||
déclare `[Authorize]` et charge les données via `HeimdallApiClient`. Les listes
|
||||
et détails site/caméra ne filtrent pas les ressources selon un `IsAdminAsync`
|
||||
local : les endpoints et queries appliquent les permissions puis
|
||||
[`ResourceAccess`](../src/Heimdall.Web/Security/ResourceAccess.cs) et les
|
||||
services d’accès aux ressources. Les endpoints de session live et la distinction
|
||||
`Camera.Read`/`Camera.Live` sont décrits ci-dessus.
|
||||
### AuthorizeView
|
||||
|
||||
```razor
|
||||
<AuthorizeView Policy="@AppPermissions.CameraLive">
|
||||
<Authorized>
|
||||
<button @onclick="StartLiveView">📷 Live</button>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
<MudTooltip Text="Accès non autorisé">
|
||||
<button disabled>📷 Live</button>
|
||||
</MudTooltip>
|
||||
</NotAuthorized>
|
||||
</AuthorizeView>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. API — filtrage des accès caméra
|
||||
## 6. API — middleware de scope
|
||||
|
||||
Le runtime n'utilise pas de `SiteScopeMiddleware` global ni de liste
|
||||
`AllowedSiteIds` placée dans `HttpContext`. Les endpoints appliquent leurs
|
||||
policies d'authentification et les queries/services partagés résolvent les
|
||||
droits de ressource à partir des accès courants. Pour les caméras, ce modèle
|
||||
est centralisé dans `ICameraAccessService`/`CameraAccessService`; pour une
|
||||
ressource précise, `ResourceAccess` effectue le contrôle demandé par le
|
||||
contrôleur. Cela inclut les accès directs, les accès de site, les anciennes
|
||||
affectations et les groupes caméra. Maintenir cette union dans le service
|
||||
partagé et ses tests, sans la réimplémenter dans un contrôleur.
|
||||
Un middleware applique le scope site automatiquement sur les requêtes API :
|
||||
|
||||
The shared camera-access service combines direct camera grants, site grants,
|
||||
legacy assignments, and camera groups. API endpoints and application queries
|
||||
both enforce access at their boundaries; UI visibility is not an authorization
|
||||
check. When changing a camera-scoped flow, cover direct and inherited grants,
|
||||
denials, and current access revocation in the service/controller tests.
|
||||
```csharp
|
||||
public class SiteScopeMiddleware
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (context.User.Identity?.IsAuthenticated != true) return;
|
||||
|
||||
// Admin bypass
|
||||
if (context.User.IsInRole(AppRoles.Admin))
|
||||
{
|
||||
context.Items["AllowedSiteIds"] = null; // all
|
||||
return;
|
||||
}
|
||||
|
||||
// User scope
|
||||
var userId = context.User.GetUserId();
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId)
|
||||
.ToListAsync();
|
||||
|
||||
context.Items["AllowedSiteIds"] = siteIds;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Puis dans les repositories/query handlers, filtrer par `AllowedSiteIds` :
|
||||
|
||||
```csharp
|
||||
public class GetEventsQueryHandler : IRequestHandler<GetEventsQuery, PagedResult<EventDto>>
|
||||
{
|
||||
public async Task<PagedResult<EventDto>> Handle(GetEventsQuery request, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Events.AsQueryable();
|
||||
|
||||
// Scope site
|
||||
if (request.AllowedSiteIds != null)
|
||||
query = query.Where(e => request.AllowedSiteIds.Contains(e.SiteId));
|
||||
|
||||
// Si siteId spécifique fourni, vérifier qu'il est dans les allowed
|
||||
if (request.SiteId.HasValue)
|
||||
{
|
||||
if (request.AllowedSiteIds != null &&
|
||||
!request.AllowedSiteIds.Contains(request.SiteId.Value))
|
||||
return new PagedResult<EventDto>(); // vide
|
||||
query = query.Where(e => e.SiteId == request.SiteId.Value);
|
||||
}
|
||||
|
||||
// ... pagination, filtres ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. JWT Claims
|
||||
|
||||
`JwtService.GenerateAccessToken` émet le sujet utilisateur, l'email, le nom,
|
||||
les métadonnées de session, les rôles et les permissions. Il n'embarque pas de
|
||||
liste d'IDs de site ou de caméra. Les droits de ressource restent résolus côté
|
||||
serveur depuis les affectations courantes via `CameraAccessService` et
|
||||
`ResourceAccess`, afin qu'une modification d'accès ne dépende pas d'une liste
|
||||
de sites figée dans un JWT.
|
||||
```csharp
|
||||
// À la génération du token JWT
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new(ClaimTypes.Name, user.DisplayName),
|
||||
new(ClaimTypes.Role, role), // "Admin"
|
||||
};
|
||||
|
||||
// Ajouter toutes les permissions du rôle
|
||||
foreach (var permission in GetPermissionsForRole(role))
|
||||
claims.Add(new Claim("permission", permission));
|
||||
|
||||
// Ajouter les sites accessibles (si non-Admin)
|
||||
if (role != AppRoles.Admin)
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == user.Id)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
foreach (var siteId in siteIds)
|
||||
claims.Add(new Claim("site", siteId));
|
||||
}
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddHours(8),
|
||||
signingCredentials: credentials);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -274,4 +360,4 @@ API respects site scope for non-admin users
|
||||
JWT token contains permissions claims
|
||||
UserSite assignment works correctly
|
||||
Removing user from site revokes access immediately
|
||||
```
|
||||
```
|
||||
@@ -1,65 +0,0 @@
|
||||
# Règles de développement et acceptance Heimdall
|
||||
|
||||
Ce document conserve les exigences opérationnelles propres au dépôt. Les
|
||||
pratiques générales des agents relèvent du catalogue partagé. Utiliser les
|
||||
issues Gitea comme backlog du projet et suivre le cycle commun de livraison.
|
||||
|
||||
## Architecture et implémentation
|
||||
|
||||
- `Domain` reste indépendant de l'infrastructure. Placer les cas d'usage et
|
||||
interfaces dans `Application`, les adaptateurs et la persistance EF Core
|
||||
dans `Infrastructure`, la composition HTTP/UI dans `Web`, et le comportement
|
||||
caméra/runtime dans `Agent`.
|
||||
- Cibler le SDK épinglé dans `global.json` et .NET 10 ou plus récent.
|
||||
- Utiliser EF Core pour les lectures et écritures de production. Les commandes
|
||||
ADO.NET ou spécifiques au fournisseur sont interdites en production. Une
|
||||
requête SQL EF propre au fournisseur n'est admise que si LINQ ne peut exprimer
|
||||
la capacité requise, avec justification adjacente et test relationnel. Le
|
||||
contrôle CI de persistance vérifie cette limite. Préserver PostgreSQL,
|
||||
ajouter les migrations de schéma et tester traduction, concurrence et
|
||||
suppression sur une base relationnelle. Ne jamais partager un `DbContext`
|
||||
entre opérations concurrentes.
|
||||
- Vérifier l'autorisation tenant/site et caméra aux frontières API et
|
||||
application. Ne jamais journaliser identifiants, URL RTSP, embeddings ou
|
||||
jetons bruts.
|
||||
|
||||
## CI, déploiement et validations
|
||||
|
||||
- Les jobs Gitea s'exécutent sur `[ubuntu-latest, build-agent]`. Ne pas placer
|
||||
`runner-aaja` sur ce label. Ne jamais exposer d'identifiants de publication
|
||||
dans un job de pull request.
|
||||
- Pour les recettes d'intégration, appliquer `disposable-test-environment` et
|
||||
choisir le script pertinent dans `scripts/acceptance/`.
|
||||
- Les validations de runner, registre, site, caméra ou stockage distant exigent
|
||||
une preuve d'exécution sur la cible concernée; les recettes locales ne
|
||||
constituent pas cette preuve.
|
||||
|
||||
## Recettes conservées
|
||||
|
||||
Les scripts Compose d'acceptance sont exécutables dans `scripts/acceptance/` :
|
||||
|
||||
- `agent-heartbeat-timeout.sh` — heartbeat Agent et expiration;
|
||||
- `agent-startup-composition.sh` — composition et démarrage Agent;
|
||||
- `camera-toggle-acceptance.sh` — activation et désactivation caméra;
|
||||
- `database-migration-startup.sh` — migration et reprise au démarrage;
|
||||
- `heimdall-identity.sh` — création/connexion et flux de cookie 2FA;
|
||||
- `optional-server-services.sh` — services optionnels et sauvegarde/restauration;
|
||||
- `renovate-automation.sh` — acceptance de l'automatisation Renovate;
|
||||
- `webrtc-live-source-change.sh` — changement de source du live view.
|
||||
|
||||
Les contrôles de build et de politique restent dans `scripts/ci/`. Voir
|
||||
[`gitea-builds.md`](gitea-builds.md) pour les workflows et contraintes de
|
||||
runners, et [`docker-compose.md`](docker-compose.md) pour les recettes jetables.
|
||||
|
||||
Pour les changements d'installation Agent, préserver la vérification de
|
||||
signature et de sommes de contrôle, ainsi que le rollback vers la release
|
||||
précédente si le démarrage échoue; voir
|
||||
[`agent-release-signing.md`](agent-release-signing.md). Les tests locaux de
|
||||
rollback ne remplacent pas la validation d'un service Linux ou Windows réel.
|
||||
|
||||
## Collaboration et conception
|
||||
|
||||
Pour les changements d'interface issus de Penpot, ouvrir le document avec la
|
||||
session authentifiée du navigateur Orca et synchroniser le design connecté avec
|
||||
les changements UI livrés. Si le travail est découpé en lots indépendants,
|
||||
coordonner les lots via Orca et intégrer puis valider le résultat combiné.
|
||||
+16
-74
@@ -1,8 +1,8 @@
|
||||
# Docker Compose deployment
|
||||
|
||||
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
|
||||
separately on each camera-network host; the Central UI supplies an Agent
|
||||
Compose file using the `latest` tag for each site. RustFS, ntfy, Ollama, TURN,
|
||||
separately on each camera-network host; the Central UI supplies a
|
||||
digest-pinned Agent Compose file for each site. RustFS, ntfy, Ollama, TURN,
|
||||
Redis and scheduled backups have separate Compose files and can be left out.
|
||||
|
||||
## Central and database
|
||||
@@ -112,18 +112,9 @@ camera detail page. Processing runs on Central; the temporary crop is removed
|
||||
after processing, while the candidate text and history event are persisted.
|
||||
The feature limits uploads to 512 KiB and images to four megapixels. It does
|
||||
not detect plates in video or perform face recognition, and the OCR result is
|
||||
not a verified identity. Review the retention and privacy implications
|
||||
documented for the product before enabling it.
|
||||
|
||||
OCR runs only after an authorized operator selects a JPEG/PNG crop. Central
|
||||
deletes the temporary image after processing and stores a normalized candidate,
|
||||
confidence, and history event; it does not link a person or vehicle
|
||||
automatically. An operator must confirm a proposed vehicle association through
|
||||
the authorized workflow. Candidate observations and detection events are
|
||||
retained for 30 days; snapshots are removed from their recorded storage
|
||||
destination before event deletion. Rows with incomplete storage provenance are
|
||||
retained rather than deleted from a guessed location. Face matching remains
|
||||
disabled until the exact model weights and training-data rights are reviewed.
|
||||
not a verified identity. Review retention/privacy implications in
|
||||
[`skills/vision-identity/SKILL.md`](../skills/vision-identity/SKILL.md) before
|
||||
enabling it.
|
||||
|
||||
The development Compose builds Central from the local source and starts only
|
||||
Central plus PostgreSQL:
|
||||
@@ -138,31 +129,17 @@ values, and choose unused loopback ports. Use a unique Compose project name and
|
||||
`HEIMDALL_NETWORK_NAME`; after checking `/healthz`, stop only that project with
|
||||
`docker compose -p <project> ... down --volumes --remove-orphans`. Verify its
|
||||
containers, volumes, and network are gone. Never use `.env.example` unchanged
|
||||
for an exposed or production deployment.
|
||||
|
||||
### Disposable Compose acceptance
|
||||
|
||||
For a product behavior or deployment change that needs integration acceptance,
|
||||
use a unique Compose project built from the changed source, generated synthetic
|
||||
credentials and data, loopback-only ports, and project-scoped volumes and
|
||||
network. Install cleanup before the first build or start. After exercising the
|
||||
changed behavior through its HTTP, UI, or Agent boundary, remove only that
|
||||
project and verify its containers, volumes, and network are absent. Remove and
|
||||
verify absence of each exact locally built image tag; retain upstream base
|
||||
images. Keep the original check result if cleanup fails and report the cleanup
|
||||
failure. Synthetic acceptance does not establish deployed-host, external
|
||||
network, or physical-camera behavior.
|
||||
for an exposed or production deployment. The disposable recipe is maintained
|
||||
in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-acceptance/SKILL.md).
|
||||
|
||||
## Agent
|
||||
|
||||
Prefer the Compose shown in the Central UI's site installation panel. It pins
|
||||
the CPU or GPU Agent image to the signed `repository@sha256:digest` and includes
|
||||
the site token, public Central URL, Agent name and release public key. Compose
|
||||
uses `pull_policy: always` to fetch that exact digest. Save it as
|
||||
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
|
||||
contains the pinned trust key; no separate PEM file is required. Updates
|
||||
dispatched later by Central continue to verify the digest in the signed release
|
||||
manifest before replacing the running container.
|
||||
Prefer the Compose shown in the Central UI's site installation panel. It uses
|
||||
the image reference and digest from Central's verified release manifest and
|
||||
includes the site token, public Central URL, Agent name and release public key.
|
||||
Save it as `docker-compose.yml`, then run `docker compose up -d`. The generated
|
||||
Compose contains the pinned trust key; no separate PEM file is required. Do
|
||||
not substitute a mutable image tag for the digest.
|
||||
|
||||
The Agent Compose is generated by Central's UI for the selected site; there is
|
||||
no production Agent Compose in this repository. For local development only,
|
||||
@@ -171,36 +148,6 @@ local Central URL. The published Agent image uses CPU inference. The optional
|
||||
NVIDIA, AMD and Intel overlays expose hardware for inventory; they do not
|
||||
enable GPU inference.
|
||||
|
||||
Docker Agents mount `/var/run/docker.sock` so the Agent can pull and replace its
|
||||
container when Central dispatches an update. This socket grants broad control
|
||||
of the Docker host, effectively host-administrator access. Keep it only on
|
||||
hosts where that trust is acceptable. The Agent image includes the Docker CLI
|
||||
client; it does not run a Docker daemon. Updates preserve the previous image
|
||||
for rollback if the replacement fails its health check. On Linux, start the
|
||||
generated Compose with `DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)"
|
||||
docker compose up -d` so the non-root Agent process can access hosts whose
|
||||
socket is owned by the Docker group. The UI's `docker run` command determines
|
||||
this group ID from the host socket automatically.
|
||||
|
||||
The Agent applies a complete camera-configuration snapshot atomically and
|
||||
acknowledges the exact digest to Central. Transient network failures and HTTP
|
||||
408/429/5xx acknowledgements are retried at most three times with bounded
|
||||
delays; permanent 4xx responses stop retries. Keep the previous applied
|
||||
snapshot active after a rejected acknowledgement. Do not log API keys, camera
|
||||
URLs, configuration payloads, or response bodies. Camera disable acceptance
|
||||
must distinguish Central's requested state, the digest acknowledged by the
|
||||
Agent, and actual FFmpeg process release. Reconnection tests verify full
|
||||
replacement including removed assignments; real-camera stability and LAN
|
||||
discovery remain separate hardware/network validation.
|
||||
|
||||
The Agent reports log levels using the exact names `Trace`, `Debug`,
|
||||
`Information`, `Warning`, `Error`, and `Critical`; Central does not accept
|
||||
`Info` or `Warn` aliases. The Central `HttpClient` timeout is ten seconds. A
|
||||
heartbeat timeout is transient and the service continues its loop; cancellation
|
||||
caused by host shutdown still propagates cooperatively. Keep timeout and
|
||||
continued-service behavior in separate acceptance assertions.
|
||||
|
||||
|
||||
## Optional software
|
||||
|
||||
Start Central first to create the shared `heimdall-net` network. Optional
|
||||
@@ -243,14 +190,9 @@ RTSPS/WHEP TCP ports and WebRTC ICE UDP port in the firewall. Add STUN URLs unde
|
||||
`LiveMedia:IceServers`; for TURN REST credentials set
|
||||
`LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns
|
||||
five-minute HMAC credentials to the browser; the shared secret is never sent.
|
||||
When using `docker-compose.coturn.yml`, the installer stores its shared secret
|
||||
at `optional/secrets/coturn_secret`. Configure the matching TURN shared secret
|
||||
in Central from that protected file and protect Central's `.env` with owner-only
|
||||
permissions. Coturn publishes TCP/UDP 3478 and UDP relay ports 49160–49200 by
|
||||
default; forward those ports through the host firewall/NAT. Set
|
||||
`COTURN_RELAY_PORT_MIN` and `COTURN_RELAY_PORT_MAX` together if you need a
|
||||
different relay range, and `COTURN_EXTERNAL_IP` when coturn must advertise an
|
||||
address other than the container's detected address. Use Docker's default bridge network; coturn must not use `network_mode: host` when relying on published ports.
|
||||
When using `docker-compose.coturn.yml`, configure the Central secret from the same
|
||||
protected secret source as `docker/secrets/coturn_secret`; protect the Central
|
||||
`.env` with owner-only permissions.
|
||||
|
||||
Start the core project first so its external `heimdall-net` network exists, then
|
||||
start MediaMTX with a separate project name:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CI Gitea et images Heimdall
|
||||
|
||||
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`.
|
||||
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.
|
||||
|
||||
## Sélection des runners
|
||||
|
||||
@@ -8,23 +8,24 @@ Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent
|
||||
|
||||
Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir.
|
||||
|
||||
Le workflow Renovate lit l’API Forgejo dans la variable d’action `FORGEJO_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Forgejo réserve les noms de variables commençant par `GITEA_`. Avant de démarrer Renovate, le workflow vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
|
||||
Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Avant de démarrer Renovate, il vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
|
||||
|
||||
`scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi.
|
||||
|
||||
## Tests
|
||||
|
||||
`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.
|
||||
`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.
|
||||
|
||||
## Publication continue
|
||||
|
||||
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.
|
||||
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` :
|
||||
|
||||
Chaque PR doit contenir exactement une ligne `Release assessment: <none|patch|minor|major> — <rationale>` dans son corps. Après une fusion vers `main`, `Create version tag after successful main CI` interroge la PR associée au SHA poussé et s'exécute seulement si `CI policy` a réussi. `none` termine sans tag; `patch`, `minor` et `major` calculent la prochaine version depuis le tag stable atteignable le plus récent. Une évaluation absente ou ambiguë échoue sans créer de tag. Le job vérifie l'absence de collision et ne déplace jamais un tag existant; une reprise est idempotente si le tag pointe déjà vers le même SHA. Les commits `main` non issus d'une PR ne créent pas de version.
|
||||
- `eltruncho/heimdall:latest` et `eltruncho/heimdall:sha-<commit complet>` ;
|
||||
- `eltruncho/heimdall-agent:latest` et `eltruncho/heimdall-agent:sha-<commit complet>`.
|
||||
|
||||
Le tag créé déclenche le workflow versionné existant: il valide tous les projets, 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.
|
||||
|
||||
Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets Actions `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN` et `RELEASE_SIGNING_KEY_B64` doivent être disponibles pour les jobs qui publient. La création du tag et la publication utilisent chacune le jeton intégré `GITEA_TOKEN` limité au job : création `contents: write` et `pull-requests: read`, publication `contents: write`, `pull-requests: read` et `actions: read`. Aucun PAT durable `RELEASE_TOKEN` n’est requis et les PR ne reçoivent aucun droit d’écriture. `RELEASE_SERVER_URL` est une variable Actions contenant l’origine HTTPS publique de la forge. Les identifiants Docker sont transmis à `docker login` sur stdin et stockés dans une configuration temporaire supprimée en sortie.
|
||||
Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. 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 reste en brouillon jusqu'à promotion explicite.
|
||||
|
||||
## Renovate
|
||||
|
||||
|
||||
+17
-10
@@ -15,7 +15,7 @@
|
||||
│ │
|
||||
│ Hangfire Server │
|
||||
│ ├── Storage: PostgreSQL (Hangfire.PostgreSql) │
|
||||
│ ├── Dashboard: /hangfire (AdminJobs ou rôle Admin) │
|
||||
│ ├── Dashboard: /admin/jobs (authentifié, Admin only) │
|
||||
│ └── Jobs: │
|
||||
│ ├── RetentionCheck (Recurring, daily) │
|
||||
│ ├── S3Cleanup (Recurring, daily) │
|
||||
@@ -467,20 +467,27 @@ public class HangfireInitializer : IHostedService
|
||||
|
||||
Intégré à l'UI Admin, authentifié, pas exposé publiquement :
|
||||
|
||||
La route Central est mappée par `MapHangfireDashboard("/hangfire", ...)` dans
|
||||
`src/Heimdall.Web/Program.cs`. `HangfireAdminAuthorizationFilter` autorise les
|
||||
requêtes authentifiées portant `Admin.Jobs` ou le rôle `Admin`. Le dashboard
|
||||
n'est pas mappé dans l'environnement `Testing`.
|
||||
|
||||
```csharp
|
||||
// Heimdall.Web/Program.cs
|
||||
app.MapHangfireDashboard("/hangfire", new DashboardOptions
|
||||
// Heimdall.Api / Program.cs
|
||||
app.UseHangfireDashboard("/admin/jobs", new DashboardOptions
|
||||
{
|
||||
Authorization =
|
||||
[
|
||||
new HangfireAdminAuthorizationFilter()
|
||||
new HangfireAuthorizationFilter() // vérifie AppPermissions.AdminJobs
|
||||
],
|
||||
StatsPollingInterval = 3000, // 3s
|
||||
DisplayStorageConnectionString = false,
|
||||
DashboardTitle = "Heimdall — Jobs",
|
||||
});
|
||||
|
||||
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
|
||||
{
|
||||
public bool Authorize(DashboardContext context)
|
||||
{
|
||||
var httpContext = context.GetHttpContext();
|
||||
return httpContext.User?.IsInRole(AppRoles.Admin) == true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -522,4 +529,4 @@ Hangfire dashboard is accessible only to Admin
|
||||
Hangfire dashboard returns 403 for non-Admin
|
||||
Agent jobs are recreated after agent restart
|
||||
Agent InMemory storage does not persist across restarts
|
||||
```
|
||||
```
|
||||
+18
-33
@@ -1,24 +1,9 @@
|
||||
# Heimdall — Archive historique du plan d'implémentation (MVP, juillet 2026)
|
||||
# Heimdall — Plan d'implémentation
|
||||
|
||||
> **Archive historique, pas une description de l’état actuel ni un guide à suivre.** Tout le contenu ci-dessous — architecture, chemins, statuts, commandes, endpoints, décomptes de tests et travaux « à faire » — reflète un instantané du MVP rédigé en juillet 2026. Ces informations ne décrivent pas le dépôt courant et ne constituent pas des instructions d’exploitation. Pour l’implémentation actuelle, utiliser les références ci-dessous; pour l’avancement et les travaux ouverts, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
> **Document historique (MVP — juillet 2026).** Les statuts de phases ci-dessous ne reflètent pas l’état courant du dépôt. Pour le suivi à jour, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
|
||||
## Références actuelles
|
||||
|
||||
| Sujet | Source actuelle |
|
||||
|---|---|
|
||||
| Installation Central, Compose et services optionnels | [Guide Docker Compose](docker-compose.md) |
|
||||
| CI, builds et publication | [CI Gitea et images](gitea-builds.md), [signatures des mises à jour Agent](agent-release-signing.md) |
|
||||
| Authentification, rôles et permissions | [Guide rôles et permissions](auth-roles.md) |
|
||||
| Pages, routes et navigation UI | [Inventaire des pages UI](ui-pages.md) |
|
||||
| Hubs SignalR et Hangfire | [Guide SignalR](signalr-usage.md), [Guide Hangfire](hangfire-usage.md) |
|
||||
| Vidéo live, caméra et capacités livrées | [État produit courant](specs.md), [guide Docker Compose](docker-compose.md) |
|
||||
| Notifications | [Guide notifications](notifications.md) |
|
||||
| Métriques et alertes | [Guide Prometheus](metrics.md) |
|
||||
| PWA et validation appareils/déploiement | [Audit PWA](pwa.md) |
|
||||
| Backup et restauration | [Guide backup](../docker/backup/README.md) |
|
||||
|
||||
**Principe directeur du plan MVP de juillet 2026 (historique) :** implémenter d'abord le **plus simple et le plus important**.
|
||||
La **vidéo live** était alors prévue en dernier dans l'IHM; cette priorité appartient au plan ancien et ne décrit pas la feuille de route actuelle.
|
||||
**Principe :** On implémente d'abord le **plus simple et le plus important**.
|
||||
La **vidéo live** arrive en dernier dans l'IHM.
|
||||
|
||||
## Statut d'avancement (MVP — Juillet 2026)
|
||||
|
||||
@@ -172,14 +157,14 @@ Chaque commit build et push les images Docker.
|
||||
push → restore → build → unit tests → integration tests → docker build
|
||||
```
|
||||
|
||||
## État déclaré dans le plan historique (juillet 2026)
|
||||
## Implémentation actuelle
|
||||
|
||||
- **Forgejo Actions** (`./forgejo/workflows/ci.yml`) ✅
|
||||
- Build + Test sur push (branches main, develop) ✅
|
||||
- Docker build (central + agent) sur main ✅
|
||||
- PostgreSQL service pour les tests ✅
|
||||
|
||||
## Travaux à faire dans le plan historique (v2, juillet 2026)
|
||||
## À faire (v2)
|
||||
|
||||
- [ ] multi-arch Docker (linux/amd64 + arm64)
|
||||
- [ ] Push vers registry Docker
|
||||
@@ -246,7 +231,7 @@ UserRole { Admin, Supervisor, Viewer } ✅
|
||||
|
||||
Interfaces, DTOs, validateurs.
|
||||
|
||||
## État déclaré dans le plan historique (juillet 2026)
|
||||
## Implémentation actuelle
|
||||
|
||||
| Composant | Approche | Status |
|
||||
|-----------|----------|--------|
|
||||
@@ -281,7 +266,7 @@ La migration vers CQRS avec MediatR est prévue en v2 si le besoin se fait senti
|
||||
|
||||
Authentification AVANT d'exposer l'API.
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Fonctionnalité | Priorité | Status |
|
||||
|---|---|---|
|
||||
@@ -314,7 +299,7 @@ Authentification AVANT d'exposer l'API.
|
||||
|
||||
# Phase 7 — API Sites + Agent Tokens
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
@@ -334,7 +319,7 @@ Le token d'enregistrement est :
|
||||
|
||||
# Phase 8 — Agent Registration + Heartbeat
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
### Côté Central
|
||||
|
||||
@@ -373,7 +358,7 @@ Reporté après le MVP logiciel.
|
||||
|
||||
# Phase 10 — Camera Management API
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
@@ -405,7 +390,7 @@ Reportées en v2.
|
||||
|
||||
# Phase 15 — Hangfire Central
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Composant | Status |
|
||||
|-----------|--------|
|
||||
@@ -439,7 +424,7 @@ Reportées en v2.
|
||||
|
||||
# Phase 18 — Blazor UI
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Page | Route | Auth | Status |
|
||||
|------|-------|------|--------|
|
||||
@@ -494,7 +479,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
# Phase 22 — Dashboard KPI
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
| Widget | Source | Status |
|
||||
|--------|--------|--------|
|
||||
@@ -509,7 +494,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
# Phase 23 — Production Hardening
|
||||
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
## Implémenté
|
||||
|
||||
- [x] Health checks (/healthz, /readyz)
|
||||
- [x] Rate limiting (Auth: 10/min, API: 200/min)
|
||||
@@ -518,10 +503,10 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
- [x] Documentation API (Scalar UI)
|
||||
- [x] README avec architecture + setup
|
||||
|
||||
## Travaux ouverts dans le plan historique (juillet 2026)
|
||||
## À faire
|
||||
|
||||
- [ ] Serilog + Seq/GlitchTip
|
||||
- [x] Export des métriques Prometheus Central/Agent (`/metrics`); le scraping externe et les seuils d'alerte en exploitation restent à configurer et valider par l'opérateur.
|
||||
- [ ] Métriques Prometheus
|
||||
- [ ] Backup PostgreSQL automatisé
|
||||
- [ ] Backup RustFS (S3 → S3)
|
||||
- [ ] Tests de charge (k6)
|
||||
@@ -529,7 +514,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
---
|
||||
|
||||
## Résumé historique — Stats MVP (juillet 2026)
|
||||
## Résumé — Stats MVP
|
||||
|
||||
| Métrique | Valeur |
|
||||
|----------|--------|
|
||||
|
||||
+457
-36
@@ -1,43 +1,464 @@
|
||||
# Heimdall — Notifications
|
||||
# Heimdall — Notifications (Email + Gotify + Templates)
|
||||
|
||||
## État livré vérifié dans le dépôt
|
||||
**Stack :** `FluentEmail.Smtp`, `Gotify.NET`, `RazorTemplating` / `Scriban` (Markdown → HTML)
|
||||
|
||||
Les canaux externes déclarés par `NotificationChannel` sont `Email` et `Ntfy`;
|
||||
les notifications in-app sont consultables séparément dans le centre
|
||||
`/notifications`. L’interface utilise les endpoints authentifiés
|
||||
`/api/notifications` et le hub `/hubs/notifications` pour le compteur non lu.
|
||||
Voir [`signalr-usage.md`](signalr-usage.md) pour le contrat du hub.
|
||||
---
|
||||
|
||||
Les réglages administrateur se trouvent dans `/settings` (policy
|
||||
`Admin.Manage`) : configuration et test SMTP, configuration et test ntfy. Les
|
||||
préférences de l’utilisateur, dont l’adresse email, l’activation ntfy, le topic,
|
||||
les événements abonnés et les options de résumé, sont éditées dans `/profile`.
|
||||
La livraison email utilise `EmailService`; les notifications push utilisent
|
||||
`NtfyService` et Hangfire. `DailyDigestJob` envoie le résumé quotidien à 8 h;
|
||||
`WeeklyDigestJob` envoie le résumé hebdomadaire le lundi à 8 h, selon les
|
||||
expressions cron enregistrées dans `JobSetup`.
|
||||
## 1. Canaux de notification
|
||||
|
||||
Ces constats sont une vérification statique des sources, pas une validation de
|
||||
serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces
|
||||
services dépend de l’opérateur.
|
||||
| Canal | Usage | Priorité | Bibliothèque |
|
||||
|---|---|---|---|
|
||||
| **Email** (SMTP) | Notifications importantes, résumés | 🔴 Requis | `FluentEmail.Smtp` + `FluentEmail.Razor` |
|
||||
| **Gotify** (push) | Alertes temps réel, notifications rapides | 🟠 Recommandé | `Gotify.NET` |
|
||||
| **In-app** (SignalR) | Notifications silencieuses dans l'UI | 🟢 Requis | SignalR (intégré) |
|
||||
|
||||
Le traitement des notifications utilise une outbox durable avec des tentatives
|
||||
rejouables; une acceptation fournisseur suivie d'une perte de l'accusé de
|
||||
persistance peut produire un doublon. Une configuration et un transport
|
||||
simulés peuvent être vérifiés localement, mais ne prouvent pas la livraison vers
|
||||
un serveur externe ou un appareil utilisateur. Pour ntfy, les réponses succès,
|
||||
429 et 5xx sont réessayées avec délai borné; les erreurs permanentes restent en
|
||||
échec et les secrets ne doivent apparaître ni dans les réponses ni dans les
|
||||
journaux.
|
||||
---
|
||||
|
||||
Sources principales :
|
||||
## 2. SMTP — Configuration
|
||||
|
||||
- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs)
|
||||
- [`NotificationSettingsSection`](../src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor)
|
||||
- [`NotificationsPage`](../src/Heimdall.Web/Components/Pages/NotificationsPage.razor)
|
||||
- [`NotificationsController`](../src/Heimdall.Web/Controllers/NotificationsController.cs)
|
||||
- [`NtfyService`](../src/Heimdall.Infrastructure/Services/NtfyService.cs)
|
||||
- [`EmailService`](../src/Heimdall.Infrastructure/Services/EmailService.cs)
|
||||
- [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs)
|
||||
- [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs)
|
||||
- [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs)
|
||||
Configurable depuis l'UI Admin :
|
||||
|
||||
```csharp
|
||||
public class SmtpConfig
|
||||
{
|
||||
public string Host { get; set; } = "smtp.example.com";
|
||||
public int Port { get; set; } = 587;
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty; // chiffré
|
||||
public bool UseSsl { get; set; } = true;
|
||||
public string FromAddress { get; set; } = "heimdall@example.com";
|
||||
public string FromName { get; set; } = "Heimdall";
|
||||
}
|
||||
```
|
||||
|
||||
Stockée en base (table `AppConfig`), champ `Password` chiffré avec `IDataProtector`.
|
||||
|
||||
Test depuis l'UI : "Envoyer un email de test".
|
||||
|
||||
### Librairies NuGet
|
||||
|
||||
```
|
||||
dotnet add package FluentEmail.Smtp
|
||||
dotnet add package FluentEmail.Razor // templates Razor → HTML
|
||||
// ou
|
||||
dotnet add package Scriban // templates Markdown alternatif
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Gotify — Configuration
|
||||
|
||||
Gotify est un serveur de notification push self-hosted (Docker).
|
||||
|
||||
### Dépendances
|
||||
|
||||
```
|
||||
dotnet add package Gotify.NET
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
```csharp
|
||||
public class GotifyConfig
|
||||
{
|
||||
public string ServerUrl { get; set; } = "http://gotify:8080";
|
||||
public string AppToken { get; set; } = string.Empty; // chiffré
|
||||
public int Priority { get; set; } = 5; // 0-10
|
||||
}
|
||||
```
|
||||
|
||||
### UI Admin
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Notifications │
|
||||
│ │
|
||||
│ ┌──── Email (SMTP) ───────────────────────┐ │
|
||||
│ │ Serveur: [smtp.example.com ] │ │
|
||||
│ │ Port: [587 ] │ │
|
||||
│ │ SSL: [x] │ │
|
||||
│ │ Utilisateur: [notifications@... ] │ │
|
||||
│ │ Mot de passe: [******** ] │ │
|
||||
│ │ De: [heimdall@example.com ] │ │
|
||||
│ │ │ │
|
||||
│ │ [Tester la connexion] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──── Gotify ──────────────────────────────┐ │
|
||||
│ │ Serveur: [http://gotify:8080 ] │ │
|
||||
│ │ Token: [******** ] │ │
|
||||
│ │ Priorité: [5 ▼] │ │
|
||||
│ │ │ │
|
||||
│ │ [Tester la connexion] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──── Templates ───────────────────────────┐ │
|
||||
│ │ [Modifier les templates ▼] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Templates de notification (Markdown)
|
||||
|
||||
### Architecture
|
||||
|
||||
```text
|
||||
Base de données
|
||||
└── NotificationTemplate
|
||||
├── EventType (enum)
|
||||
├── Language ("fr", "en", "de"...)
|
||||
├── Channel ("email", "gotify", "inapp")
|
||||
├── Subject (string, avec variables)
|
||||
└── Body (string, Markdown avec variables)
|
||||
```
|
||||
|
||||
### Template Entity
|
||||
|
||||
```csharp
|
||||
public class NotificationTemplate
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public EventType EventType { get; set; } // PersonDetected, etc.
|
||||
public string Language { get; set; } = "fr"; // "fr", "en", "de"
|
||||
public string Channel { get; set; } = "email"; // "email", "gotify", "inapp"
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
public string BodyMarkdown { get; set; } = string.Empty;
|
||||
public bool IsDefault { get; set; } // template par défaut
|
||||
}
|
||||
```
|
||||
|
||||
### Variables disponibles dans les templates
|
||||
|
||||
| Variable | Description | Exemple |
|
||||
|---|---|---|
|
||||
| `{{SiteName}}` | Nom du site | "Entrepôt A" |
|
||||
| `{{CameraName}}` | Nom de la caméra | "Entrée principale" |
|
||||
| `{{EventType}}` | Type d'événement | "PersonDetected" |
|
||||
| `{{EventTime}}` | Horodatage | "14/07/2026 14:23:05" |
|
||||
| `{{EventTimeAgo}}` | Relatif | "il y a 2 minutes" |
|
||||
| `{{PersonName}}` | Nom de la personne | "Jean Dupont" |
|
||||
| `{{PersonPhotoUrl}}` | Lien photo | `https://heimdall/...` |
|
||||
| `{{VehiclePlate}}` | Plaque | "AA-123-XX" |
|
||||
| `{{VehicleModel}}` | Modèle | "Renault Clio" |
|
||||
| `{{SnapshotUrl}}` | Lien snapshot | `https://heimdall/...` |
|
||||
| `{{EventUrl}}` | Lien vers l'événement | `https://heimdall/events/...` |
|
||||
| `{{SiteUrl}}` | URL du Central | `https://heimdall.example.com` |
|
||||
| `{{AlertCount}}` | Nombre d'alertes (résumé) | "12" |
|
||||
|
||||
### Templates par défaut (fr)
|
||||
|
||||
```markdown
|
||||
=== PersonDetected — email — fr ===
|
||||
Subject: [Heimdall] Personne détectée — {{CameraName}}
|
||||
Body:
|
||||
**🔴 Alerte — Personne détectée**
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Site** | {{SiteName}} |
|
||||
| **Caméra** | {{CameraName}} |
|
||||
| **Date** | {{EventTime}} |
|
||||
| **Personne** | {{PersonName}} |
|
||||
|
||||
Voir l'événement : [{{EventUrl}}]({{EventUrl}})
|
||||
|
||||
---
|
||||
|
||||
=== PersonDetected — email — en ===
|
||||
Subject: [Heimdall] Person detected — {{CameraName}}
|
||||
Body:
|
||||
**🔴 Alert — Person detected**
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Site** | {{SiteName}} |
|
||||
| **Camera** | {{CameraName}} |
|
||||
| **Time** | {{EventTime}} |
|
||||
| **Person** | {{PersonName}} |
|
||||
|
||||
View event: [{{EventUrl}}]({{EventUrl}})
|
||||
|
||||
---
|
||||
|
||||
=== UnknownPerson — gotify — fr ===
|
||||
Subject: Visage inconnu — {{CameraName}}
|
||||
Body:
|
||||
Visage inconnu détecté sur {{CameraName}} ({{SiteName}})
|
||||
à {{EventTime}}.
|
||||
|
||||
---
|
||||
|
||||
=== DailySummary — email — fr ===
|
||||
Subject: [Heimdall] Résumé quotidien — {{SiteName}} — {{EventTime}}
|
||||
Body:
|
||||
**📊 Résumé quotidien — {{SiteName}}**
|
||||
|
||||
Période: {{DateStart}} → {{DateEnd}}
|
||||
|
||||
| Type | Nombre |
|
||||
|---|---|
|
||||
| Personnes détectées | {{PersonCount}} |
|
||||
| Dont connues | {{KnownPersonCount}} |
|
||||
| Dont inconnues | {{UnknownPersonCount}} |
|
||||
| Véhicules détectés | {{VehicleCount}} |
|
||||
| Événements total | {{TotalEventCount}} |
|
||||
|
||||
[Voir le tableau de bord]({{SiteUrl}})
|
||||
```
|
||||
|
||||
### Rendu du template
|
||||
|
||||
```csharp
|
||||
public class NotificationService : INotificationService
|
||||
{
|
||||
private readonly ScribanTemplateEngine _scriban;
|
||||
private readonly IRepository<NotificationTemplate> _templates;
|
||||
|
||||
public async Task<string> RenderAsync(
|
||||
EventType eventType,
|
||||
string language,
|
||||
string channel,
|
||||
Dictionary<string, object> variables)
|
||||
{
|
||||
// 1. Chercher template spécifique (eventType + language + channel)
|
||||
var template = await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == language &&
|
||||
t.Channel == channel);
|
||||
|
||||
// 2. Fallback : template par défaut de cette langue
|
||||
template ??= await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == language &&
|
||||
t.IsDefault);
|
||||
|
||||
// 3. Fallback : template anglais
|
||||
template ??= await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == "en" &&
|
||||
t.IsDefault);
|
||||
|
||||
if (template == null) return string.Empty;
|
||||
|
||||
// 4. Rendre avec Scriban
|
||||
var parsed = Template.Parse(template.BodyMarkdown);
|
||||
var result = await parsed.RenderAsync(variables);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### UI d'édition des templates
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Templates de notification [Langue: français ▼]
|
||||
│ │
|
||||
│ Événement: [Personne détectée ▼] Canal: [Email ▼] │
|
||||
│ │
|
||||
│ Sujet: │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ [Heimdall] Personne détectée — {{CameraName}} │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Corps (Markdown): │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ **🔴 Alerte — Personne détectée** │ │
|
||||
│ │ │ │
|
||||
│ │ | | | │ │
|
||||
│ │ |---|---| │ │
|
||||
│ │ | **Site** | {{SiteName}} | │ │
|
||||
│ │ | **Caméra** | {{CameraName}} | │ │
|
||||
│ │ │ │
|
||||
│ │ Voir : [{{EventUrl}}]({{EventUrl}}) │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ [Aperçu] [Réinitialiser] [Enregistrer] │
|
||||
│ │
|
||||
│ ── Aperçu ────────────────────────────────────────── │
|
||||
│ De: heimdall@example.com │
|
||||
│ À: test@example.com │
|
||||
│ Sujet: [Heimdall] Personne détectée — Entrée │
|
||||
│ ──────────────────────────────────────────────────── │
|
||||
│ 🔴 Alerte — Personne détectée │
|
||||
│ Site: Entrepôt A | Caméra: Entrée | Date: 14/07... │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Librairies
|
||||
|
||||
```
|
||||
dotnet add package Scriban # Moteur de templates Markdown
|
||||
dotnet add package Scriban.Signed # (si besoin strong name)
|
||||
// ou
|
||||
dotnet add package FluentEmail.Razor # Alternative Razor → HTML
|
||||
dotnet add package FluentEmail.Smtp # Envoi SMTP
|
||||
dotnet add package Gotify.NET # Gotify push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Types d'événements notifiables
|
||||
|
||||
| EventType | Email | Gotify | In-App (SignalR) | Template dispo |
|
||||
|---|---|---|---|---|
|
||||
| `PersonDetected` | ✅ | ✅ | ✅ | Oui |
|
||||
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | Oui |
|
||||
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | Oui |
|
||||
| `VehicleDetected` | ✅ | ✅ | ✅ | Oui |
|
||||
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | Oui |
|
||||
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | Non |
|
||||
| `CameraOffline` | ✅ | ✅ | ✅ | Oui |
|
||||
| `CameraOnline` | 🟡 | 🟡 | ✅ | Oui |
|
||||
| `DailySummary` | ✅ | ❌ | ❌ | Oui |
|
||||
| `WeeklySummary` | ✅ | ❌ | ❌ | Oui |
|
||||
|
||||
---
|
||||
|
||||
## 6. File d'attente des notifications (Hangfire)
|
||||
|
||||
Toutes les notifications passent par Hangfire pour :
|
||||
|
||||
1. Fiabilité (retry si échec SMTP)
|
||||
2. File d'attente (ne pas bloquer le thread de détection)
|
||||
3. Rate limiting (max N emails/min)
|
||||
|
||||
```csharp
|
||||
public class SendNotificationJob
|
||||
{
|
||||
[AutomaticRetry(Attempts = 3, DelaysInSeconds = [60, 300, 900])]
|
||||
public async Task ExecuteAsync(
|
||||
Guid eventId,
|
||||
string channel, // "email", "gotify", "inapp"
|
||||
string language,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var event = await _db.Events.FindAsync(new object[] { eventId }, ct);
|
||||
var variables = await BuildVariablesAsync(event, ct);
|
||||
|
||||
var rendered = await _notificationService.RenderAsync(
|
||||
event.Type, language, channel, variables);
|
||||
|
||||
await channel switch
|
||||
{
|
||||
"email" => await SendEmailAsync(event, rendered, ct),
|
||||
"gotify" => await SendGotifyAsync(event, rendered, ct),
|
||||
"inapp" => await SendInAppAsync(event, rendered, ct),
|
||||
_ => Task.CompletedTask
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Déclenchement depuis le pipeline IA
|
||||
|
||||
```csharp
|
||||
// Dans le handler de détection
|
||||
if (shouldNotify)
|
||||
{
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None));
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(event.Id, "gotify", user.Language, CancellationToken.None));
|
||||
}
|
||||
|
||||
// Notification in-app = temps réel via SignalR (pas Hangfire)
|
||||
await _signalrHub.SendEventAsync(event);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Configuration par User
|
||||
|
||||
Chaque utilisateur peut configurer ses notifications :
|
||||
|
||||
```csharp
|
||||
public class UserNotificationConfig
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public bool EmailEnabled { get; set; } = true;
|
||||
public bool GotifyEnabled { get; set; } = false;
|
||||
public string EmailAddress { get; set; } = string.Empty;
|
||||
public List<EventType> SubscribedEvents { get; set; } = new();
|
||||
public string Language { get; set; } = "fr";
|
||||
public bool DailyDigest { get; set; } = true;
|
||||
public bool WeeklyDigest { get; set; } = false;
|
||||
}
|
||||
```
|
||||
|
||||
UI User :
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Mes notifications │
|
||||
│ │
|
||||
│ Recevoir les notifications par : │
|
||||
│ [✅] Email : jean@example.com │
|
||||
│ [ ] Gotify │
|
||||
│ │
|
||||
│ M'alerter pour : │
|
||||
│ [✅] Personnes détectées │
|
||||
│ [✅] Visages inconnus │
|
||||
│ [ ] Véhicules │
|
||||
│ [✅] Caméra hors ligne │
|
||||
│ [ ] Mouvement seul │
|
||||
│ │
|
||||
│ Résumés : │
|
||||
│ [✅] Résumé quotidien │
|
||||
│ [ ] Résumé hebdomadaire │
|
||||
│ │
|
||||
│ Langue des notifications : [Français ▼] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Résumés quotidiens/hebdomadaires (Hangfire)
|
||||
|
||||
```csharp
|
||||
// Planifié dans Hangfire
|
||||
RecurringJob.AddOrUpdate<DailyDigestJob>(
|
||||
"daily-digest",
|
||||
j => j.ExecuteAsync(CancellationToken.None),
|
||||
Cron.Daily(8)); // 8h00
|
||||
|
||||
public class DailyDigestJob
|
||||
{
|
||||
public async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
var users = await _db.Users
|
||||
.Where(u => u.NotificationConfig.DailyDigest)
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var user in users)
|
||||
{
|
||||
var stats = await BuildDailyStatsAsync(user.Id, ct);
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(stats, "email", user.NotificationConfig.Language, ct));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests
|
||||
|
||||
```
|
||||
Notification is sent when person detected
|
||||
SMTP failure retries 3 times via Hangfire
|
||||
Gotify notification is sent correctly
|
||||
User can disable email notifications
|
||||
Template rendering replaces all variables
|
||||
Missing variable does not crash (Scriban safe)
|
||||
Template editing in UI saves correctly
|
||||
Template preview shows correct rendering
|
||||
Fallback to default template works
|
||||
Fallback to English template works
|
||||
Daily digest is generated at configured hour
|
||||
User language changes template language
|
||||
Admin can test SMTP connection from UI
|
||||
Admin can test Gotify connection from UI
|
||||
```
|
||||
@@ -1,12 +1,5 @@
|
||||
# Audit PWA du serveur Heimdall et plan de réalisation
|
||||
|
||||
L’acceptance locale du code source couvre le manifeste, les icônes publiques,
|
||||
le contenu exact du cache et la navigation hors ligne dans un navigateur.
|
||||
L’installation sur appareils, les mises à jour multi-onglets, le rollback,
|
||||
HTTPS de déploiement, la reprise après veille et l’usage hors connexion des
|
||||
données métier restent des validations distinctes; un test navigateur local ne
|
||||
prouve pas leur fonctionnement sur appareil ou déploiement réel.
|
||||
|
||||
Mis à jour le 24 octobre 2026. Périmètre : `src/Heimdall.Web`, API, authentification, hubs, notifications et déploiement. L’application native a été retirée à la demande du propriétaire ; la cible mobile est désormais l’application web existante. La PR #64 livre le manifeste, une icône SVG, l’enregistrement d’un service worker et une page hors connexion statique. Ce socle ne rend pas les écrans métier utilisables hors ligne : les composants Interactive Server dépendent toujours du serveur.
|
||||
|
||||
## Décision recommandée
|
||||
|
||||
+420
-80
@@ -1,111 +1,451 @@
|
||||
# SignalR : routes et contrats livrés
|
||||
# Heimdall — SignalR : Tous les hubs, events temps réel
|
||||
|
||||
Mis à jour le 13 novembre 2026. Ce guide décrit les hubs effectivement mappés par `src/Heimdall.Web/Program.cs`. Un message SignalR est un signal temps réel destiné aux connexions actuellement autorisées; l’API et la base de données restent la source de vérité pour charger l’état et récupérer ce qui a été manqué lors d’une déconnexion.
|
||||
**Stack :** SignalR (intégré à ASP.NET Core) — pas de lib externe supplémentaire
|
||||
|
||||
## Routes et authentification
|
||||
---
|
||||
|
||||
| Hub | Route | Authentification | Usage |
|
||||
## 1. Architecture générale
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ SIGNALR CENTRAL │
|
||||
│ │
|
||||
│ /hubs/events → Événements de détection │
|
||||
│ /hubs/streaming → Signaling WebRTC │
|
||||
│ /hubs/monitoring → Status (agents, caméras, alertes) │
|
||||
│ /hubs/notifications→ Notifications in-app │
|
||||
│ /hubs/admin → Changements config (admin broadcast) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Chaque hub est authentifié : JWT pour les utilisateurs humains, API Key
|
||||
pour les Agents. Les connexions sont groupées par Site et par User pour
|
||||
ne recevoir que les events pertinents.
|
||||
|
||||
---
|
||||
|
||||
## 2. Hub /hubs/events — Événements de détection
|
||||
|
||||
### Connexion
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class EventsHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
// L'User rejoint automatiquement les groupes de ses sites
|
||||
var userId = Context.User.GetUserId();
|
||||
var isAdmin = Context.User.IsInRole(AppRoles.Admin);
|
||||
|
||||
if (isAdmin)
|
||||
{
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, "all-sites");
|
||||
}
|
||||
else
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var siteId in siteIds)
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site-{siteId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Événements émis
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `ConfigHub` | `/hubs/config` | Clé API associée à un Agent enregistré | Envoyer des changements et commandes de configuration aux Agents |
|
||||
| `EventsHub` | `/hubs/events` | JWT humain | Recevoir les nouveaux événements des caméras auxquelles l’utilisateur a accès |
|
||||
| `MonitoringHub` | `/hubs/monitoring` | JWT humain | Recevoir les changements d’état des sites accessibles ou les signaux réservés aux Admins |
|
||||
| `NotificationsHub` | `/hubs/notifications` | JWT humain | Recevoir les notifications personnelles et le compteur non lu |
|
||||
| `AdminHub` | `/hubs/admin` | JWT humain avec rôle `Admin` | Recevoir les changements administratifs |
|
||||
| `EventCreated` | `EventDto` | Groupe du site | Nouvel événement de détection |
|
||||
| `PersonDetected` | `PersonEventDto` | Groupe du site | Personne reconnue |
|
||||
| `UnknownPerson` | `UnknownPersonDto` | Groupe du site + Admins | Visage inconnu |
|
||||
| `VehicleDetected` | `VehicleEventDto` | Groupe du site | Véhicule détecté |
|
||||
| `LicensePlateRead` | `PlateEventDto` | Groupe du site | Plaque lue |
|
||||
| `MotionDetected` | `MotionDto` | Groupe du site (silencieux) | Mouvement simple |
|
||||
|
||||
Il n’existe pas de route `/hubs/streaming` dans le routage actuel. Ce dépôt ne mappe donc pas de `StreamingHub` ni de signaling WebRTC à cette adresse. Les documents de spécification qui décrivent le streaming cible ne constituent pas un contrat d’API livré.
|
||||
### Exemple d'envoi
|
||||
|
||||
Les hubs humains exigent le schéma `JwtBearer`; le cookie Web seul n’authentifie pas ces connexions. Pour les transports SignalR qui ne peuvent pas envoyer un en-tête bearer, le gestionnaire JWT accepte `access_token` seulement sur les chemins `/hubs`. Le client Agent passe sa clé API via `AccessTokenProvider`; le gestionnaire `ApiKey` reconnaît ce jeton sur les routes SignalR. Les clients doivent laisser la bibliothèque SignalR gérer le handshake et ne jamais écrire le jeton dans une URL de page, un journal ou un exemple partagé.
|
||||
```csharp
|
||||
// Dans le handler de détection IA
|
||||
public class DetectionResultHandler
|
||||
{
|
||||
private readonly IHubContext<EventsHub> _hub;
|
||||
|
||||
La validation du JWT vérifie aussi la session de compte. L’authentification seule ne donne pas accès à tous les groupes : chaque méthode de jointure vérifie le type de demandeur et son périmètre. Les broadcasts réévaluent les droits persistés avant d’envoyer le message.
|
||||
public async Task HandleAsync(DetectionResult result, CancellationToken ct)
|
||||
{
|
||||
var dto = _mapper.Map<EventDto>(result);
|
||||
|
||||
## Méthodes invoquées par les clients
|
||||
// Envoyer au groupe du site
|
||||
await _hub.Clients
|
||||
.Group($"site-{result.SiteId}")
|
||||
.SendAsync("EventCreated", dto, ct);
|
||||
|
||||
| Hub | Méthode | Arguments | Contrôle appliqué |
|
||||
// Si visage inconnu, envoyer aussi aux admins
|
||||
if (result.EventType == EventType.UnknownPerson)
|
||||
{
|
||||
await _hub.Clients
|
||||
.Group("all-sites")
|
||||
.SendAsync("UnknownPerson", dto, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Hub /hubs/streaming — Signaling WebRTC
|
||||
|
||||
**Voir `docs/specs.md` §13 pour le protocole complet.**
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class StreamingHub : Hub
|
||||
{
|
||||
/// <summary>
|
||||
/// Agent : s'enregistre comme source de flux pour une caméra
|
||||
/// </summary>
|
||||
public async Task RegisterSource(Guid agentId, Guid cameraId)
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"camera-{cameraId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser : demande un flux pour une caméra
|
||||
/// </summary>
|
||||
public async Task RequestStream(Guid cameraId)
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"viewer-{cameraId}");
|
||||
|
||||
// Notifier l'Agent qu'un viewer arrive
|
||||
await Clients.Group($"camera-{cameraId}")
|
||||
.SendAsync("ViewerConnected", Context.ConnectionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Agent → Browser : offre SDP
|
||||
/// </summary>
|
||||
public async Task SendSdp(string sdp, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("SdpOffer", sdp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser → Agent : réponse SDP
|
||||
/// </summary>
|
||||
public async Task SendAnswer(string sdp, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("SdpAnswer", sdp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Échange ICE candidates (Agent ↔ Browser)
|
||||
/// </summary>
|
||||
public async Task SendIceCandidate(string candidate, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("IceCandidate", candidate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser : arrête de regarder le flux
|
||||
/// </summary>
|
||||
public async Task StopStreaming(Guid cameraId)
|
||||
{
|
||||
await Groups.RemoveFromGroupAsync(
|
||||
Context.ConnectionId, $"viewer-{cameraId}");
|
||||
|
||||
await Clients.Group($"camera-{cameraId}")
|
||||
.SendAsync("ViewerDisconnected", Context.ConnectionId);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Participants
|
||||
|
||||
| Type | Se connecte en tant que | Envoie | Reçoit |
|
||||
|---|---|---|---|
|
||||
| Config | `JoinAgentGroup` | `agentId` (GUID sous forme de chaîne) | La clé API doit correspondre à l’Agent demandé |
|
||||
| Events | `JoinSiteEvents` | `siteId` (GUID sous forme de chaîne) | Demandeur humain; abonnement limité aux caméras accessibles du site; refus si aucune caméra accessible |
|
||||
| Events | `LeaveSiteEvents` | `siteId` (GUID sous forme de chaîne) | Retire les abonnements caméra de cette connexion |
|
||||
| Monitoring | `JoinSiteMonitoring` | `siteId` (GUID sous forme de chaîne) | Demandeur humain ayant accès au site |
|
||||
| Monitoring | `LeaveSiteMonitoring` | `siteId` (GUID sous forme de chaîne) | Retire l’abonnement de cette connexion |
|
||||
| Monitoring | `JoinAdminBroadcast` | Aucun | Administrateur vérifié depuis l’état courant du compte |
|
||||
| Monitoring | `LeaveAdminBroadcast` | Aucun | Retire l’abonnement administratif de cette connexion |
|
||||
| Notifications | `JoinPersonalNotifications` | Aucun | Identité humaine résolue depuis l’état persistant du compte |
|
||||
| Notifications | `LeavePersonalNotifications` | Aucun | Retire l’abonnement personnel de la connexion |
|
||||
| Admin | `JoinAdminBroadcast` | Aucun | JWT de rôle `Admin`, puis vérification du rôle courant |
|
||||
| Admin | `LeaveAdminBroadcast` | Aucun | Retire l’abonnement de cette connexion |
|
||||
| **Agent** (SIPSorcery) | `RegisterSource` | SendSdp, SendIceCandidate | ViewerConnected, ViewerDisconnected, SdpAnswer, IceCandidate |
|
||||
| **Browser** (Blazor) | `RequestStream` | SendAnswer, SendIceCandidate, StopStreaming | SdpOffer, IceCandidate |
|
||||
|
||||
Ces méthodes de jointure sont les appels Hub destinés aux clients. Les méthodes `Notify...` visibles sur les classes de service de broadcast sont des méthodes internes utilisées par l’application; elles ne sont pas des méthodes RPC du Hub.
|
||||
---
|
||||
|
||||
## Messages envoyés par Central aux clients
|
||||
## 4. Hub /hubs/monitoring — Status temps réel
|
||||
|
||||
### Configuration des Agents — `/hubs/config`
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class MonitoringHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
var userId = Context.User.GetUserId();
|
||||
var isAdmin = Context.User.IsInRole(AppRoles.Admin);
|
||||
|
||||
| Message | Arguments | Destinataire |
|
||||
|---|---|---|
|
||||
| `SettingChanged` | `key`, `value` | Agent concerné ou Agents autorisés selon la portée du réglage |
|
||||
| `ConfigReload` | Aucun | Agents autorisés; leur client récupère la configuration complète par l’API |
|
||||
| `DiscoveryScanRequested` | Aucun | Agent concerné |
|
||||
| `AgentUpdateRequested` | Aucun | Agent concerné |
|
||||
| `ManualSnapshotRequested` | `cameraId`, `requestId` | Agent concerné |
|
||||
if (isAdmin)
|
||||
{
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-monitoring");
|
||||
}
|
||||
else
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
|
||||
L’Agent attend son enregistrement, ouvre `/hubs/config`, rejoint son groupe, puis charge la configuration par HTTP. Il écoute les changements, retente une connexion initiale en cas d’échec, utilise une reconnexion automatique et relit périodiquement la configuration. Après une reconnexion, le client Agent rejoint de nouveau son groupe.
|
||||
foreach (var siteId in siteIds)
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"monitoring-site-{siteId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Événements caméra — `/hubs/events`
|
||||
### Événements émis
|
||||
|
||||
| Message | Payload | Destinataire |
|
||||
|---|---|---|
|
||||
| `EventCreated` | `CameraEventResponse` | Connexions humaines autorisées à lire la caméra de l’événement |
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `AgentStatusChanged` | `AgentStatusDto` | Groupe monitoring du site | Agent online/offline |
|
||||
| `CameraStatusChanged` | `CameraStatusDto` | Groupe monitoring du site | Caméra online/offline |
|
||||
| `StorageUsageUpdated` | `StorageDto` | Admin | Espace RustFS mis à jour |
|
||||
| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU agent (ONNX Runtime) |
|
||||
| `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue |
|
||||
| `SystemHealthChanged` | `HealthDto` | Admin | Health check global |
|
||||
|
||||
Le client choisit un site avec `JoinSiteEvents`; Central calcule les caméras accessibles et s’abonne aux groupes caméra correspondants. Central revérifie l’accès au moment de chaque diffusion. Le Hub n’envoie pas de replay historique et ne diffuse pas de messages `PersonDetected`, `VehicleDetected`, `MotionDetected` ou `LicensePlateRead` distincts dans son code actuel; ces informations, lorsqu’elles existent, font partie du DTO d’événement chargé par l’API.
|
||||
### Exemple — Agent offline détecté
|
||||
|
||||
### Monitoring — `/hubs/monitoring`
|
||||
```csharp
|
||||
// Déclenché par le heartbeat timeout
|
||||
BackgroundJob.Schedule<AgentTimeoutJob>(
|
||||
j => j.ExecuteAsync(agentId, CancellationToken.None),
|
||||
TimeSpan.FromSeconds(90));
|
||||
|
||||
| Message | Payload | Destinataire |
|
||||
|---|---|---|
|
||||
| `AgentStatusChanged` | `{ agentId, status }` pour un site; `{ siteId, agentId, status }` pour le broadcast Admin | Utilisateurs autorisés du site et Administrateurs |
|
||||
| `CameraStatusChanged` | `{ cameraId, status }` pour un site; `{ siteId, cameraId, status }` pour le broadcast Admin | Utilisateurs autorisés du site et Administrateurs |
|
||||
| `StorageUsageUpdated` | `{ usedPercent, availableBytes }` | Administrateurs abonnés |
|
||||
| `GpuUsageUpdated` | `{ usedPercent, temperature }` | Administrateurs abonnés |
|
||||
| `JobStatusChanged` | `{ jobName, status, duration }` | Administrateurs abonnés |
|
||||
public class AgentTimeoutJob
|
||||
{
|
||||
public async Task ExecuteAsync(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var agent = await _db.Agents.FindAsync(new object[] { agentId }, ct);
|
||||
if (agent == null) return;
|
||||
|
||||
Une connexion doit appeler `JoinSiteMonitoring(siteId)` pour un site ou `JoinAdminBroadcast()` pour les signaux d’administration. Central vérifie le droit d’accès avant inscription et réévalue les destinataires lors de chaque diffusion.
|
||||
if (agent.LastHeartbeat < DateTime.UtcNow.AddSeconds(-90))
|
||||
{
|
||||
agent.Status = AgentStatus.Offline;
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
### Notifications personnelles — `/hubs/notifications`
|
||||
// Broadcast en temps réel
|
||||
await _hub.Clients
|
||||
.Group($"monitoring-site-{agent.SiteId}")
|
||||
.SendAsync("AgentStatusChanged", new AgentStatusDto
|
||||
{
|
||||
AgentId = agent.Id,
|
||||
Status = "Offline",
|
||||
LastHeartbeat = agent.LastHeartbeat
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Message | Payload | Quand |
|
||||
|---|---|---|
|
||||
| `UnreadCount` | `{ count }` | À la jointure personnelle et après un changement du compteur |
|
||||
| `NewNotification` | `NotificationDto` | Nouvelle notification de l’utilisateur |
|
||||
---
|
||||
|
||||
Le client Web (`NotificationsHubClient`) écoute ces messages et tente une reconnexion automatique. Si aucun JWT n’est disponible (par exemple une session cookie seule) ou si la connexion temps réel échoue, le badge et la page notifications peuvent recharger le compteur via HTTP lors de leur initialisation ou après une action; aucun timer de polling périodique n’est configuré. Rechargez l’état courant par l’API plutôt que de traiter le compteur local comme un historique durable.
|
||||
## 5. Hub /hubs/notifications — Notifications in-app
|
||||
|
||||
### Administration — `/hubs/admin`
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class NotificationsHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
// L'User rejoint son groupe de notifications personnel
|
||||
var userId = Context.User.GetUserId().ToString();
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"notif-{userId}");
|
||||
}
|
||||
|
||||
| Message | Payload | Quand |
|
||||
|---|---|---|
|
||||
| `ConfigChanged` | `{ key, oldValue, newValue }` | Réglage administratif modifié |
|
||||
| `CameraAdded` | `{ siteId, cameraId, cameraName }` | Caméra ajoutée |
|
||||
| `CameraRemoved` | `{ siteId, cameraId }` | Caméra supprimée |
|
||||
| `UserRoleChanged` | `{ userId, newRole }` | Rôle d’un utilisateur modifié |
|
||||
/// <summary>
|
||||
/// L'User marque une notification comme lue
|
||||
/// </summary>
|
||||
public async Task MarkAsRead(Guid notificationId)
|
||||
{
|
||||
await _db.Notifications
|
||||
.Where(n => n.Id == notificationId)
|
||||
.ExecuteUpdateAsync(setters =>
|
||||
setters.SetProperty(n => n.ReadAt, DateTime.UtcNow));
|
||||
}
|
||||
|
||||
Seuls les Administrateurs peuvent établir une connexion Admin et joindre le broadcast. Les destinataires sont revérifiés avant chaque message.
|
||||
/// <summary>
|
||||
/// L'User marque toutes ses notifications comme lues
|
||||
/// </summary>
|
||||
public async Task MarkAllAsRead()
|
||||
{
|
||||
var userId = Context.User.GetUserId();
|
||||
await _db.Notifications
|
||||
.Where(n => n.UserId == userId && n.ReadAt == null)
|
||||
.ExecuteUpdateAsync(setters =>
|
||||
setters.SetProperty(n => n.ReadAt, DateTime.UtcNow));
|
||||
|
||||
## Limites et maintenance
|
||||
// Mettre à jour le badge
|
||||
await Clients.Caller.SendAsync("UnreadCount", 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Les messages sont des signaux, pas une file durable : un client déconnecté doit relire l’état via l’API.
|
||||
- Les abonnements sont suivis par connexion et leur accès est réévalué à l’envoi; ne pas remplacer ce contrôle par un groupe global accessible à tout utilisateur.
|
||||
- Les hôtes et méthodes listés ici sont extraits de `Program.cs`, des classes `*Hub` et des services de broadcast. Les tests unitaires d’isolation ne valident ni un proxy WebSocket, ni une installation réelle.
|
||||
- Avant d’ajouter un hub ou un événement, mettre à jour les tests d’autorisation et ce guide dans le même changement.
|
||||
- Agent log levels sent to Central use the exact names `Trace`, `Debug`,
|
||||
`Information`, `Warning`, `Error`, and `Critical`; `Info` and `Warn` are not
|
||||
accepted aliases. Preserve these values in the Agent serialization and
|
||||
Central parser tests.
|
||||
### Événements émis
|
||||
|
||||
## Sources locales
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `NewNotification` | `NotificationDto` | Groupe notif-{userId} | Alerte pour cet user |
|
||||
| `UnreadCount` | `int` | Groupe notif-{userId} | Mise à jour badge |
|
||||
| `NotificationRead` | `Guid` | Groupe notif-{userId} | Confirmé par l'user |
|
||||
|
||||
- Routes : [`Program.cs`](../src/Heimdall.Web/Program.cs)
|
||||
- Hubs et diffusion : [`src/Heimdall.Web/Hubs`](../src/Heimdall.Web/Hubs)
|
||||
- Client Web notifications : [`NotificationsHubClient.cs`](../src/Heimdall.Web/Services/NotificationsHubClient.cs)
|
||||
- Client Agent configuration : [`ConfigReceiverService.cs`](../src/Heimdall.Agent/Services/ConfigReceiverService.cs)
|
||||
- Authentification API key : [`ApiKeyAuthenticationHandler.cs`](../src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs)
|
||||
- Tests d’accès et d’isolation : [`tests/Heimdall.Web.Tests/Hubs`](../tests/Heimdall.Web.Tests/Hubs)
|
||||
---
|
||||
|
||||
## 6. Hub /hubs/admin — Changements configuration
|
||||
|
||||
```csharp
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class AdminHub : Hub
|
||||
{
|
||||
/// <summary>
|
||||
/// L'Admin rejoint le groupe admin-broadcast
|
||||
/// </summary>
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, "admin-broadcast");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Événements émis
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `ConfigChanged` | `ConfigChangeDto` | Admin broadcast | Modification config globale |
|
||||
| `TemplateUpdated` | `TemplateDto` | Admin broadcast | Template notification modifié |
|
||||
| `UserRoleChanged` | `UserRoleDto` | Admin broadcast | Permission utilisateur modifiée |
|
||||
| `SiteUpdated` | `SiteDto` | Tous les users du site | Site modifié |
|
||||
| `CameraAdded` | `CameraDto` | Tous les users du site | Nouvelle caméra |
|
||||
| `CameraRemoved` | `Guid` | Tous les users du site | Caméra supprimée |
|
||||
|
||||
### Usage côté Blazor
|
||||
|
||||
```csharp
|
||||
// Dans le Layout ou un service injecté
|
||||
public class ConfigChangeListener : IDisposable
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl("/hubs/admin", options =>
|
||||
{
|
||||
options.AccessTokenProvider = () =>
|
||||
_tokenProvider.GetTokenAsync();
|
||||
})
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<ConfigChangeDto>("ConfigChanged", change =>
|
||||
{
|
||||
// Recharger la config concernée
|
||||
_invokeRequired(() =>
|
||||
{
|
||||
switch (change.Type)
|
||||
{
|
||||
case "site": _navigation.Refresh(); break;
|
||||
case "template": _notifService.ReloadTemplates(); break;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await _hub.StartAsync();
|
||||
}
|
||||
|
||||
public void Dispose() => _hub?.DisposeAsync();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Hub Agent — Communication Agent → Central
|
||||
|
||||
Les Agents se connectent aussi via SignalR (pas seulement HTTP REST) :
|
||||
|
||||
```csharp
|
||||
// Côté Agent
|
||||
public class AgentSignalRService : BackgroundService
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl($"{_centralUrl}/hubs/events", options =>
|
||||
{
|
||||
options.AccessTokenProvider = () =>
|
||||
Task.FromResult(_apiKey);
|
||||
})
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<CameraStatusDto>("CameraStatusRequest", async request =>
|
||||
{
|
||||
// Le Central demande le statut d'une caméra
|
||||
var status = await _cameraService.CheckStatusAsync(request.CameraId, ct);
|
||||
await _hub.InvokeAsync("CameraStatusResponse", status, ct);
|
||||
});
|
||||
|
||||
_hub.On<SnapshotRequest>("SnapshotRequest", async request =>
|
||||
{
|
||||
var snapshot = await _cameraService.CaptureSnapshotAsync(
|
||||
request.CameraId, ct);
|
||||
await _hub.InvokeAsync("SnapshotResponse", snapshot, ct);
|
||||
});
|
||||
|
||||
await _hub.StartAsync(ct);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Résumé — Tous les hubs
|
||||
|
||||
| Hub | Route | Auth | Clients | Usage |
|
||||
|---|---|---|---|---|
|
||||
| **EventsHub** | `/hubs/events` | JWT + API Key | Browser + Agent | Événements détection temps réel |
|
||||
| **StreamingHub** | `/hubs/streaming` | JWT + API Key | Browser + Agent | Signaling WebRTC |
|
||||
| **MonitoringHub** | `/hubs/monitoring` | JWT | Browser + Admin | Status agents, caméras, stockage |
|
||||
| **NotificationsHub** | `/hubs/notifications` | JWT | Browser | Notifications in-app |
|
||||
| **AdminHub** | `/hubs/admin` | JWT (Admin only) | Browser (Admin) | Broadcast changements config |
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests
|
||||
|
||||
```
|
||||
EventsHub emits EventCreated to correct site group
|
||||
EventsHub sends UnknownPerson to admin group too
|
||||
StreamingHub relays SDP offer from Agent to Browser
|
||||
StreamingHub relays ICE candidates bidirectionally
|
||||
MonitoringHub sends AgentStatusChanged on timeout
|
||||
MonitoringHub sends CameraStatusChanged on status change
|
||||
NotificationsHub sends NewNotification to correct user
|
||||
NotificationsHub MarkAsRead updates database
|
||||
NotificationsHub MarkAllAsRead resets badge to 0
|
||||
AdminHub ConfigChanged reaches all connected admins
|
||||
AdminHub CameraAdded reaches all users of the site
|
||||
Agent can connect to EventsHub with API key
|
||||
Agent receives SnapshotRequest and responds
|
||||
Hub groups are correctly created per site
|
||||
User without permission receives 403 on connect
|
||||
Disconnected users are removed from groups
|
||||
```
|
||||
+84
-107
@@ -1,18 +1,17 @@
|
||||
# Heimdall — Spécification technique
|
||||
|
||||
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Agent-local AI par défaut
|
||||
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Local AI
|
||||
|
||||
---
|
||||
|
||||
# 1. Vision
|
||||
|
||||
Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
Agent inference runs locally by default; a remote analysis broker is configurable.
|
||||
The default deployment does not require a managed cloud service.
|
||||
100% local AI, no cloud dependency, multi-site distributed architecture.
|
||||
|
||||
## Pourquoi Heimdall ?
|
||||
|
||||
- **Privacy first** — l'analyse ONNX est locale par défaut sur l'Agent; le mode broker distant est une option de déploiement distincte
|
||||
- **Privacy first** — tout l'IA tourne en local (ONNX Runtime sur agents + Ollama)
|
||||
- **Multi-site** — un Central + N Agents distants
|
||||
- **Économique** — pas d'abonnement cloud, hardware standard
|
||||
- **Pérenne** — .NET 10, Clean Architecture, open source
|
||||
@@ -23,14 +22,14 @@ The default deployment does not require a managed cloud service.
|
||||
|
||||
- Clean Architecture / CQRS / MédiatR
|
||||
- Multi-site : 1 serveur Central + N Agents Docker distants
|
||||
- Live vidéo : relais RTSP de l’Agent vers MediaMTX, lecture navigateur WHEP/WebRTC; mesurer la latence avant d’annoncer une cible
|
||||
- Analyse ONNX sur l'Agent : CPU par défaut, CUDA NVIDIA optionnel; AMD/Intel détectés pour l'inventaire ne signifient pas une inférence accélérée. Le mode broker distant est configurable, sans validation inter-sites revendiquée.
|
||||
- Rôles humains : Admin, Supervisor et Viewer; permissions par rôle, avec contrôle distinct du périmètre site/caméra sur chaque ressource
|
||||
- Live vidéo : WebRTC P2P (SIPSorcery), latence < 500 ms
|
||||
- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés)
|
||||
- Espace utilisateur : Admin (global) + User (site-scope)
|
||||
- Stockage : RustFS/S3 centralisé
|
||||
- Temps réel : SignalR (5 hubs)
|
||||
- Jobs planifiés : Hangfire (Central PGSQL + Agent InMemory)
|
||||
- Stack : .NET 10, Blazor MudBlazor, PostgreSQL
|
||||
- Déploiement auto-hébergé; aucun service cloud géré n'est requis par défaut
|
||||
- Pas de cloud, pas de dépendance externe
|
||||
|
||||
---
|
||||
|
||||
@@ -41,16 +40,16 @@ The default deployment does not require a managed cloud service.
|
||||
│ HEIMDALL CENTRAL │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
|
||||
│ │ API │ │ Web │ │ Workers │ │ MediaMTX │ │
|
||||
│ │ REST + │ │ Blazor │ │ Hangfire │ │ RustFS │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ Live media │ │
|
||||
│ │ API │ │ Web │ │ Workers │ │ Broker IA │ │
|
||||
│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ RustFS │ │
|
||||
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └──────────────┴─────────────┘ │
|
||||
│ │ PostgreSQL / RustFS │
|
||||
└─────────────────────────┼────────────────────────────────────────┘
|
||||
│
|
||||
HTTPS REST + SignalR (configuration/événements; pas le média vidéo)
|
||||
HTTPS REST + SignalR (signaling)
|
||||
│
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
@@ -58,37 +57,47 @@ The default deployment does not require a managed cloud service.
|
||||
│ Agent A │ │ Agent B │
|
||||
│ (site distant) │ │ (site distant) │
|
||||
│ │ │ │
|
||||
│ SIPSorcery │ │ SIPSorcery │
|
||||
│ WebRTC Peer │ │ WebRTC Peer │
|
||||
│ FFmpeg capture │ │ FFmpeg capture │
|
||||
│ RTSP publish │ │ RTSP publish │
|
||||
│ Hangfire memory │ │ Hangfire memory │
|
||||
└────────┬────────┘ └────────┬────────┘
|
||||
└─────────────┬────────┘
|
||||
│ RTSP(S) publication
|
||||
▼
|
||||
MediaMTX
|
||||
▲
|
||||
│ WHEP / WebRTC (lecture)
|
||||
Navigateur
|
||||
│ │
|
||||
P2P WebRTC (SRTP/H264) │
|
||||
◄══════════════════════════════►│
|
||||
Navigateur
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 4. Domain Model — Entités principales
|
||||
|
||||
Résumé des principaux types et propriétés représentatives; les noms suivent
|
||||
les entités actuelles dans `Heimdall.Domain` et ne remplacent pas leur modèle
|
||||
complet.
|
||||
```
|
||||
Site Agent Camera
|
||||
├── Id (Guid) ├── Id (Guid) ├── Id (Guid)
|
||||
├── Name ├── SiteId (FK) ├── SiteId (FK)
|
||||
├── Address ├── Name ├── Name
|
||||
├── Timezone ├── Hostname ├── Manufacturer
|
||||
├── Enabled ├── Version ├── Model
|
||||
└── Registration ├── Status ├── RtspUrl
|
||||
Token (hash) │ (Online/Offline/Err) ├── Status
|
||||
TokenPlain ├── LastHeartbeat ├── Capabilities
|
||||
TokenExpiresAt ├── PublicIp │ (Ptz, Audio, Motion)
|
||||
└── Capabilities ├── Credentials (encrypted)
|
||||
HasGpu, CpuCores └── StoragePolicyId
|
||||
|
||||
| Type | Propriétés et relations principales |
|
||||
|---|---|
|
||||
| `Site` | `Name`, `Address`, `Timezone`, `Enabled`, `RegistrationTokenHash`, `TokenExpiresAt`. Seul le hash du jeton d’enrôlement est persisté; la valeur brute est renvoyée lors de la création ou régénération. |
|
||||
| `Agent` | `SiteId`, `Name`, `Hostname`, `Version`, `Status`, `LastHeartbeat`, `ApiKeyHash`, `ApiKeyPrefix`; inclut aussi les relevés d’inventaire matériel et système. |
|
||||
| `Camera` | `SiteId`, `AgentId`, `Name`, `RtspUrl`, `SubRtspUrl`, `Status`, `Capabilities`, `StoragePolicyId`; les credentials résident dans l’entité liée `CameraCredentials`. |
|
||||
| `Person` / `KnownFace` | `Person.DisplayName`, `PhotoUrl`, `Category`, `IsWatchlisted`; les embeddings appartiennent aux entités liées `KnownFace`. |
|
||||
| `Vehicle` | `LicensePlate`, `PersonId`, `Make`, `Model`, `Color`. |
|
||||
| `CameraEvent` | `CameraId`, `AgentId`, `Type`, `Confidence`, `OccurredAt`, références de snapshot/stockage, `MetadataJson`; peut référencer une personne, un véhicule et un enregistrement. |
|
||||
Person Vehicle Event
|
||||
├── Id ├── Id ├── Id
|
||||
├── Name ├── LicensePlate ├── SiteId
|
||||
├── Photo ├── PersonId (FK) ├── CameraId
|
||||
├── IsUnknown ├── Make ├── Type (enum)
|
||||
├── FaceSamples ├── Model ├── Timestamp
|
||||
└── Notes └── Color ├── SnapshotPath
|
||||
└── Metadata (jsonb)
|
||||
|
||||
Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/Heimdall.Domain/Entities/Agent.cs), [`Camera`](../src/Heimdall.Domain/Entities/Camera.cs), [`Person` et `KnownFace`](../src/Heimdall.Domain/Entities/Person.cs), [`Vehicle`](../src/Heimdall.Domain/Entities/Vehicle.cs), [`CameraEvent`](../src/Heimdall.Domain/Entities/CameraEvent.cs).
|
||||
Enum: CameraStatus, AgentStatus, EventType, StorageProvider
|
||||
Enum: GpuAcceleration, ThemeMode
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -100,23 +109,16 @@ Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/He
|
||||
|
||||
- Création de Site avec token d'enregistrement Agent
|
||||
- Agent bootstrap : token → register → heartbeat
|
||||
- L'Agent récupère une configuration caméra complète, en vérifie le digest et
|
||||
accuse réception de cette version; après reconnexion il rejoint son groupe et
|
||||
recharge l'instantané complet, y compris les affectations supprimées.
|
||||
- L'état demandé par Central, la version accusée par l'Agent et l'arrêt effectif
|
||||
du processus FFmpeg sont distincts. Les changements activation, désactivation,
|
||||
réaffectation et redémarrage doivent vérifier le digest appliqué et l'arrêt du
|
||||
processus séparément; un statut seul ne prouve pas l'arrêt du flux.
|
||||
- Cycle de vie : Registration → Heartbeat (30s) → Offline (90s)
|
||||
- API dédiée : POST /api/agents/register
|
||||
- Voir `docs/auth-roles.md` §11 pour le détail complet
|
||||
|
||||
## Authentification — `docs/auth-roles.md`
|
||||
|
||||
- 3 rôles : Admin, Supervisor et Viewer; les permissions viennent du rôle et l'accès aux sites/caméras est vérifié séparément selon la ressource
|
||||
- 2 types d'utilisateurs : Admin (tout) + User (N sites)
|
||||
- ASP.NET Core Identity + JWT + Refresh tokens
|
||||
- Permissions par Policy : Camera.Read, Admin.Manage...
|
||||
- Accès aux ressources : les services d’accès vérifient le périmètre site/caméra pour chaque opération; voir `docs/auth-roles.md`
|
||||
- Scope site : un User ne voit que ses sites assignés
|
||||
- Visibilité UI adaptée au rôle (menus, boutons)
|
||||
- Voir `docs/auth-roles.md` pour le détail complet
|
||||
|
||||
@@ -124,56 +126,30 @@ Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/He
|
||||
|
||||
- ONVIF WS-Discovery (même VLAN) + discovery manuelle (IP)
|
||||
- Protocole Imou : activation RTSP manuelle requise
|
||||
- Analyse d'images : YOLO/ONNX sur Agent, CPU par défaut; CUDA NVIDIA optionnel avec fallback CPU. Les détections de matériel AMD/Intel alimentent l'inventaire et ne prouvent pas une inférence accélérée.
|
||||
- Mode d'analyse distant : configurable avec un broker et repli local si celui-ci est inaccessible; aucun déploiement inter-sites n'est validé par cette configuration seule.
|
||||
- FFmpeg capture : RTSP → H264, GPU auto-détection (NVENC/QSV/VAAPI/CPU)
|
||||
- AI Pipeline : Agent CPU (YOLOv8 nano) → analyse IA sur agents GPU (ONNX Runtime, local ou via broker inter-sites)
|
||||
- Détection : objets, visages, plaques (LPR), véhicules
|
||||
- Stockage credentials caméras chiffré (IDataProtector)
|
||||
|
||||
## Streaming live — parcours logiciel livré, validation externe partielle
|
||||
## Streaming live — `docs/signalr-usage.md`
|
||||
|
||||
Le parcours actuel utilise le relay Agent→MediaMTX en RTSP(S), puis WHEP/WebRTC
|
||||
entre le navigateur et MediaMTX. Central fournit des sessions courtes et autorise
|
||||
les lectures selon les droits sur la caméra; SignalR ne transporte pas le média
|
||||
ni le signaling SDP/ICE de ce parcours. L’application n’expose pas de hub
|
||||
`/hubs/streaming`. Les URL et ICE servers dépendent de la configuration de
|
||||
l’installation. La négociation synthétique dispose d’une preuve séparée, mais
|
||||
cela ne valide ni une caméra physique, ni l’accès depuis un réseau externe, ni
|
||||
une latence cible en déploiement; voir #161 et #341.
|
||||
|
||||
Le relay compare la source RTSP effective (sous-flux s’il est configuré, sinon
|
||||
flux principal) et redémarre le processus après un changement de source pour le
|
||||
même CameraId. Ce comportement est couvert par les tests Agent et l’acceptance
|
||||
locale de #355; aucune caméra réelle ni réseau externe n’a été validé.
|
||||
|
||||
## Inference et jobs Agent
|
||||
|
||||
Les travaux d'analyse utilisent uniquement des types autorisés à la frontière
|
||||
Web, dans le planificateur Central et dans le parseur Agent. La détection
|
||||
d'objets est plafonnée à 500 résultats dans l'ordre du modèle; la détection de
|
||||
personne filtre la classe COCO 0 avant plafonnement. La classification véhicule
|
||||
retient les classes COCO 2, 3, 5 et 7, dans l'ordre d'origine. Le détecteur de
|
||||
mouvement CPU compare deux images du flux actif séparées de 500 ms, redimensionne
|
||||
à 32×18, compare la luminance normalisée à 0,12 par pixel et déclenche à partir
|
||||
de 2 % de pixels changés. Le résultat porte l'étiquette `motion`, des limites
|
||||
normalisées de zone et le ratio de pixels changés comme confiance. L'éclairage
|
||||
et les vibrations peuvent produire de faux positifs; ces seuils doivent être
|
||||
mesurés sur des caméras représentatives avant de dépendre des alertes.
|
||||
- WebRTC P2P via SIPSorcery (latence < 500ms)
|
||||
- Signaling via SignalR hub /hubs/streaming (SDP + ICE)
|
||||
- SFU (MediaMTX) pour multi-utilisateurs (>2 viewers)
|
||||
- Blazor Server + JS module autonome pour <video>
|
||||
- Voir `docs/signalr-usage.md` §3 pour le protocole complet
|
||||
|
||||
## Temps réel (SignalR) — `docs/signalr-usage.md`
|
||||
|
||||
Résumé des cinq hubs actuellement mappés :
|
||||
|
||||
| Hub | Route | Usage |
|
||||
|---|---|---|
|
||||
| Config | `/hubs/config` | Configuration et commandes Agent |
|
||||
| Events | `/hubs/events` | Événements détection temps réel |
|
||||
| Streaming | `/hubs/streaming` | Signaling WebRTC |
|
||||
| Monitoring | `/hubs/monitoring` | Status agents, caméras |
|
||||
| Notifications | `/hubs/notifications` | Notifications in-app |
|
||||
| Admin | `/hubs/admin` | Broadcast changements config |
|
||||
|
||||
Voir [`docs/signalr-usage.md`](signalr-usage.md) pour les méthodes invocables,
|
||||
messages émis et contrôles d’accès. Ce résumé ne reproduit ni le code ni toutes
|
||||
les clés de groupe internes.
|
||||
Voir `docs/signalr-usage.md` pour tous les events, groupes, code.
|
||||
|
||||
## Jobs planifiés (Hangfire) — `docs/hangfire-usage.md`
|
||||
|
||||
@@ -186,18 +162,17 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
|
||||
|
||||
## Notifications — `docs/notifications.md`
|
||||
|
||||
Les notifications in-app sont consultables dans `/notifications`. Les canaux
|
||||
externes livrés sont l’email SMTP et ntfy; les administrateurs configurent et
|
||||
testent ces services dans `/settings`, tandis que les préférences individuelles
|
||||
et les options de résumé se règlent dans `/profile`. Les digests quotidien et
|
||||
hebdomadaire sont planifiés par les jobs Hangfire actuels. Voir
|
||||
[`docs/notifications.md`](notifications.md) pour les endpoints, les contrôles
|
||||
d’accès, la cadence et les limites de validation SMTP/ntfy.
|
||||
- Email SMTP (FluentEmail), Gotify push
|
||||
- Templates Markdown avec Scriban, variables, fallback i18n
|
||||
- Templates éditables depuis l'UI Admin
|
||||
- File Hangfire avec retry (3 tentatives)
|
||||
- Résumés quotidiens/hebdomadaires planifiés
|
||||
- Voir `docs/notifications.md` pour le détail complet
|
||||
|
||||
## Stockage & Rétention — `docs/hangfire-usage.md`
|
||||
|
||||
- RustFS (par défaut), S3-compatible (AWS S3, MinIO), Local (fallback)
|
||||
- L'Agent découpe le flux RTSP principal en segments MP4 dans son spool local, puis envoie les segments terminés au Central via l'API; le Central les écrit dans le fournisseur de stockage configuré
|
||||
- L'Agent écrit les segments directement sur S3
|
||||
- Retention configurable par caméra (7-90 jours)
|
||||
- Hangfire purge les fichiers expirés
|
||||
- Voir `docs/hangfire-usage.md` §2 pour les jobs
|
||||
@@ -205,18 +180,15 @@ d’accès, la cadence et les limites de validation SMTP/ntfy.
|
||||
## Interface Web (Blazor) — `docs/ui-pages.md`
|
||||
|
||||
- MudBlazor, Interactive Server Rendering
|
||||
- Parcours documentés : authentification, dashboard, sites/caméras, personnes,
|
||||
événements, alertes/notifications, profil et administration. Les routes et
|
||||
pages détaillées sont recensées dans [`docs/ui-pages.md`](ui-pages.md);
|
||||
l’administration est répartie entre pages protégées et ne correspond pas à
|
||||
une route unique `/admin`.
|
||||
- Live vidéo depuis le détail caméra : publication RTSP Agent→MediaMTX et lecture WHEP/WebRTC via `live-view.js`
|
||||
- 8 pages : Login, Dashboard, Sites, Cameras, Persons, Events, Admin, Alertes
|
||||
- Live vidéo via module JS autonome (WebRTC)
|
||||
- Thème Light/Dark/Auto, localisation française
|
||||
- Voir `docs/ui-pages.md` pour les maquettes ASCII complètes
|
||||
|
||||
## Application web installable — PWA
|
||||
|
||||
Le client natif est retiré. Le socle PWA livré comprend le manifeste, le service worker borné et la page d’information hors connexion. Les écrans métier restent dépendants d’une connexion Interactive Server; Web Push et consultation métier hors ligne ne sont pas implémentés. Les validations appareils/déploiement restent à faire.
|
||||
Le client natif est retiré. La cible est le serveur Blazor accessible sur mobile et installable depuis le navigateur.
|
||||
Installation, page hors connexion, reprise de session et Web Push doivent être implémentés ; le rendu Interactive Server nécessite une connexion pour les fonctions métier.
|
||||
Voir [l’audit et le plan PWA](pwa.md) pour les écarts, critères de réception et l’option de consultation hors ligne ultérieure.
|
||||
|
||||
---
|
||||
@@ -230,26 +202,31 @@ services:
|
||||
heimdall-api: # ASP.NET Core API + SignalR
|
||||
heimdall-web: # Blazor Web App (MudBlazor)
|
||||
heimdall-worker: # Hangfire jobs (PostgreSQL)
|
||||
heimdall-agent: # Agent .NET + FFmpeg relay (Hangfire InMemory)
|
||||
heimdall-agent: # SIPSorcery + FFmpeg (InMemory Hangfire)
|
||||
postgresql: # Base de données
|
||||
rustfs: # Stockage S3 (enregistrements)
|
||||
# Analyse ONNX exécutée par l'Agent (CPU par défaut, CUDA NVIDIA optionnel); voir docs/gpu-runtime.md
|
||||
ollama: # service optionnel; URL configurable et disponibilité sondée, aucune génération LLM livrée
|
||||
mediamtx: # Serveur média RTSP/WHEP (optionnel, live vidéo)
|
||||
# IA lourde (détection, visages, LPR) : agents GPU ONNX Runtime — pas de service central
|
||||
ollama: # LLM local (résumés)
|
||||
mediamtx: # SFU WebRTC (optionnel, multi-user)
|
||||
coturn: # TURN relay (optionnel, double NAT)
|
||||
```
|
||||
|
||||
## GPU et inférence
|
||||
## GPU Passthrough
|
||||
|
||||
L'image et le chemin Agent par défaut utilisent `CPUExecutionProvider`. Une
|
||||
image amd64 NVIDIA/CUDA signée est proposée en option; si CUDA ne peut pas
|
||||
initialiser une session, l'Agent revient au CPU. L'inventaire peut détecter du
|
||||
matériel NVIDIA, AMD et Intel, mais les overlays AMD/Intel ne fournissent pas
|
||||
de backend ONNX correspondant. La détection de capacités d'encodage dans
|
||||
l'inventaire n'implique pas leur utilisation par les parcours vidéo. Voir
|
||||
[`docs/gpu-runtime.md`](gpu-runtime.md) pour les variantes et les preuves
|
||||
disponibles. L'exécution CUDA sur matériel réel et les performances par flux
|
||||
restent à mesurer; aucune capacité chiffrée n'est annoncée ici.
|
||||
| Conteneur | GPU | Docker |
|
||||
|---|---|---|
|
||||
| `heimdall-agent` (GPU) | NVIDIA/AMD/Intel | profiles compose GPU : nvidia / rocm (/dev/kfd,/dev/dri) / vaapi (/dev/dri) |
|
||||
| `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `--device /dev/dri:/dev/dri` |
|
||||
| `ollama` | NVIDIA (opt) | `--gpus all` |
|
||||
|
||||
Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
|
||||
|
||||
## Estimation capacité CPU (Intel i5-10gen)
|
||||
|
||||
| Mode | 720p | 1080p | 4K |
|
||||
|---|---|---|---|
|
||||
| CPU (libx264) | 8 flux | 4 flux | 1 flux |
|
||||
| GPU (NVENC/QSV) | 20+ flux | 12+ flux | 4+ flux |
|
||||
|
||||
---
|
||||
|
||||
@@ -259,7 +236,7 @@ restent à mesurer; aucune capacité chiffrée n'est annoncée ici.
|
||||
- Serilog (structure logging)
|
||||
- OpenTelemetry ready
|
||||
- Sentry SDK compatible GlitchTip
|
||||
- Health checks Central : `/healthz` est une liveness toujours `200`; `/readyz` vérifie PostgreSQL et le stockage actif (`200` si healthy, sinon `503`); `/health/live` vérifie PostgreSQL plus le backend IA configuré (CodeProject.AI ou Ollama; l'absence de backend IA est valide) et renvoie `503` si un check n'est pas healthy. Côté Agent, `/healthz` agrège `agent_health` et `live` (`Degraded` → `200`, `Unhealthy` → `503`); `/health/live` expose la dégradation du pipeline IA (`200` healthy, sinon `503`). Aucun health check Central distinct du broker distant n'est enregistré; voir [`HealthController`](../src/Heimdall.Web/Controllers/HealthController.cs), [`AiHealthCheck`](../src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs) et [`Agent Program`](../src/Heimdall.Agent/Program.cs).
|
||||
- Healthchecks (API, Agent, DB, RustFS, Broker IA, Ollama)
|
||||
- Tests : xUnit + Shouldly + NSubstitute + bUnit + Testcontainers
|
||||
|
||||
---
|
||||
|
||||
+70
-97
@@ -226,72 +226,19 @@ Dashboard shows agent offline state
|
||||
│ │ │ Token: a1b2c3d4-... (caché après création)│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ 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 │ │
|
||||
│ │ Commande Docker à exécuter sur le site distant : │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ demander URL/token puis installer [⧉]│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ Lancer │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ sudo systemctl start heimdall-agent [⧉]│ │ │
|
||||
│ │ │ docker run -e HEIMDALL_CENTRAL_URL=... │ │ │
|
||||
│ │ │ -e HEIMDALL_SITE_TOKEN=... │ │ │
|
||||
│ │ │ heimdall/agent:latest │ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [× Révoquer le token] │ │
|
||||
│ │ [Copier la commande] [× Révoquer le token] │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
Seuls Linux, Windows et Docker sont proposés. Les commandes natives exigent
|
||||
une release signée disponible; les commandes Docker utilisent l'image signée
|
||||
épinglée par digest et `pull_policy: always`. Les valeurs d'enrôlement ne sont
|
||||
pas incluses dans les commandes Linux: l'installateur les demande à l'exécution
|
||||
et les transmet via des fichiers temporaires protégés, supprimés à la sortie.
|
||||
Les textes visibles proviennent des ressources de localisation. Vérifier aussi
|
||||
les états sans release signée ou sans image GPU publiée.
|
||||
|
||||
```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
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ demande URL et token masqué, puis installe [⧉]│
|
||||
└──────────────────────────────────────────────┘
|
||||
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 les métadonnées d'image vérifiées de la release et épingle l'image CPU ou GPU sur son digest signé (`repository@sha256:digest`). Compose utilise `pull_policy: always` pour récupérer exactement ce digest; Docker Run utilise `--pull always`. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
|
||||
|
||||
La commande Linux ne contient ni l'URL Central ni le token du site. À son exécution, elle demande l'URL HTTPS puis le token sans afficher sa saisie, place les valeurs dans des fichiers temporaires protégés et télécharge les scripts par HTTPS avant leur exécution. L'installateur exige les fichiers d'enrôlement protégés et conserve le token comme credential systemd.
|
||||
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, `MudSnackbar` (copié)
|
||||
|
||||
### États — Détail Site
|
||||
|
||||
@@ -307,37 +254,41 @@ La commande Linux ne contient ni l'URL Central ni le token du site. À son exéc
|
||||
|
||||
## P4 — Caméras
|
||||
|
||||
### Live view — lecteur intégré au détail caméra (parcours logiciel livré)
|
||||
### Live View — P4a (DERNIÈRE page implémentée)
|
||||
|
||||
**Route** : `/cameras/{id}` (page détail, section Live)
|
||||
**Auth** : session utilisateur requise; l’API vérifie aussi l’accès à la caméra
|
||||
**Route** : `/cameras/{id}/live`
|
||||
**Auth** : Requise
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────┐
|
||||
│ Live [Regarder le direct] │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ <video> HTML natif, autoplay, playsinline │ │
|
||||
│ │ lecture navigateur via WHEP/WebRTC │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└────────────────────────────────────────────────────┘
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ 📷 Entrée — Live [Plein écran]│
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ FLUX VIDÉO WEBRTC │ │
|
||||
│ │ │ │
|
||||
│ │ <video> élément HTML natif │ │
|
||||
│ │ │ │
|
||||
│ │ ⏳ Loading... | 🟢 Live | 🔴 Offline │ │
|
||||
│ │ │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Qualité: [1080p ▼] [📷 Snapshot] [⏺️ Enregistrer]│
|
||||
│ │
|
||||
│ ┌───Événements récents (cette caméra)────────────┐ │
|
||||
│ │ 🟢 14:23 — Personne détectée │ │
|
||||
│ │ 🟡 14:20 — Véhicule détecté │ │
|
||||
│ └────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Timeline: [══════■══════■══════════■══════] │
|
||||
│ 14:00 14:10 14:20 14:30 Maintenant │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Le bouton est désactivé lorsque l’état caméra n’est pas `Online`; il démarre ou
|
||||
arrête le lecteur. Le composant importe `wwwroot/js/live-view.js`, demande une
|
||||
session de lecture à `POST /api/live-media/cameras/{cameraId}/session`, puis
|
||||
négocie WHEP avec l’URL et le jeton temporaires retournés par Central. L’Agent
|
||||
publie le flux caméra vers MediaMTX en RTSP(S). À l’arrêt ou à la destruction du
|
||||
composant, le client ferme la connexion WebRTC et libère la session.
|
||||
|
||||
La route WHEP, les ICE servers et les paramètres de publication dépendent de la
|
||||
configuration Central/MediaMTX. Une recette avec média synthétique prouve le
|
||||
parcours logiciel seulement; elle ne prouve pas l’accès d’une caméra physique,
|
||||
le TURN depuis Internet ni un budget de latence en exploitation (voir #161 et
|
||||
#341). La maquette ci-dessus représente le lecteur livré; le choix de qualité,
|
||||
l’enregistrement depuis le lecteur et une timeline de lecture ne sont pas des
|
||||
contrôles présents dans ce panneau. Changer l’URL RTSP d’une caméra tout en
|
||||
gardant le même ID et la même assignation peut laisser l’ancien relay actif
|
||||
jusqu’au renouvellement de sa session; cette limite Agent est suivie dans #355.
|
||||
**Attention Blazor Server + WebRTC** : Voir §26 de la spec — le flux WebRTC
|
||||
est géré par un module JS autonome (`wwwroot/js/liveView.js`) qui survit
|
||||
aux reconnexions Blazor. Le `<video>` est un élément HTML standard,
|
||||
pas un composant Blazor.
|
||||
|
||||
### Détail Caméra — P4b
|
||||
|
||||
@@ -572,15 +523,41 @@ Matrice complète des 15 permissions système avec coches par rôle
|
||||
|
||||
---
|
||||
|
||||
## P14 — Administration centralisée (ancienne maquette retirée)
|
||||
## P14 — Administration (legacy)
|
||||
|
||||
La page d’accueil `/admin` et les onglets regroupés dans cette maquette ne sont
|
||||
pas mappés dans le runtime. Les capacités d’administration sont réparties sur
|
||||
les pages actuelles : `/users`, `/admin/roles`, `/admin/groups`,
|
||||
`/admin/claims`, `/admin/agents`, `/admin/api-keys`, `/settings` et `/hangfire`.
|
||||
Les notifications et la configuration des releases sont des sections de
|
||||
`/settings`, pas des sous-pages d’un dashboard `/admin`. Voir
|
||||
[`docs/auth-roles.md`](auth-roles.md) pour les rôles, routes et policies actuels.
|
||||
**Route** : `/admin`
|
||||
**Auth** : Requise + `Admin.Manage`
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Administration │
|
||||
│ │
|
||||
│ ┌──── Tabs ───────────────────────────────────────┐ │
|
||||
│ │ Utilisateurs | Rôles | Clés API | Jobs │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Utilisateurs] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Jean Dupont Admin jean@ex.com [×] │ │ │
|
||||
│ │ │ Marie Martin Superviseur marie@ex.com [×] │ │ │
|
||||
│ │ │ Paul View paul@ex.com [×] │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Clés API] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Key-1 Camera.Read 01/01/2026 Actif [×] │ │ │
|
||||
│ │ │ Key-2 Camera.Write 15/06/2026 Expiré [×] │ │ │
|
||||
│ │ │ Key-3 Person.Read 01/07/2026 Actif [×] │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Jobs Hangfire] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Retention Check Tous les jours 🟢 OK │ │ │
|
||||
│ │ │ S3 Cleanup Tous les jours 🟢 OK │ │ │
|
||||
│ │ │ Unknown Faces Clean Toutes les sem. 🟢 OK │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -605,10 +582,6 @@ Les notifications et la configuration des releases sont des sections de
|
||||
Accessible depuis `MudBadge` dans la barre de navigation.
|
||||
Les événements arrivent en temps réel via SignalR.
|
||||
|
||||
### Source des releases Heimdall
|
||||
|
||||
Dans **Réglages**, l’administrateur saisit uniquement l’URL HTTPS publique de Forgejo. Heimdall affiche l’API `.../api/v1/repos/arnaud.dartois/Heimdall/releases/latest` calculée automatiquement en lecture seule. L’URL publique est éditable; le propriétaire, le dépôt et le chemin de release ne le sont pas. Le blocage « aucune release signée utilisable » reste affiché tant que l’API ne retourne pas une release avec clé, manifeste signé, signature et assets Agent.
|
||||
|
||||
### Configuration notifications
|
||||
|
||||
```text
|
||||
|
||||
@@ -234,7 +234,6 @@ try {
|
||||
"Agent__SiteToken=$SiteToken",
|
||||
"Agent__AgentName=$AgentName",
|
||||
"Agent__StateDirectory=$stateDirectory",
|
||||
"MODEL_PATH=$(Join-Path $releasePath 'models\yolov8n.onnx')",
|
||||
"Agent__UpdateInstallRoot=$releaseRoot",
|
||||
"Agent__UpdatePublicKeyPath=$publicKeyPath",
|
||||
"Agent__UpdateSupervisorPath=$supervisorPath",
|
||||
|
||||
@@ -1,25 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# install-agent.sh — Heimdall Agent installer for Linux
|
||||
set -euo pipefail
|
||||
CENTRAL_URL="" SITE_TOKEN="" CENTRAL_URL_FILE="" SITE_TOKEN_FILE="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
|
||||
CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
|
||||
INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall"
|
||||
while [[ $# -gt 0 ]]; do case "$1" in --central-url-file) CENTRAL_URL_FILE="$2"; shift 2;; --site-token-file) SITE_TOKEN_FILE="$2"; shift 2;; --central-url|--site-token) echo "Error: pass enrollment settings through protected files, not command-line values" >&2; exit 1;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url-file PATH --site-token-file PATH [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
|
||||
read_protected_value() {
|
||||
local path="$1" label="$2" mode
|
||||
[[ -n "$path" && -f "$path" && ! -L "$path" ]] || { echo "Error: $label must reference a regular protected file" >&2; exit 1; }
|
||||
mode=$(stat -c '%a' "$path")
|
||||
(( (8#$mode & 077) == 0 )) || { echo "Error: $label file must not be accessible by group or others" >&2; exit 1; }
|
||||
cat -- "$path"
|
||||
}
|
||||
[[ -n "$CENTRAL_URL_FILE" && -n "$SITE_TOKEN_FILE" ]] || { echo "Error: --central-url-file and --site-token-file are required" >&2; exit 1; }
|
||||
CENTRAL_URL="$(read_protected_value "$CENTRAL_URL_FILE" 'Central URL')"
|
||||
SITE_TOKEN="$(read_protected_value "$SITE_TOKEN_FILE" 'site token')"
|
||||
[[ -n "$CENTRAL_URL" && -n "$SITE_TOKEN" ]] || { echo "Error: protected Central URL and site token files must be non-empty" >&2; exit 1; }
|
||||
while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
|
||||
[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token are required" >&2; exit 1; }
|
||||
[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; }
|
||||
if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi
|
||||
CENTRAL_URL="${CENTRAL_URL%/}"
|
||||
if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then
|
||||
echo "Error: Central URL must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
|
||||
echo "Error: --central-url must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
|
||||
exit 1
|
||||
fi
|
||||
ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac
|
||||
@@ -55,11 +45,9 @@ RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
|
||||
for attempt in 1 2 3; do
|
||||
CURL_PROTOCOL=https
|
||||
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
|
||||
printf '%s' "$RELEASE_METADATA_URL" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/release-metadata.curl"
|
||||
chmod 600 "$TMP_DIR/release-metadata.curl"
|
||||
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
|
||||
--connect-timeout 10 --max-time 30 \
|
||||
-w '%{http_code}' --config "$TMP_DIR/release-metadata.curl" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
|
||||
-w '%{http_code}' "$RELEASE_METADATA_URL" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
|
||||
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
|
||||
break
|
||||
fi
|
||||
@@ -121,11 +109,6 @@ with tarfile.open(sys.argv[1], 'r:gz') as archive:
|
||||
shutil.copyfileobj(source,output)
|
||||
PY
|
||||
[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; }
|
||||
printf '%s' "$CENTRAL_URL" | python3 -c 'import json,pathlib,sys; p=pathlib.Path(sys.argv[1]); raw=p.read_text() if p.exists() else "{}";
|
||||
try: d=json.loads(raw)
|
||||
except json.JSONDecodeError: d={}
|
||||
d.setdefault("Agent",{})["CentralUrl"]=sys.stdin.read(); p.write_text(json.dumps(d,indent=2)+"\n")' "$TMP_DIR/agent/appsettings.json"
|
||||
chmod 640 "$TMP_DIR/agent/appsettings.json"
|
||||
id "$SERVICE_USER" &>/dev/null || sudo useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" 2>/dev/null || true
|
||||
sudo mkdir -p "$STATE_DIR" && sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR" && sudo chmod 700 "$STATE_DIR"
|
||||
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$INSTALL_ROOT" "$INSTALL_ROOT/releases"
|
||||
@@ -139,9 +122,7 @@ sudo install -d -o root -g root -m 755 /usr/local/libexec
|
||||
SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py"
|
||||
if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then
|
||||
SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py"
|
||||
printf '%s' "$CENTRAL_URL/install/agent-supervisor.py" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/supervisor.curl"
|
||||
chmod 600 "$TMP_DIR/supervisor.curl"
|
||||
curl -fsS --config "$TMP_DIR/supervisor.curl" -o "$SUPERVISOR_SOURCE" || {
|
||||
curl -fsS "$CENTRAL_URL/install/agent-supervisor.py" -o "$SUPERVISOR_SOURCE" || {
|
||||
echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
@@ -169,7 +150,7 @@ if [[ "$RUN_MODE" == true ]]; then
|
||||
ASPNETCORE_URLS=http://127.0.0.1:8081 \
|
||||
HEIMDALL_DOTNET="$DOTNET_BIN" \
|
||||
ASPNETCORE_ENVIRONMENT=Production \
|
||||
Agent__AgentName="$AGENT_NAME" \
|
||||
Agent__CentralUrl="$CENTRAL_URL" \
|
||||
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
|
||||
Agent__StateDirectory="$STATE_DIR" \
|
||||
Agent__UpdateInstallRoot="$INSTALL_ROOT" \
|
||||
@@ -191,6 +172,7 @@ RestartSec=5
|
||||
Environment=ASPNETCORE_URLS=http://127.0.0.1:8081
|
||||
Environment=HEIMDALL_DOTNET=$DOTNET_BIN
|
||||
Environment=ASPNETCORE_ENVIRONMENT=Production
|
||||
Environment=Agent__CentralUrl=$CENTRAL_URL
|
||||
Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP
|
||||
Environment=Agent__StateDirectory=$STATE_DIR
|
||||
Environment=Agent__UpdateInstallRoot=$INSTALL_ROOT
|
||||
@@ -200,7 +182,6 @@ $AGENT_NAME_CREDENTIAL
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
sudo chmod 600 "/etc/systemd/system/$SERVICE_NAME.service"
|
||||
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME"
|
||||
if [[ "$INSTALL_ONLY" == true ]]; then
|
||||
echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME"
|
||||
|
||||
@@ -4,82 +4,12 @@ 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é."
|
||||
}
|
||||
$digestProperty = $installerAsset.PSObject.Properties['digest']
|
||||
$assetDigest = if ($null -ne $digestProperty) { $digestProperty.Value } else { $null }
|
||||
if ($null -ne $assetDigest) {
|
||||
if ($assetDigest -isnot [string] -or $assetDigest -notmatch '^sha256:[A-Fa-f0-9]{64}$') {
|
||||
throw 'Le digest Gitea du bundle est invalide.'
|
||||
}
|
||||
$expectedHash = $assetDigest.Substring(7)
|
||||
} else {
|
||||
$checksumName = "$installerName.sha256"
|
||||
$checksumAsset = @($release.assets) | Where-Object { $_.name -eq $checksumName } | Select-Object -First 1
|
||||
if (-not $checksumAsset -or $checksumAsset.browser_download_url -notmatch '^https://') {
|
||||
throw 'La release ne fournit pas le checksum publié du bundle.'
|
||||
}
|
||||
$checksumPath = Join-Path $bootstrapRoot 'installers.zip.sha256'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $checksumAsset.browser_download_url -OutFile $checksumPath -TimeoutSec 30
|
||||
$checksumText = [IO.File]::ReadAllText($checksumPath)
|
||||
$escapedName = [Regex]::Escape($installerName)
|
||||
$checksumMatches = [Regex]::Matches($checksumText, "(?m)^([A-Fa-f0-9]{64})\s+\*?$escapedName\s*$")
|
||||
if ($checksumMatches.Count -ne 1) { throw 'Le checksum publié du bundle est invalide.' }
|
||||
$expectedHash = $checksumMatches[0].Groups[1].Value
|
||||
}
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $installerAsset.browser_download_url -OutFile $bundlePath -TimeoutSec 120
|
||||
$actualHash = (Get-FileHash -LiteralPath $bundlePath -Algorithm SHA256).Hash
|
||||
if ($actualHash -ne $expectedHash) { throw 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' }
|
||||
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]"
|
||||
@@ -148,6 +78,9 @@ 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.' }
|
||||
@@ -350,7 +283,6 @@ if ($startCore) {
|
||||
}
|
||||
|
||||
foreach ($service in $selected) {
|
||||
$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }
|
||||
switch ($service) {
|
||||
'rustfs' {
|
||||
$accessKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_access_key'
|
||||
@@ -380,7 +312,7 @@ foreach ($service in $selected) {
|
||||
}
|
||||
}
|
||||
if ($startCore -and (Read-YesNo "Démarrer le service optionnel $service ?" 'o')) {
|
||||
Invoke-DockerCompose @('--project-directory', $composeProjectDirectory, '--project-name', "heimdall-$service", '--env-file', $envPath,
|
||||
Invoke-DockerCompose @('--project-name', "heimdall-$service", '--env-file', $envPath,
|
||||
'-f', (Join-Path $optionalDirectory "docker-compose.$service.yml"), 'up', '-d')
|
||||
} else {
|
||||
Write-Host "Service $service préparé dans $optionalDirectory."
|
||||
|
||||
@@ -7,8 +7,6 @@ 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)"
|
||||
@@ -28,69 +26,11 @@ 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 jq unzip; do
|
||||
for command in docker openssl curl; 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;
|
||||
}
|
||||
asset_digest_type="$(jq -r 'if has("digest") then (.digest | type) else "missing" end' <<<"$asset_json")"
|
||||
asset_digest="$(jq -r '.digest // empty' <<<"$asset_json")"
|
||||
if [[ "$asset_digest_type" != null && "$asset_digest_type" != missing ]]; then
|
||||
[[ "$asset_digest_type" == string && "$asset_digest" =~ ^sha256:[A-Fa-f0-9]{64}$ ]] || {
|
||||
echo 'Le digest Gitea du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
expected_sha256="${asset_digest#sha256:}"
|
||||
else
|
||||
checksum_asset_json="$(jq -ce --arg name "$installer_asset.sha256" '.assets[]? | select(.name == $name)' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release ne fournit pas le checksum publié du bundle.' >&2; exit 1;
|
||||
}
|
||||
checksum_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$checksum_asset_json")" || {
|
||||
echo 'URL HTTPS du checksum du bundle invalide.' >&2; exit 1;
|
||||
}
|
||||
curl --fail --silent --show-error --location "$checksum_url" --output "$bootstrap_dir/installers.zip.sha256"
|
||||
expected_sha256="$(awk -v name="$installer_asset" '$2 == name && $1 ~ /^[A-Fa-f0-9]{64}$/ { print tolower($1); count++ } END { if (count != 1) exit 1 }' "$bootstrap_dir/installers.zip.sha256")" || {
|
||||
echo 'Le checksum publié du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
curl --fail --silent --show-error --location "$installer_url" --output "$bootstrap_dir/installers.zip"
|
||||
actual_sha256="$(sha256sum "$bootstrap_dir/installers.zip" | cut -d ' ' -f 1)"
|
||||
[[ "${actual_sha256,,}" == "${expected_sha256,,}" ]] || { echo 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' >&2; exit 1; }
|
||||
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
|
||||
@@ -110,8 +50,6 @@ copy_source_asset() {
|
||||
|
||||
say "Installation de Heimdall Central (serveur + PostgreSQL)."
|
||||
destination="$(ask 'Dossier d’installation' "$HOME/heimdall")"
|
||||
compose_project="$(ask 'Nom isolé du projet Docker Compose' 'heimdall')"
|
||||
[[ "$compose_project" =~ ^[a-z0-9][a-z0-9_-]{0,62}$ ]] || { echo 'Nom de projet Compose invalide.' >&2; exit 1; }
|
||||
compose_path="$destination/docker-compose.yml"
|
||||
env_path="$destination/.env"
|
||||
is_existing=no
|
||||
@@ -127,10 +65,7 @@ if [[ -e "$compose_path" || -e "$env_path" ]]; then
|
||||
is_existing=yes
|
||||
else
|
||||
web_port="$(ask 'Port HTTP du serveur' '5000')"
|
||||
public_origin="${HEIMDALL_URL:-}"
|
||||
cors_default=''
|
||||
if [[ "$public_origin" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?$ ]]; then cors_default="$public_origin"; fi
|
||||
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' "${cors_default:-https://heimdall.invalid}")"
|
||||
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')"
|
||||
[[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; }
|
||||
[[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; }
|
||||
fi
|
||||
@@ -191,6 +126,8 @@ fi
|
||||
compose_tmp="$(mktemp "$destination/.docker-compose.yml.XXXXXX")"
|
||||
trap 'rm -f "${compose_tmp:-}"' EXIT
|
||||
cat > "$compose_tmp" <<'COMPOSE'
|
||||
name: heimdall
|
||||
|
||||
services:
|
||||
postgresql:
|
||||
image: postgres:17-alpine
|
||||
@@ -260,10 +197,11 @@ secrets:
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
driver: bridge
|
||||
COMPOSE
|
||||
chmod 600 "$compose_tmp"
|
||||
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_tmp" config --quiet
|
||||
docker compose --env-file "$env_path" -f "$compose_tmp" config --quiet
|
||||
if [[ "$is_existing" == yes ]]; then
|
||||
backup_path="$compose_path.bak.$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
cp -p "$compose_path" "$backup_path"
|
||||
@@ -293,15 +231,11 @@ say "Variables protégées dans $destination/.env (mode 600), secret PostgreSQL
|
||||
say "Validation du Compose avant démarrage…"
|
||||
start_core=no
|
||||
if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_path" up -d
|
||||
docker compose --env-file "$env_path" -f "$compose_path" up -d
|
||||
start_core=yes
|
||||
fi
|
||||
|
||||
for service in "${selected[@]}"; do
|
||||
compose_project_directory="$destination"
|
||||
if [[ "$service" == backup ]]; then
|
||||
compose_project_directory="$destination/optional"
|
||||
fi
|
||||
case "$service" in
|
||||
rustfs)
|
||||
printf '%s' "heimdall$(openssl rand -hex 8)" > "$destination/optional/secrets/rustfs_access_key"
|
||||
@@ -324,8 +258,7 @@ for service in "${selected[@]}"; do
|
||||
;;
|
||||
esac
|
||||
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
docker compose --project-directory "$compose_project_directory" --project-name "${compose_project}-${service}" \
|
||||
--env-file "$destination/.env" \
|
||||
docker compose --project-name "heimdall-${service}" --env-file "$destination/.env" \
|
||||
-f "$destination/optional/docker-compose.${service}.yml" up -d
|
||||
else
|
||||
say "Service ${service} préparé dans $destination/optional/."
|
||||
|
||||
@@ -87,12 +87,9 @@ Windows, copiez la commande affichée sur l’hôte distant : elle télécharge
|
||||
script depuis le Central et l’exécute avec les identifiants propres à ce site.
|
||||
L’installation Linux peut créer un service systemd; l’installation Windows
|
||||
peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
|
||||
utilisez le Compose généré par l’IHM, qui suit le tag `latest`. Aucun fichier de
|
||||
utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de
|
||||
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
|
||||
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
|
||||
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
|
||||
jour pilotées par Central; ce socket donne à l’Agent un contrôle étendu sur
|
||||
l’hôte. N’installez ce mode que sur un hôte de confiance.
|
||||
|
||||
### 3. Développement local
|
||||
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \n')"
|
||||
project="heimdall-heartbeat-${suffix}"
|
||||
central_image="heimdall-heartbeat-mock:${suffix}"
|
||||
agent_image="heimdall-agent:heartbeat-${suffix}"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
compose_file="$temp_dir/compose.yml"
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
local_image_tags=("$agent_image" "$central_image")
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
down --volumes --remove-orphans || cleanup_failed=1
|
||||
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resource cleanup failed: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no containers, volumes, or networks remain for %s\n' "$project"
|
||||
fi
|
||||
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image still exists: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
|
||||
rm -rf -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable recipe cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
site_token=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
|
||||
cat >"$env_file" <<EOF
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
ACCEPTANCE_AGENT_IMAGE=$agent_image
|
||||
ACCEPTANCE_CENTRAL_IMAGE=$central_image
|
||||
ACCEPTANCE_SITE_TOKEN=$site_token
|
||||
EOF
|
||||
|
||||
mkdir -p "$temp_dir/mock-central"
|
||||
cat >"$temp_dir/mock-central/Dockerfile" <<'EOF'
|
||||
FROM python:3.13-alpine
|
||||
WORKDIR /app
|
||||
COPY mock_central.py .
|
||||
CMD ["python", "-u", "/app/mock_central.py"]
|
||||
EOF
|
||||
cat >"$temp_dir/mock-central/mock_central.py" <<'PY'
|
||||
import json
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
heartbeat_count = 0
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/healthz":
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
elif self.path == "/counts":
|
||||
payload = json.dumps({"heartbeats": heartbeat_count}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
def do_POST(self):
|
||||
global heartbeat_count
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
self.rfile.read(length)
|
||||
if self.path == "/api/agents/register":
|
||||
payload = json.dumps({
|
||||
"agentId": "a583ec73-665f-4628-93e3-fcfe746a0e02",
|
||||
"apiKey": "synthetic-acceptance-key",
|
||||
"apiKeyPrefix": "synthetic",
|
||||
}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
elif self.path.endswith("/heartbeat"):
|
||||
heartbeat_count += 1
|
||||
if heartbeat_count == 1:
|
||||
time.sleep(12)
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
|
||||
PY
|
||||
|
||||
cat >"$compose_file" <<'YAML'
|
||||
services:
|
||||
fake-central:
|
||||
image: ${ACCEPTANCE_CENTRAL_IMAGE}
|
||||
build:
|
||||
context: ./mock-central
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz')"]
|
||||
interval: 1s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
agent:
|
||||
image: ${ACCEPTANCE_AGENT_IMAGE}
|
||||
build:
|
||||
context: ${ACCEPTANCE_REPO_ROOT}
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
environment:
|
||||
ASPNETCORE_URLS: http://127.0.0.1:8081
|
||||
Agent__CentralUrl: http://fake-central:8080
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${ACCEPTANCE_SITE_TOKEN}
|
||||
Agent__AgentName: heartbeat-acceptance
|
||||
Agent__HeartbeatIntervalSeconds: "5"
|
||||
Agent__PublicIpResolverUrl: ""
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
ports:
|
||||
- "127.0.0.1::8081"
|
||||
depends_on:
|
||||
fake-central:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
agent_state:
|
||||
YAML
|
||||
|
||||
printf 'ACCEPTANCE_REPO_ROOT=%s\n' "$repo_root" >>"$env_file"
|
||||
printf 'Disposable project: %s\n' "$project"
|
||||
printf 'Locally built image tags: %s %s\n' "$agent_image" "$central_image"
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" up -d --build
|
||||
|
||||
deadline=$((SECONDS + 45))
|
||||
while (( SECONDS < deadline )); do
|
||||
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
exec -T agent wget -q --spider http://127.0.0.1:8081/healthz >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if (( SECONDS >= deadline )); then
|
||||
printf 'Agent health endpoint did not become available\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
deadline=$((SECONDS + 35))
|
||||
while (( SECONDS < deadline )); do
|
||||
counts=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
exec -T fake-central python -c \
|
||||
'import json,urllib.request; print(json.load(urllib.request.urlopen("http://127.0.0.1:8080/counts"))["heartbeats"])')
|
||||
if [[ "$counts" =~ ^[0-9]+$ ]] && (( counts >= 2 )); then
|
||||
printf 'Acceptance passed: Agent remained healthy and fake Central observed %s heartbeats, including a retry after its first delayed response.\n' "$counts"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'Acceptance failed: fake Central did not observe a heartbeat retry (last count: %s)\n' "${counts:-unknown}" >&2
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs --no-color agent | tail -80 >&2 || true
|
||||
exit 1
|
||||
@@ -1,127 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
project="heimdall-agent-startup-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 3)"
|
||||
image_tag="heimdall-agent:${project}-agent"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
compose_file="$temp_dir/compose.yaml"
|
||||
local_image_tags=("$image_tag")
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
|
||||
|
||||
containers=
|
||||
volumes=
|
||||
networks=
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
[[ -z "${containers:-}" && -z "${volumes:-}" && -z "${networks:-}" ]] || cleanup_failed=1
|
||||
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
cleanup_failed=1
|
||||
fi
|
||||
done
|
||||
|
||||
rm -f -- "$env_file" "$compose_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable Agent startup cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
else
|
||||
printf 'Cleanup verified: project=%s; containers/volumes/networks absent; image tag %s absent.\n' \
|
||||
"$project" "$image_tag"
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
umask 077
|
||||
cat >"$env_file" <<EOF
|
||||
PROJECT=$project
|
||||
SOURCE_ROOT=$repo_root
|
||||
IMAGE_TAG=$image_tag
|
||||
SYNTHETIC_SITE_TOKEN=$(openssl rand -hex 32)
|
||||
EOF
|
||||
|
||||
cat >"$compose_file" <<'EOF'
|
||||
services:
|
||||
agent:
|
||||
image: ${IMAGE_TAG}
|
||||
build:
|
||||
context: ${SOURCE_ROOT}
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
network: host
|
||||
restart: "no"
|
||||
environment:
|
||||
Agent__CentralUrl: http://127.0.0.1:1
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${SYNTHETIC_SITE_TOKEN}
|
||||
Agent__AgentName: ${PROJECT}
|
||||
Agent__RegistrationMaxRetries: "20"
|
||||
Agent__HeartbeatIntervalSeconds: "5"
|
||||
Agent__DiscoveryEnabled: "false"
|
||||
Agent__UpdateCheckIntervalHours: "0"
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
Sentry__Dsn: ""
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
networks:
|
||||
- isolated
|
||||
|
||||
volumes:
|
||||
agent_state:
|
||||
|
||||
networks:
|
||||
isolated:
|
||||
internal: true
|
||||
EOF
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
up --build --detach agent
|
||||
|
||||
container_id=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps -q agent)
|
||||
[[ -n "$container_id" ]] || { printf 'Agent container was not created.\n' >&2; exit 1; }
|
||||
|
||||
deadline=$((SECONDS + 90))
|
||||
live_ready=0
|
||||
while (( SECONDS < deadline )); do
|
||||
running=$(docker inspect --format '{{.State.Running}}' "$container_id" 2>/dev/null || true)
|
||||
if [[ "$running" != true ]]; then
|
||||
printf 'Agent container exited before its live endpoint became ready.\n' >&2
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
exec -T agent wget -q --tries=1 --spider http://127.0.0.1:8080/health/live >/dev/null 2>&1; then
|
||||
live_ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
(( live_ready == 1 )) || { printf 'Agent /health/live did not become ready.\n' >&2; exit 1; }
|
||||
|
||||
restart_count=$(docker inspect --format '{{.RestartCount}}' "$container_id")
|
||||
[[ "$restart_count" == 0 ]] || { printf 'Agent container restarted unexpectedly.\n' >&2; exit 1; }
|
||||
|
||||
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs agent 2>&1 |
|
||||
rg -q "Unable to resolve service for type 'Heimdall\.Agent\.Services\.SnapshotPipelineServiceOptions'|Hosting failed to start"; then
|
||||
printf 'Agent startup log contains a dependency-injection or host-start failure.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'Agent host started; /health/live returned success; container remained running without restart.\n'
|
||||
printf 'Project: %s\nLocal image tag: %s\n' "$project" "$image_tag"
|
||||
@@ -1,276 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
stamp="$(date +%s)-$RANDOM"
|
||||
project="heimdall-157-${stamp}"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
env_next="$temp_dir/acceptance.env.next"
|
||||
compose_override="$temp_dir/compose.override.yml"
|
||||
config_headers="$temp_dir/config.headers"
|
||||
config_body="$temp_dir/config.json"
|
||||
stage=setup
|
||||
local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent")
|
||||
compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override")
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
if (( status != 0 )); then
|
||||
printf 'acceptance failed at stage=%s\n' "$stage" >&2
|
||||
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null |
|
||||
grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true
|
||||
fi
|
||||
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
rm -f -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
printf 'cleanup verification failed for %s\n' "$project" >&2
|
||||
status=1
|
||||
else
|
||||
printf 'cleanup verified: project resources absent; exact local tags absent\n'
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
port=$((20000 + RANDOM % 20000))
|
||||
pg_port=$((port + 1))
|
||||
db_password=$(openssl rand -hex 24)
|
||||
jwt_key=$(openssl rand -hex 48)
|
||||
jwt_refresh=$(openssl rand -hex 48)
|
||||
cat >"$env_file" <<EOF
|
||||
POSTGRES_DB=heimdall_acceptance
|
||||
POSTGRES_USER=acceptance
|
||||
POSTGRES_PASSWORD=$db_password
|
||||
POSTGRES_PORT=127.0.0.1:$pg_port
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=acceptance;Password=$db_password
|
||||
JWT__KEY=$jwt_key
|
||||
JWT__REFRESHKEY=$jwt_refresh
|
||||
JWT__ISSUER=heimdall-acceptance
|
||||
JWT__AUDIENCE=heimdall-acceptance-api
|
||||
WEB_PORT=127.0.0.1:$port
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
DOCKER_GID=0
|
||||
HEIMDALL_NETWORK_NAME=${project}-network
|
||||
HEIMDALL_TEST_SITE_TOKEN=placeholder-token
|
||||
EOF
|
||||
cat >"$compose_override" <<'EOF'
|
||||
services:
|
||||
heimdall:
|
||||
image: heimdall:${ACCEPTANCE_PROJECT}-central
|
||||
heimdall-agent:
|
||||
image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
user: "1654:1654"
|
||||
environment:
|
||||
Agent__CentralUrl: http://heimdall:8080
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required}
|
||||
Agent__AgentName: camera-157-agent
|
||||
Agent__HeartbeatIntervalSeconds: "5"
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
Agent__DiscoveryEnabled: "false"
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
depends_on:
|
||||
heimdall:
|
||||
condition: service_healthy
|
||||
synthetic-camera-publisher:
|
||||
condition: service_started
|
||||
networks:
|
||||
- heimdall-net
|
||||
synthetic-camera:
|
||||
image: bluenviron/mediamtx:1.21.3
|
||||
volumes:
|
||||
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
|
||||
networks:
|
||||
- heimdall-net
|
||||
synthetic-camera-publisher:
|
||||
image: jrottenberg/ffmpeg:7.1-alpine
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"]
|
||||
depends_on:
|
||||
- synthetic-camera
|
||||
networks:
|
||||
- heimdall-net
|
||||
volumes:
|
||||
agent_state:
|
||||
EOF
|
||||
|
||||
# The cleanup trap is installed before any image build or Compose start.
|
||||
trap cleanup EXIT
|
||||
chmod 600 "$env_file"
|
||||
api="http://127.0.0.1:$port"
|
||||
compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; }
|
||||
contract_failures=0
|
||||
wait_http() {
|
||||
for _ in $(seq 1 90); do
|
||||
if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi
|
||||
sleep 2
|
||||
done
|
||||
return 1
|
||||
}
|
||||
request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; }
|
||||
ffmpeg_count() {
|
||||
compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"'
|
||||
}
|
||||
wait_count() {
|
||||
expected=$1; seconds=$2
|
||||
for _ in $(seq 1 "$((seconds * 20))"); do
|
||||
count=$(ffmpeg_count)
|
||||
observed_at_ns=$(date +%s%N)
|
||||
(( count <= 1 )) || return 1
|
||||
if [[ "$count" == "$expected" ]]; then
|
||||
count_observed_at_ns=$observed_at_ns
|
||||
return 0
|
||||
fi
|
||||
sleep 0.05
|
||||
done
|
||||
return 1
|
||||
}
|
||||
wait_ack() {
|
||||
expected_enabled=$1
|
||||
for _ in $(seq 1 100); do
|
||||
request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body"
|
||||
wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers")
|
||||
actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body")
|
||||
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
|
||||
applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents")
|
||||
if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then
|
||||
acknowledged_version=$wanted
|
||||
return 0
|
||||
fi
|
||||
sleep 0.1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
wait_agent_reconnected_and_ack() {
|
||||
restarted_at_ns=$1
|
||||
expected_version=$2
|
||||
for _ in $(seq 1 60); do
|
||||
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
|
||||
agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents")
|
||||
status=$(jq -r '.status // empty' <<<"$agent")
|
||||
heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent")
|
||||
applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent")
|
||||
applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent")
|
||||
if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then
|
||||
heartbeat_ns=$(date -u -d "$heartbeat" +%s%N)
|
||||
applied_at_ns=$(date -u -d "$applied_at" +%s%N)
|
||||
if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}"
|
||||
stage=build
|
||||
compose build heimdall heimdall-agent
|
||||
stage=central-startup
|
||||
compose up -d postgresql heimdall
|
||||
wait_http
|
||||
stage=bootstrap
|
||||
admin_password="Tst!$(openssl rand -hex 20)A9"
|
||||
bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin")
|
||||
admin_token=$(jq -er '.accessToken' <<<"$bootstrap")
|
||||
printf 'synthetic Admin bootstrap accepted\n'
|
||||
site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites")
|
||||
site_id=$(jq -er '.id' <<<"$site")
|
||||
printf 'synthetic site created\n'
|
||||
site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token')
|
||||
grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next"
|
||||
printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next"
|
||||
mv "$env_next" "$env_file"
|
||||
camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras")
|
||||
camera_id=$(jq -er '.id' <<<"$camera")
|
||||
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
|
||||
printf 'synthetic camera created\n'
|
||||
stage=agent-startup
|
||||
compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent
|
||||
agent_id=
|
||||
for _ in $(seq 1 60); do
|
||||
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
|
||||
agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents")
|
||||
[[ -n "$agent_id" ]] && break
|
||||
sleep 1
|
||||
done
|
||||
[[ -n "$agent_id" ]]
|
||||
printf 'Agent registered\n'
|
||||
request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null
|
||||
stage=initial-on
|
||||
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
|
||||
wait_count 1 10
|
||||
wait_ack true
|
||||
|
||||
off_once() {
|
||||
started=$(date +%s%N)
|
||||
result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status")
|
||||
response_ms=$((( $(date +%s%N) - started ) / 1000000))
|
||||
[[ $(jq -r '.status' <<<"$result") == Disabled ]]
|
||||
within_contract=1
|
||||
if ! wait_count 0 2; then
|
||||
within_contract=0
|
||||
wait_count 0 10 || return 1
|
||||
fi
|
||||
elapsed_ms=$((( count_observed_at_ns - started ) / 1000000))
|
||||
printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract"
|
||||
if (( ! within_contract || elapsed_ms >= 2000 )); then
|
||||
contract_failures=$((contract_failures + 1))
|
||||
fi
|
||||
wait_ack false
|
||||
}
|
||||
for iteration in 1 2 3; do
|
||||
stage="cycle-${iteration}-off"
|
||||
off_once
|
||||
stage="cycle-${iteration}-on"
|
||||
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
|
||||
wait_count 1 10
|
||||
wait_ack true
|
||||
count=$(ffmpeg_count)
|
||||
[[ "$count" == 1 ]]
|
||||
done
|
||||
stage=agent-restart-on
|
||||
compose restart heimdall-agent
|
||||
wait_count 1 10
|
||||
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
|
||||
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
|
||||
[[ "$old_agent_id" == "$agent_id" ]]
|
||||
wait_ack true
|
||||
stage=final-off
|
||||
off_once
|
||||
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
|
||||
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
|
||||
compose restart heimdall-agent
|
||||
post_off_restart_returned_ns=$(date +%s%N)
|
||||
wait_count 0 10
|
||||
wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version"
|
||||
stage=central-restart-off
|
||||
compose restart heimdall
|
||||
central_restart_returned_ns=$(date +%s%N)
|
||||
wait_http
|
||||
sleep 2
|
||||
[[ $(ffmpeg_count) == 0 ]]
|
||||
camera=$(request "$api/api/cameras/$camera_id")
|
||||
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
|
||||
wait_ack false
|
||||
wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version"
|
||||
printf 'restart OFF persisted; camera config digest acknowledged\n'
|
||||
if (( contract_failures > 0 )); then
|
||||
printf 'contract failures=%s\n' "$contract_failures" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,198 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
project="heimdall-migration-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 4)"
|
||||
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
compose_override="$temp_dir/compose.override.yml"
|
||||
failure_override="$temp_dir/compose.failure.yml"
|
||||
recovery_override="$temp_dir/compose.recovery.yml"
|
||||
compose_file="$(git rev-parse --show-toplevel)/docker/docker-compose.yml"
|
||||
local_image_tags=("heimdall:${project}-central")
|
||||
|
||||
web_port="$(python3 - <<'PY'
|
||||
import socket
|
||||
s = socket.socket()
|
||||
s.bind(('127.0.0.1', 0))
|
||||
print(s.getsockname()[1])
|
||||
s.close()
|
||||
PY
|
||||
)"
|
||||
db_name="${project//-/_}"
|
||||
db_user="migration_owner_${project//-/_}"
|
||||
db_password="$(openssl rand -hex 24)"
|
||||
probe_password="$(openssl rand -hex 24)"
|
||||
jwt_key="$(openssl rand -base64 48 | tr -d '\n')"
|
||||
jwt_refresh_key="$(openssl rand -base64 48 | tr -d '\n')"
|
||||
|
||||
cat > "$env_file" <<EOF
|
||||
POSTGRES_DB=$db_name
|
||||
POSTGRES_USER=$db_user
|
||||
POSTGRES_PASSWORD=$db_password
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=$db_name;Username=$db_user;Password=$db_password
|
||||
JWT__KEY=$jwt_key
|
||||
JWT__REFRESHKEY=$jwt_refresh_key
|
||||
JWT__ISSUER=$project
|
||||
JWT__AUDIENCE=$project
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
Sentry__Dsn=
|
||||
SENTRY_DSN=
|
||||
WEB_PORT=$web_port
|
||||
HEIMDALL_NETWORK_NAME=${project}_net
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
MIGRATION_PROBE_PASSWORD=$probe_password
|
||||
EOF
|
||||
chmod 600 "$env_file"
|
||||
|
||||
cat > "$compose_override" <<'EOF'
|
||||
services:
|
||||
postgresql:
|
||||
ports: !override []
|
||||
heimdall:
|
||||
image: heimdall:${ACCEPTANCE_PROJECT}-central
|
||||
ports: !override
|
||||
- "127.0.0.1:${WEB_PORT}:8080"
|
||||
EOF
|
||||
|
||||
cat > "$failure_override" <<'EOF'
|
||||
services:
|
||||
heimdall:
|
||||
environment:
|
||||
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
|
||||
restart: "no"
|
||||
EOF
|
||||
|
||||
cat > "$recovery_override" <<'EOF'
|
||||
services:
|
||||
heimdall:
|
||||
environment:
|
||||
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
|
||||
restart: "no"
|
||||
EOF
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" down --volumes --remove-orphans || cleanup_failed=1
|
||||
|
||||
containers="$(docker ps -aq --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
|
||||
volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
|
||||
networks="$(docker network ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
|
||||
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
|
||||
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
|
||||
python3 - "$env_file" "$compose_override" "$failure_override" "$recovery_override" <<'PY' || cleanup_failed=1
|
||||
import pathlib
|
||||
import sys
|
||||
for name in sys.argv[1:]:
|
||||
pathlib.Path(name).unlink(missing_ok=True)
|
||||
PY
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable migration recipe cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
else
|
||||
printf 'Cleanup verified: project containers/volumes/network and exact tag absent (%s).\n' "${local_image_tags[*]}"
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Unique acceptance image tag already exists: %s\n' "$tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
compose() {
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" "$@"
|
||||
}
|
||||
|
||||
compose config --quiet
|
||||
compose up -d --build
|
||||
base_url="http://127.0.0.1:$web_port"
|
||||
|
||||
wait_healthy() {
|
||||
for attempt in $(seq 1 120); do
|
||||
if curl --fail --silent "$base_url/healthz" -o /dev/null; then return 0; fi
|
||||
sleep 2
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_healthy || { echo 'Central did not become healthy after first migration.' >&2; exit 1; }
|
||||
echo 'First boot: PostgreSQL fresh schema migrated; Central healthz returned HTTP 200.'
|
||||
|
||||
compose restart heimdall
|
||||
wait_healthy || { echo 'Central did not recover against the migrated database.' >&2; exit 1; }
|
||||
echo 'Restart: Central healthz returned HTTP 200 on the migrated schema.'
|
||||
|
||||
postgres_container="$(compose ps -q postgresql)"
|
||||
[[ -n "$postgres_container" ]] || { echo 'PostgreSQL container was not found.' >&2; exit 1; }
|
||||
docker exec -i "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
|
||||
-v probe_password="$probe_password" <<'SQL'
|
||||
CREATE ROLE migration_probe LOGIN PASSWORD :'probe_password';
|
||||
SELECT format('GRANT CONNECT ON DATABASE %I TO migration_probe', current_database()) \gexec
|
||||
GRANT USAGE ON SCHEMA public TO migration_probe;
|
||||
GRANT CREATE ON SCHEMA public TO migration_probe;
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO migration_probe;
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO migration_probe;
|
||||
GRANT USAGE, CREATE ON SCHEMA hangfire TO migration_probe;
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA hangfire TO migration_probe;
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA hangfire TO migration_probe;
|
||||
REVOKE SELECT ON TABLE public."__EFMigrationsHistory" FROM migration_probe;
|
||||
SQL
|
||||
|
||||
compose -f "$failure_override" up -d --force-recreate heimdall
|
||||
web_container="$(compose -f "$failure_override" ps -q heimdall)"
|
||||
[[ -n "$web_container" ]] || { echo 'Central failure-test container was not found.' >&2; exit 1; }
|
||||
|
||||
failure_state=""
|
||||
for attempt in $(seq 1 90); do
|
||||
failure_state="$(docker inspect -f '{{.State.Status}}' "$web_container" 2>/dev/null || true)"
|
||||
[[ "$failure_state" == exited ]] && break
|
||||
sleep 1
|
||||
done
|
||||
[[ "$failure_state" == exited ]] || { echo 'Central did not exit on a permanent migration permission failure.' >&2; exit 1; }
|
||||
failure_exit_code="$(docker inspect -f '{{.State.ExitCode}}' "$web_container")"
|
||||
[[ "$failure_exit_code" != 0 ]] || { echo 'Central exited successfully despite the permanent migration failure.' >&2; exit 1; }
|
||||
|
||||
failure_logs="$(docker logs "$web_container" 2>&1)"
|
||||
application_logs="$(grep -E 'Applying database migrations \(attempt|Database migration attempt .* failed|Failed to apply database migrations after 5 attempts|Database migrations applied successfully|permission denied' <<<"$failure_logs" | grep -v 'HttpTransport: Envelope')"
|
||||
attempt_count="$(grep -c 'Applying database migrations (attempt' <<<"$application_logs" || true)"
|
||||
retry_count="$(grep -c 'Database migration attempt .* failed' <<<"$application_logs" || true)"
|
||||
terminal_count="$(grep -c 'Failed to apply database migrations after 5 attempts' <<<"$application_logs" || true)"
|
||||
success_count="$(grep -c 'Database migrations applied successfully' <<<"$application_logs" || true)"
|
||||
[[ "$attempt_count" -eq 5 && "$retry_count" -eq 4 && "$terminal_count" -eq 1 && "$success_count" -eq 0 ]] || {
|
||||
printf 'Retry log counts: attempts=%s retries=%s terminal=%s successes=%s\n' \
|
||||
"$attempt_count" "$retry_count" "$terminal_count" "$success_count" >&2
|
||||
grep -E 'Applying database migrations \(attempt|Database migration attempt|Failed to apply database migrations|Database migrations applied successfully' \
|
||||
<<<"$application_logs" | cut -c1-240 >&2 || true
|
||||
echo 'Permanent failure did not show five attempts, four retries, one terminal failure, and zero success logs.' >&2
|
||||
exit 1
|
||||
}
|
||||
grep -qi 'permission denied' <<<"$application_logs" || {
|
||||
echo 'The synthetic failure did not report the expected history-table permission denial.' >&2
|
||||
exit 1
|
||||
}
|
||||
echo 'Permanent failure: permission denied on migration history; five attempts, four retries, final Critical error, nonzero exit, no migration-success log.'
|
||||
|
||||
docker exec "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
|
||||
-c 'GRANT SELECT ON TABLE public."__EFMigrationsHistory" TO migration_probe;' >/dev/null
|
||||
compose -f "$recovery_override" up -d --force-recreate heimdall
|
||||
wait_healthy || {
|
||||
echo 'Central did not recover after granting migration-history access.' >&2
|
||||
docker logs "$(compose -f "$recovery_override" ps -q heimdall)" 2>&1 \
|
||||
| grep -Ei 'failed|error|permission denied|database migration|migration.*success' \
|
||||
| grep -v 'HttpTransport: Envelope' | cut -c1-240 | tail -n 20 >&2 || true
|
||||
exit 1
|
||||
}
|
||||
echo 'Recovery: granting history-table SELECT allowed startup; Central healthz returned HTTP 200.'
|
||||
@@ -1,182 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
|
||||
flow="${HEIMDALL_ACCEPTANCE_FLOW:-create-login}"
|
||||
if [[ "$flow" != "create-login" && "$flow" != "2fa-cookie" ]]; then
|
||||
echo 'HEIMDALL_ACCEPTANCE_FLOW must be create-login or 2fa-cookie' >&2
|
||||
exit 2
|
||||
fi
|
||||
project="heimdall-auth-${flow}-${suffix}"
|
||||
central_image="heimdall:${project}-central"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
override_file="$temp_dir/compose.override.yml"
|
||||
compose_file="$repo_root/docker/docker-compose.yml"
|
||||
local_image_tags=("$central_image")
|
||||
compose_port=$(python3 - <<'PY'
|
||||
import socket
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
print(sock.getsockname()[1])
|
||||
PY
|
||||
)
|
||||
web_port=$(python3 - <<'PY'
|
||||
import socket
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
print(sock.getsockname()[1])
|
||||
PY
|
||||
)
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" \
|
||||
down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then status=1; fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
pg_password=$(python3 - <<'PY'
|
||||
import secrets, string
|
||||
alphabet=string.ascii_letters+string.digits
|
||||
print(''.join(secrets.choice(alphabet) for _ in range(40)))
|
||||
PY
|
||||
)
|
||||
jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password="${admin_password}Aa1!"
|
||||
cat >"$env_file" <<EOF
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
POSTGRES_DB=heimdall_acceptance
|
||||
POSTGRES_USER=heimdall_acceptance
|
||||
POSTGRES_PASSWORD=$pg_password
|
||||
POSTGRES_PORT=$compose_port
|
||||
WEB_PORT=$web_port
|
||||
DATABASE_URL="Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=heimdall_acceptance;Password=$pg_password;Timeout=60;Command Timeout=300"
|
||||
JWT__KEY=$jwt_key
|
||||
JWT__REFRESHKEY=$refresh_key
|
||||
JWT__ISSUER=heimdall-acceptance
|
||||
JWT__AUDIENCE=heimdall-acceptance
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
HEIMDALL_NETWORK_NAME=${project}-net
|
||||
EOF
|
||||
cat >"$override_file" <<EOF
|
||||
services:
|
||||
heimdall:
|
||||
image: $central_image
|
||||
environment:
|
||||
Database__MigrateOnStartup: "true"
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nCentral image: %s\n' "$project" "$central_image"
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" up -d --build
|
||||
|
||||
base_url="http://127.0.0.1:$web_port"
|
||||
deadline=$((SECONDS + 300))
|
||||
until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do
|
||||
if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
printf 'Central /healthz: HTTP 200\n'
|
||||
|
||||
BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY'
|
||||
import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request
|
||||
base=os.environ['BASE_URL']
|
||||
flow=os.environ['ACCEPTANCE_FLOW']
|
||||
def request(method, path, body=None, token=None, cookie=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['Authorization']='Bearer '+token
|
||||
if cookie: headers['Cookie']=cookie
|
||||
data=json.dumps(body).encode() if body is not None else None
|
||||
req=urllib.request.Request(base+path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as response:
|
||||
return response.status, response.read(), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read(), error.headers
|
||||
def post(path, body, token=None):
|
||||
status, payload, _=request('POST', path, body, token)
|
||||
return status, payload
|
||||
def totp(key):
|
||||
secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8))
|
||||
counter=int(time.time())//30
|
||||
digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest()
|
||||
offset=digest[-1]&15
|
||||
value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff
|
||||
return f'{value%1000000:06d}'
|
||||
status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'})
|
||||
if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}')
|
||||
if flow == 'create-login':
|
||||
status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']})
|
||||
if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}')
|
||||
admin=json.loads(payload)['accessToken']
|
||||
for role in ('Viewer','Supervisor'):
|
||||
email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test'
|
||||
password='CreateLogin!'+secrets.token_urlsafe(18)+'A1'
|
||||
status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin)
|
||||
if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}')
|
||||
user_id=json.loads(payload)['id']
|
||||
status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin)
|
||||
if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}')
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}')
|
||||
if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token')
|
||||
print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)')
|
||||
else:
|
||||
admin=json.loads(bootstrap_payload)['accessToken']
|
||||
email='acceptance-admin@heimdall.test'
|
||||
password=os.environ['ACCEPTANCE_ADMIN_PASSWORD']
|
||||
status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin)
|
||||
if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}')
|
||||
shared_key=json.loads(payload)['sharedKey']
|
||||
# ResetAuthenticatorKey rotates the security stamp; renew the setup session
|
||||
# before the authenticated confirmation call.
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}')
|
||||
admin=json.loads(payload)['accessToken']
|
||||
status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin)
|
||||
if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}')
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}')
|
||||
challenge=json.loads(payload)
|
||||
if not challenge.get('requires2fa') or not challenge.get('challengeId'):
|
||||
raise SystemExit('2FA login did not return an authenticator challenge')
|
||||
status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)})
|
||||
if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}')
|
||||
access_token=json.loads(payload)['accessToken']
|
||||
status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token})
|
||||
if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}')
|
||||
set_cookie=headers.get('Set-Cookie','').split(';',1)[0]
|
||||
if not set_cookie.startswith('.Heimdall.Auth='):
|
||||
raise SystemExit('2FA cookie sign-in returned no auth cookie')
|
||||
status,_,_=request('GET','/api/users/me',cookie=set_cookie)
|
||||
if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}')
|
||||
print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)')
|
||||
PY
|
||||
@@ -1,266 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
|
||||
project="heimdall-optional-services-${suffix}"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
install_root="$temp_dir/install-root"
|
||||
secret_dir="$install_root/optional/secrets"
|
||||
backup_scripts_dir="$install_root/optional/scripts"
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
override_file="$temp_dir/compose.override.yml"
|
||||
turn_log="$temp_dir/turn-client.log"
|
||||
rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml"
|
||||
coturn_compose="$repo_root/docker/docker-compose.coturn.yml"
|
||||
backup_compose="$repo_root/docker/docker-compose.backup.yml"
|
||||
backup_scripts=(backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh)
|
||||
local_image_tags=()
|
||||
mkdir -p "$secret_dir" "$backup_scripts_dir"
|
||||
|
||||
compose() {
|
||||
docker compose --project-directory "$install_root" --env-file "$env_file" \
|
||||
-f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \
|
||||
-p "$project" "$@"
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
compose down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" ]]; then
|
||||
# `compose run --rm` may leave a one-off test container behind if the
|
||||
# client exits during shutdown; remove only containers carrying this
|
||||
# recipe's unique Compose project label.
|
||||
while IFS= read -r container; do
|
||||
[[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1
|
||||
done <<< "$containers"
|
||||
fi
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
if ((${#local_image_tags[@]} == 0)); then
|
||||
printf 'No local images built; upstream service images retained.\n'
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" "$turn_log" \
|
||||
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
|
||||
"$secret_dir/coturn_secret" "$secret_dir/db_password" || cleanup_failed=1
|
||||
for name in "${backup_scripts[@]}"; do
|
||||
rm -f -- "$backup_scripts_dir/$name" || cleanup_failed=1
|
||||
done
|
||||
rmdir -- "$backup_scripts_dir" "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if ((cleanup_failed)); then
|
||||
printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
read -r rustfs_api_port rustfs_console_port coturn_port relay_min relay_max < <(python3 - <<'PY'
|
||||
import random, socket
|
||||
used=set()
|
||||
def free_port(protocols):
|
||||
for port in random.sample(range(20000, 60000), 2000):
|
||||
if port in used: continue
|
||||
sockets=[]
|
||||
try:
|
||||
for kind in protocols:
|
||||
sock=socket.socket(socket.AF_INET,kind)
|
||||
sock.bind(('127.0.0.1',port))
|
||||
sockets.append(sock)
|
||||
used.add(port)
|
||||
return port
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for sock in sockets: sock.close()
|
||||
raise SystemExit('No free loopback ports found')
|
||||
def free_udp_range(width):
|
||||
for start in random.sample(range(25000, 55000-width), 2000):
|
||||
if any(port in used for port in range(start,start+width)): continue
|
||||
sockets=[]
|
||||
try:
|
||||
for port in range(start,start+width):
|
||||
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
|
||||
sock.bind(('127.0.0.1',port))
|
||||
sockets.append(sock)
|
||||
used.update(range(start,start+width))
|
||||
return start,start+width-1
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for sock in sockets: sock.close()
|
||||
raise SystemExit('No free contiguous UDP relay ports found')
|
||||
print(free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,)),
|
||||
free_port((socket.SOCK_STREAM,socket.SOCK_DGRAM)), *free_udp_range(20))
|
||||
PY
|
||||
)
|
||||
rustfs_access_key="acceptance$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')"
|
||||
rustfs_secret_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
coturn_secret=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
coturn_username=acceptance
|
||||
printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key"
|
||||
printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key"
|
||||
printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret"
|
||||
printf 'acceptance-db-password-%s' "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" > "$secret_dir/db_password"
|
||||
for name in "${backup_scripts[@]}"; do
|
||||
cp "$repo_root/docker/scripts/$name" "$backup_scripts_dir/$name"
|
||||
done
|
||||
chmod 600 "$secret_dir"/*
|
||||
cat > "$env_file" <<EOF
|
||||
RUSTFS_API_PORT=$rustfs_api_port
|
||||
RUSTFS_CONSOLE_PORT=$rustfs_console_port
|
||||
COTURN_PORT=$coturn_port
|
||||
COTURN_RELAY_PORT_MIN=$relay_min
|
||||
COTURN_RELAY_PORT_MAX=$relay_max
|
||||
COTURN_REALM=heimdall.acceptance.test
|
||||
COTURN_SECRET=$coturn_secret
|
||||
COTURN_USERNAME=$coturn_username
|
||||
RUSTFS_ACCESS_KEY=$rustfs_access_key
|
||||
RUSTFS_SECRET_KEY=$rustfs_secret_key
|
||||
ACCEPTANCE_NETWORK=${project}-heimdall-net
|
||||
HEIMDALL_DATA_VOLUME=${project}-heimdall-data
|
||||
EOF
|
||||
chmod 600 "$env_file"
|
||||
cat > "$override_file" <<'EOF'
|
||||
services:
|
||||
turn-test:
|
||||
image: coturn/coturn:4.6
|
||||
pull_policy: always
|
||||
profiles: [acceptance]
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478
|
||||
-W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn
|
||||
environment:
|
||||
COTURN_SECRET: ${COTURN_SECRET}
|
||||
COTURN_USERNAME: ${COTURN_USERNAME}
|
||||
depends_on:
|
||||
- coturn
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: ${ACCEPTANCE_NETWORK}
|
||||
external: false
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
|
||||
compose config --quiet
|
||||
compose config --format json | INSTALL_ROOT="$install_root" python3 -c '
|
||||
import json, os, sys
|
||||
config = json.load(sys.stdin)
|
||||
root = os.environ["INSTALL_ROOT"]
|
||||
expected = {
|
||||
"rustfs_access_key": os.path.join(root, "optional/secrets/rustfs_access_key"),
|
||||
"rustfs_secret_key": os.path.join(root, "optional/secrets/rustfs_secret_key"),
|
||||
"coturn_secret": os.path.join(root, "optional/secrets/coturn_secret"),
|
||||
}
|
||||
actual = {name: config["secrets"][name]["file"] for name in expected}
|
||||
if actual != expected:
|
||||
raise SystemExit("Compose secret bind mounts do not resolve under the installer root")
|
||||
print("Verified RustFS and coturn secret bind mounts resolve under the installer root.")
|
||||
'
|
||||
docker compose --project-directory "$install_root/optional" --env-file "$env_file" \
|
||||
-f "$backup_compose" --project-name "${project}-backup" config --format json |
|
||||
BACKUP_PROJECT_DIRECTORY="$install_root/optional" python3 -c '
|
||||
import json, os, sys
|
||||
config = json.load(sys.stdin)
|
||||
project_directory = os.environ["BACKUP_PROJECT_DIRECTORY"]
|
||||
expected_secret = os.path.join(project_directory, "secrets/db_password")
|
||||
expected_scripts = os.path.join(project_directory, "scripts")
|
||||
actual_secret = config["secrets"]["db_password"]["file"]
|
||||
scripts_mount = next((mount for mount in config["services"]["backup"]["volumes"]
|
||||
if mount.get("target") == "/scripts"), None)
|
||||
if actual_secret != expected_secret or scripts_mount is None or scripts_mount.get("source") != expected_scripts:
|
||||
raise SystemExit("Backup secret or script bind mounts do not resolve under optional/")
|
||||
print("Verified backup secret and scripts resolve under the installer optional directory.")
|
||||
'
|
||||
compose up -d rustfs coturn
|
||||
|
||||
base_url="http://127.0.0.1:$rustfs_api_port"
|
||||
deadline=$((SECONDS + 180))
|
||||
until curl -fsS "$base_url/health" >/dev/null 2>&1; do
|
||||
if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \
|
||||
"$rustfs_api_port" "$rustfs_console_port"
|
||||
|
||||
RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \
|
||||
RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY'
|
||||
import datetime, hashlib, hmac, os, urllib.error, urllib.request
|
||||
|
||||
access = os.environ['RUSTFS_ACCESS_KEY']
|
||||
secret = os.environ['RUSTFS_SECRET_KEY']
|
||||
host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT']
|
||||
path = '/acceptance'
|
||||
payload_hash = hashlib.sha256(b'').hexdigest()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
amz_date = now.strftime('%Y%m%dT%H%M%SZ')
|
||||
date = now.strftime('%Y%m%d')
|
||||
canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n'
|
||||
signed_headers = 'host;x-amz-content-sha256;x-amz-date'
|
||||
canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}'
|
||||
scope = f'{date}/us-east-1/s3/aws4_request'
|
||||
to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest()
|
||||
def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest()
|
||||
key = sign(('AWS4' + secret).encode(), date)
|
||||
key = sign(key, 'us-east-1')
|
||||
key = sign(key, 's3')
|
||||
key = sign(key, 'aws4_request')
|
||||
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}'
|
||||
request = urllib.request.Request(
|
||||
f'http://{host}{path}', data=b'', method='PUT',
|
||||
headers={'Host': host, 'x-amz-content-sha256': payload_hash,
|
||||
'x-amz-date': amz_date, 'Authorization': authorization})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status')
|
||||
except urllib.error.HTTPError as error:
|
||||
from xml.etree import ElementTree
|
||||
body = error.read()
|
||||
try: code = ElementTree.fromstring(body).findtext('{*}Code')
|
||||
except ElementTree.ParseError: code = None
|
||||
raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})')
|
||||
PY
|
||||
printf 'RustFS S3 authenticated bucket creation: passed.\n'
|
||||
|
||||
if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then
|
||||
echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2
|
||||
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' "$turn_log" | tail -30 >&2 || true
|
||||
echo 'sanitized coturn server diagnostics:' >&2
|
||||
compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \
|
||||
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' | tail -40 >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \
|
||||
"$coturn_port" "$relay_min" "$relay_max"
|
||||
|
||||
for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do
|
||||
if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then
|
||||
echo 'A generated service secret appeared in container logs.' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
printf 'Verified generated service secrets are absent from container logs.\n'
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
project="heimdall-renovate-acceptance-$(date -u +%Y%m%d%H%M%S)-$RANDOM"
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
compose_file="$temp_dir/compose.yml"
|
||||
runner_file="$temp_dir/acceptance.mjs"
|
||||
cert_file="$temp_dir/mock.crt"
|
||||
key_file="$temp_dir/mock.key"
|
||||
local_image_tags=()
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then cleanup_failed=1; fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
rm -f -- "$compose_file" "$runner_file" "$cert_file" "$key_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
echo "Disposable Compose cleanup failed for $project" >&2
|
||||
status=1
|
||||
else
|
||||
echo "Verified no project containers, volumes, or networks; no local images built ($project)"
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$key_file" -out "$cert_file" \
|
||||
-subj "/CN=localhost" -addext "subjectAltName=IP:127.0.0.1" -days 1 >/dev/null 2>&1
|
||||
cat > "$runner_file" <<'NODE'
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:https';
|
||||
import { checkGiteaAccess } from '/workspace/scripts/ci/renovate-preflight.mjs';
|
||||
|
||||
const requests = [];
|
||||
const server = createServer({
|
||||
key: readFileSync('/acceptance/mock.key'),
|
||||
cert: readFileSync('/acceptance/mock.crt'),
|
||||
}, (request, response) => {
|
||||
requests.push({ path: request.url, authorization: request.headers.authorization });
|
||||
if (request.headers.authorization !== 'token synthetic-valid') {
|
||||
response.writeHead(401, { 'content-type': 'application/json' });
|
||||
response.end('{"message":"credential rejected"}');
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, { 'content-type': 'application/json' });
|
||||
response.end('{}');
|
||||
});
|
||||
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const endpoint = `https://127.0.0.1:${server.address().port}/api/v1`;
|
||||
await checkGiteaAccess(endpoint, 'synthetic-valid');
|
||||
await assert.rejects(
|
||||
checkGiteaAccess(endpoint, 'synthetic-invalid'),
|
||||
error => error.message.includes('HTTP 401') &&
|
||||
error.message.includes('RENOVATE_TOKEN') &&
|
||||
!error.message.includes('synthetic-invalid') &&
|
||||
!error.message.includes('credential rejected'),
|
||||
);
|
||||
assert.deepEqual(requests.map(({ path }) => path), [
|
||||
'/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall',
|
||||
'/api/v1/user',
|
||||
]);
|
||||
assert.ok(requests.every(({ authorization }) =>
|
||||
['token synthetic-valid', 'token synthetic-invalid'].includes(authorization)));
|
||||
console.log('HTTPS mock preflight accepted valid and rejected invalid synthetic credentials without exposing response details.');
|
||||
} finally {
|
||||
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
NODE
|
||||
cat > "$compose_file" <<EOF
|
||||
services:
|
||||
acceptance:
|
||||
image: node:22-alpine
|
||||
working_dir: /workspace
|
||||
volumes:
|
||||
- "$repo_root:/workspace:ro"
|
||||
- "$temp_dir:/acceptance:ro"
|
||||
environment:
|
||||
NODE_EXTRA_CA_CERTS: /acceptance/mock.crt
|
||||
command: ["node", "/acceptance/acceptance.mjs"]
|
||||
EOF
|
||||
|
||||
docker compose -p "$project" -f "$compose_file" config --quiet
|
||||
docker compose -p "$project" -f "$compose_file" run --rm acceptance
|
||||
@@ -1,105 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
|
||||
project="heimdall-sentry-privacy-${suffix}"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
compose_file="$temp_dir/compose.yml"
|
||||
props_file="$temp_dir/acceptance.props"
|
||||
local_image_tags=()
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
# Cleanup must continue through every independent resource even when the
|
||||
# caller enabled errexit/nounset or an earlier Docker query failed.
|
||||
set +e
|
||||
set +u
|
||||
cleanup_failed=0
|
||||
docker compose --project-directory "$repo_root" --env-file "$env_file" \
|
||||
-f "$compose_file" -p "$project" down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" ]]; then
|
||||
while IFS= read -r container; do
|
||||
[[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1
|
||||
done <<< "$containers"
|
||||
fi
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
if ((${#local_image_tags[@]} == 0)); then
|
||||
printf 'Local images built: none; upstream SDK image retained.\n'
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$compose_file" "$props_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if ((cleanup_failed)); then
|
||||
printf 'Disposable Sentry privacy acceptance cleanup failed for %s\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
cat > "$env_file" <<EOF
|
||||
REPO_ROOT=$repo_root
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
ACCEPTANCE_DIR=$temp_dir
|
||||
ACCEPTANCE_UID=$(id -u)
|
||||
ACCEPTANCE_GID=$(id -g)
|
||||
EOF
|
||||
cat > "$props_file" <<'EOF'
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<BaseIntermediateOutputPath>/tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/</BaseIntermediateOutputPath>
|
||||
<MSBuildProjectExtensionsPath>/tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/</MSBuildProjectExtensionsPath>
|
||||
<BaseOutputPath>/tmp/$(ACCEPTANCE_PROJECT)/bin/$(MSBuildProjectName)/</BaseOutputPath>
|
||||
<DefaultItemExcludes>$(DefaultItemExcludes);**/obj/**;**/bin/**</DefaultItemExcludes>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
EOF
|
||||
cat > "$compose_file" <<'EOF'
|
||||
services:
|
||||
focused-tests:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
entrypoint: ["dotnet"]
|
||||
user: "${ACCEPTANCE_UID}:${ACCEPTANCE_GID}"
|
||||
working_dir: /workspace
|
||||
environment:
|
||||
ACCEPTANCE_PROJECT: ${ACCEPTANCE_PROJECT}
|
||||
volumes:
|
||||
- ${REPO_ROOT}:/workspace
|
||||
- ${ACCEPTANCE_DIR}:/acceptance
|
||||
command:
|
||||
- test
|
||||
- tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj
|
||||
- --filter
|
||||
- FullyQualifiedName~SentryTelemetryPrivacyTests
|
||||
- --verbosity
|
||||
- minimal
|
||||
- -p:RestoreLockedMode=true
|
||||
- -p:CustomBeforeDirectoryBuildProps=/acceptance/acceptance.props
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
|
||||
docker compose --project-directory "$repo_root" --env-file "$env_file" \
|
||||
-f "$compose_file" -p "$project" config --quiet
|
||||
docker compose --project-directory "$repo_root" --env-file "$env_file" \
|
||||
-f "$compose_file" -p "$project" run --rm focused-tests
|
||||
@@ -1,76 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')"
|
||||
project="heimdall-live-source-change-${suffix}"
|
||||
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
|
||||
compose_file="${temp_dir}/compose.json"
|
||||
source_archive="${temp_dir}/source.tar"
|
||||
local_image_tags=()
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
|
||||
printf 'Docker Compose is required for live source-change acceptance.\n' >&2
|
||||
rmdir -- "$temp_dir"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
if [[ -f "$compose_file" ]]; then
|
||||
docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
|
||||
fi
|
||||
containers="$(docker ps -aq --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
|
||||
volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
|
||||
networks="$(docker network ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
|
||||
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
rm -f -- "$compose_file" "$source_archive" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable acceptance cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
python3 - "$compose_file" "$source_archive" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
compose_path, archive_path = sys.argv[1:]
|
||||
test_command = """set -euo pipefail
|
||||
mkdir -p /tmp/heimdall-source
|
||||
tar -xf /source.tar -C /tmp/heimdall-source
|
||||
cd /tmp/heimdall-source
|
||||
dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
|
||||
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --configuration Release -m:1 --filter FullyQualifiedName~LiveCameraRelayServiceTests
|
||||
"""
|
||||
document = {
|
||||
"services": {
|
||||
"source-change-tests": {
|
||||
"image": "mcr.microsoft.com/dotnet/sdk:10.0",
|
||||
"entrypoint": ["bash", "-euc"],
|
||||
"command": [test_command],
|
||||
"volumes": [f"{archive_path}:/source.tar:ro"],
|
||||
}
|
||||
}
|
||||
}
|
||||
with open(compose_path, "w", encoding="utf-8") as compose_file:
|
||||
json.dump(document, compose_file)
|
||||
PY
|
||||
|
||||
# Archive only tracked and non-ignored working files; exclude multi-gigabyte
|
||||
# ignored build/model outputs from the disposable SDK container.
|
||||
git -C "$repo_root" ls-files -z --cached --others --exclude-standard |
|
||||
tar -C "$repo_root" --null -T - -cf "$source_archive"
|
||||
|
||||
printf 'Project: %s\n' "$project"
|
||||
printf 'Local images built: none (upstream .NET SDK image only)\n'
|
||||
docker compose -p "$project" -f "$compose_file" up --abort-on-container-exit --exit-code-from source-change-tests
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline acceptance for one tagged image and installer release with synthetic doubles."""
|
||||
"""Offline acceptance for package.sh and publish.sh using synthetic credentials and API doubles."""
|
||||
import base64
|
||||
import email
|
||||
import hashlib
|
||||
@@ -19,6 +19,7 @@ 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
|
||||
@@ -50,7 +51,7 @@ def main():
|
||||
fakebin = temp / 'bin'
|
||||
fakebin.mkdir()
|
||||
docker_log = temp / 'docker-commands.jsonl'
|
||||
release_state = {'release': None, 'assets': {}, 'authorized': 0}
|
||||
release_state = {'draft': None, 'assets': {}, 'authorized': 0}
|
||||
|
||||
subprocess.run([
|
||||
'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes',
|
||||
@@ -67,22 +68,14 @@ 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']:
|
||||
sys.exit(12) # Release publication must reuse the scanned image builds.
|
||||
target = args[args.index('-t') + 1]
|
||||
sys.exit(0)
|
||||
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] == ['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[:2] == ['manifest', 'inspect']:
|
||||
sys.exit(1) # Simulate absent remote tags; never call a registry.
|
||||
if args[:1] == ['tag']:
|
||||
sys.exit(0)
|
||||
if args[:1] == ['push']:
|
||||
@@ -95,10 +88,7 @@ if args[:2] == ['image', 'inspect']:
|
||||
digest = os.environ['OFFLINE_AGENT_DIGEST']
|
||||
else:
|
||||
digest = os.environ['OFFLINE_SERVER_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'])
|
||||
print(image + '@' + digest)
|
||||
sys.exit(0)
|
||||
if args[:1] == ['save']:
|
||||
from pathlib import Path
|
||||
@@ -123,42 +113,6 @@ 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'):
|
||||
installer_path = os.environ['OFFLINE_INSTALLER_ZIP']
|
||||
if os.environ.get('OFFLINE_BAD_API_DIGEST') == '1':
|
||||
digest = 'invalid'
|
||||
elif os.environ.get('OFFLINE_NULL_ASSET_DIGEST') == '1':
|
||||
digest = None
|
||||
else:
|
||||
digest = 'sha256:' + hashlib.sha256(open(installer_path,'rb').read()).hexdigest()
|
||||
payload = json.dumps({'tag_name':'1.2.3','assets':[{
|
||||
'name':'heimdall-installers-1.2.3.zip',
|
||||
'digest':digest,
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}, {
|
||||
'name':'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]}).encode()
|
||||
open(output, 'wb').write(payload)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip.sha256':
|
||||
if os.environ.get('OFFLINE_BAD_CHECKSUM') == '1':
|
||||
open(output, 'w').write('0' * 64 + ' heimdall-installers-1.2.3.zip\n')
|
||||
else:
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'] + '.sha256', output)
|
||||
else:
|
||||
sys.exit(22)
|
||||
'''
|
||||
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):
|
||||
@@ -179,45 +133,11 @@ else:
|
||||
self.wfile.write(payload)
|
||||
|
||||
def do_GET(self):
|
||||
path = urlsplit(self.path).path
|
||||
if path == '/token':
|
||||
expected = 'Basic ' + base64.b64encode(
|
||||
b'offline-user:' + DOCKER_TOKEN.encode()).decode('ascii')
|
||||
if self.headers.get('Authorization') != expected:
|
||||
self._json(401, {})
|
||||
return
|
||||
self._json(200, {'token': 'offline-registry-bearer'})
|
||||
return
|
||||
if path.startswith('/v2/') and '/manifests/sha-' in path:
|
||||
if self.headers.get('Authorization') != 'Bearer offline-registry-bearer':
|
||||
self._json(401, {})
|
||||
return
|
||||
if self.headers.get('Accept') is None:
|
||||
self._json(406, {})
|
||||
return
|
||||
digest = (GPU_AGENT_DIGEST if 'heimdall-agent-gpu' in path else
|
||||
AGENT_DIGEST if 'heimdall-agent' in path else SERVER_DIGEST)
|
||||
self.send_response(200)
|
||||
self.send_header('Docker-Content-Digest', digest)
|
||||
self.send_header('Content-Length', '0')
|
||||
self.end_headers()
|
||||
return
|
||||
if not self._authorized():
|
||||
self._json(401, {})
|
||||
return
|
||||
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('/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'}, {
|
||||
'name': 'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]})
|
||||
elif path.endswith('/releases/tags/1.2.3'):
|
||||
path = urlsplit(self.path).path
|
||||
if path.endswith('/releases/tags/' + TAG):
|
||||
self._json(404, {'message': 'not found'})
|
||||
elif path.endswith('/releases/7301/assets'):
|
||||
self._json(200, [])
|
||||
@@ -232,16 +152,12 @@ else:
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
|
||||
if path.endswith('/releases'):
|
||||
release = json.loads(body)
|
||||
assert release['tag_name'] == '1.2.3'
|
||||
assert release['name'] == '1.2.3'
|
||||
assert release['tag_name'] == TAG
|
||||
assert release['draft'] 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()
|
||||
release_state['release'] = release
|
||||
self._json(201, {'id': 7301, 'draft': True, 'prerelease': True,
|
||||
'tag_name': release['tag_name'],
|
||||
release_state['draft'] = release
|
||||
self._json(201, {'id': 7301, 'draft': True,
|
||||
'html_url': 'https://gitea.test/releases/7301'})
|
||||
return
|
||||
if path.endswith('/releases/7301/assets'):
|
||||
@@ -259,24 +175,6 @@ else:
|
||||
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',
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256'}
|
||||
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
release_state['release']['draft'] = body['draft']
|
||||
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)
|
||||
@@ -292,119 +190,21 @@ else:
|
||||
'SSL_CERT_FILE': str(cert),
|
||||
'NO_PROXY': '127.0.0.1,localhost',
|
||||
'no_proxy': '127.0.0.1,localhost',
|
||||
'BUILD_REF': 'refs/tags/1.2.3',
|
||||
'BUILD_REF': 'refs/tags/' + TAG,
|
||||
'BUILD_REPOSITORY': REPOSITORY,
|
||||
'BUILD_RUN_ID': 'offline-acceptance',
|
||||
'BUILD_SERVER_URL': origin,
|
||||
'EXPECTED_BUILD_SERVER_URL': origin,
|
||||
'DOCKERHUB_USERNAME': 'offline-user',
|
||||
'DOCKERHUB_TOKEN': DOCKER_TOKEN,
|
||||
'DOCKER_REGISTRY_TOKEN_URL': origin,
|
||||
'DOCKER_REGISTRY_URL': origin,
|
||||
'RELEASE_TOKEN': RELEASE_TOKEN,
|
||||
'RELEASE_SIGNING_KEY_B64': signing_key_b64,
|
||||
'OFFLINE_DOCKER_LOG': str(docker_log),
|
||||
'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',
|
||||
]
|
||||
checksum_log = curl_log
|
||||
checksum_env = launcher_env.copy()
|
||||
checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(checksum_log),
|
||||
'OFFLINE_NULL_ASSET_DIGEST': '1',
|
||||
'HEIMDALL_INSTALLER_VERSION': '',
|
||||
})
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=checksum_env, capture_output=True, text=True)
|
||||
checksum_output = checksum_launcher.stdout + checksum_launcher.stderr
|
||||
assert checksum_launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
|
||||
f'checksum fallback exit={checksum_launcher.returncode}; '
|
||||
f'URLs={checksum_log.read_text() if checksum_log.exists() else "<none>"}; '
|
||||
+ checksum_output[-2000:])
|
||||
assert checksum_log.read_text().splitlines() == [
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
], (f'checksum fallback did not request expected assets; '
|
||||
f'HEIMDALL_INSTALLER_VERSION={checksum_env.get("HEIMDALL_INSTALLER_VERSION")!r}; '
|
||||
f'log={checksum_log.read_text() if checksum_log.exists() else "<missing>"}; '
|
||||
f'returncode={checksum_launcher.returncode}; output={checksum_output[-2000:]}')
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
bad_checksum_log = temp / 'installer-bootstrap-bad-checksum-urls.txt'
|
||||
bad_checksum_env = checksum_env.copy()
|
||||
bad_checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(bad_checksum_log),
|
||||
'OFFLINE_BAD_CHECKSUM': '1',
|
||||
})
|
||||
bad_checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=bad_checksum_env, capture_output=True, text=True)
|
||||
bad_checksum_output = bad_checksum_launcher.stdout + bad_checksum_launcher.stderr
|
||||
assert bad_checksum_launcher.returncode != 0 and 'ne correspond pas à la release' in bad_checksum_output, (
|
||||
f'bad checksum was not rejected; returncode={bad_checksum_launcher.returncode}; '
|
||||
f'output={bad_checksum_output[-2000:]}')
|
||||
assert bad_checksum_log.read_text().splitlines() == [
|
||||
bad_checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
invalid_digest_log = temp / 'installer-bootstrap-invalid-digest-urls.txt'
|
||||
invalid_digest_env = checksum_env.copy()
|
||||
invalid_digest_env.update({
|
||||
'OFFLINE_CURL_LOG': str(invalid_digest_log),
|
||||
'OFFLINE_BAD_API_DIGEST': '1',
|
||||
})
|
||||
invalid_digest_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=invalid_digest_env, capture_output=True, text=True)
|
||||
invalid_digest_output = invalid_digest_launcher.stdout + invalid_digest_launcher.stderr
|
||||
assert invalid_digest_launcher.returncode != 0 and 'digest Gitea du bundle est invalide' in invalid_digest_output, (
|
||||
f'malformed API digest was not rejected; returncode={invalid_digest_launcher.returncode}; '
|
||||
f'output={invalid_digest_output[-2000:]}')
|
||||
assert invalid_digest_log.read_text().splitlines() == [
|
||||
invalid_digest_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
]
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
env['GITEA_TOKEN'] = RELEASE_TOKEN
|
||||
env['BEFORE_SHA'] = commit + '^'
|
||||
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'
|
||||
@@ -414,73 +214,49 @@ else:
|
||||
signature = temp / 'manifest.sig'
|
||||
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert manifest['version'] == '1.2.3'
|
||||
assert manifest['version'] == TAG
|
||||
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((packages / 'provenance.json').read_text())
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/1.2.3'
|
||||
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
|
||||
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}-1.2.3.tar.gz'
|
||||
archive = f'heimdall-agent-{platform}-{TAG.removeprefix("v")}.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 = (packages / 'SHA256SUMS').read_text().splitlines()
|
||||
checksums = release_state['assets']['SHA256SUMS'].decode().splitlines()
|
||||
for line in checksums:
|
||||
digest, filename = line.split(maxsplit=1)
|
||||
filename = filename.lstrip('* ')
|
||||
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()
|
||||
checksum_asset = packages / 'heimdall-installers-1.2.3.zip.sha256'
|
||||
checksum, filename = checksum_asset.read_text().split()
|
||||
assert filename == 'heimdall-installers-1.2.3.zip'
|
||||
assert checksum == hashlib.sha256((packages / filename).read_bytes()).hexdigest()
|
||||
expected_release_assets = {
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'agent-image.json', 'agent-image-gpu.json',
|
||||
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
|
||||
}
|
||||
assert set(release_state['assets']) == expected_release_assets
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
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) == 0
|
||||
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) == 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']) == len(expected_release_assets)
|
||||
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',
|
||||
}
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 1
|
||||
assert release_state['draft']['draft'] is True
|
||||
assert len(release_state['assets']) >= 9
|
||||
assert release_state['authorized'] >= 7
|
||||
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(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('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
"""Create the next immutable version tag for a successfully validated merged PR."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
VERSION = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
|
||||
ASSESSMENT = re.compile(
|
||||
r"(?im)^\s*Release assessment:\s*(none|patch|minor|major)\s*—\s*(.*?)\s*$"
|
||||
)
|
||||
SHA = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$", re.IGNORECASE)
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(message)
|
||||
|
||||
|
||||
server = os.environ.get("BUILD_SERVER_URL", "").rstrip("/")
|
||||
repository = os.environ.get("BUILD_REPOSITORY", "")
|
||||
sha = os.environ.get("CURRENT_SHA", "").lower()
|
||||
token = os.environ.get("GITEA_TOKEN", "")
|
||||
if not server.startswith("https://"):
|
||||
fail("BUILD_SERVER_URL must use HTTPS")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
|
||||
fail("BUILD_REPOSITORY is not a valid owner/repository")
|
||||
if not SHA.fullmatch(sha):
|
||||
fail("CURRENT_SHA is not a full Git commit SHA")
|
||||
if not token:
|
||||
fail("GITEA_TOKEN is unavailable to the release-tag job")
|
||||
|
||||
api = f"{server}/api/v1/repos/{repository}"
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status):
|
||||
self.status = status
|
||||
|
||||
|
||||
def request(path, method="GET", body=None, allow_missing=False):
|
||||
payload = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Authorization": "token " + token, "Accept": "application/json"}
|
||||
if payload is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(api + path, data=payload, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else None
|
||||
except urllib.error.HTTPError as error:
|
||||
if allow_missing and error.code == 404:
|
||||
return None
|
||||
raise ApiError(error.code) from None
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
fail("Gitea API request failed due to a network or TLS error")
|
||||
|
||||
|
||||
def verify_tag(tag_name, expected_sha):
|
||||
existing = request("/tags/" + urllib.parse.quote(tag_name, safe=""), allow_missing=True)
|
||||
if existing is None:
|
||||
return False
|
||||
actual_sha = (existing.get("commit") or {}).get("sha", "").lower()
|
||||
if actual_sha != expected_sha:
|
||||
fail(f"Refusing to overwrite existing tag {tag_name} at a different commit")
|
||||
print(f"Version tag already points to this commit: {tag_name}")
|
||||
return True
|
||||
|
||||
|
||||
try:
|
||||
subprocess.run(["git", "cat-file", "-e", f"{sha}^{{commit}}"], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
fail("The pushed commit is missing from the checked-out Git history")
|
||||
|
||||
try:
|
||||
pull = request(f"/commits/{sha}/pull", allow_missing=True)
|
||||
except ApiError as error:
|
||||
fail(f"Could not inspect the merged pull request (Gitea HTTP {error.status})")
|
||||
|
||||
if pull is None:
|
||||
print("No pull request is associated with this main push; no version tag created")
|
||||
sys.exit(0)
|
||||
if not pull.get("merged") or pull.get("state") != "closed":
|
||||
print("The associated pull request is not merged; no version tag created")
|
||||
sys.exit(0)
|
||||
if (pull.get("base") or {}).get("ref") != "main":
|
||||
print("The associated pull request did not target main; no version tag created")
|
||||
sys.exit(0)
|
||||
if (pull.get("merge_commit_sha") or "").lower() != sha:
|
||||
fail("The pull request merge SHA does not match the main push SHA")
|
||||
|
||||
body = pull.get("body") or ""
|
||||
assessment_lines = [line for line in body.splitlines()
|
||||
if re.match(r"^\s*Release assessment:", line, re.IGNORECASE)]
|
||||
matches = [ASSESSMENT.fullmatch(line) for line in assessment_lines]
|
||||
if len(matches) != 1 or matches[0] is None:
|
||||
fail("Merged PR must contain exactly one machine-readable 'Release assessment: <none|patch|minor|major> — <rationale>' line")
|
||||
assessment, rationale = matches[0].groups()
|
||||
if not rationale.strip() or rationale.strip().lower() in {"rationale", "reason", "<rationale>"}:
|
||||
fail("Merged PR release assessment must include a concrete rationale")
|
||||
if assessment == "none":
|
||||
print("Merged PR is explicitly assessed as no release; no version tag created")
|
||||
sys.exit(0)
|
||||
|
||||
try:
|
||||
tags = subprocess.run(["git", "tag", "--merged", sha, "--sort=-version:refname"],
|
||||
check=True, capture_output=True, text=True).stdout.splitlines()
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
fail("Could not read reachable version tags from the checked-out Git history")
|
||||
|
||||
versions = []
|
||||
for name in tags:
|
||||
match = VERSION.fullmatch(name)
|
||||
if match:
|
||||
versions.append((tuple(int(part) for part in match.groups()), name))
|
||||
if not versions:
|
||||
fail("No reachable stable MAJOR.MINOR.PATCH tag was found; refusing to guess a version")
|
||||
|
||||
(major, minor, patch), previous = max(versions, key=lambda version: version[0])
|
||||
if assessment == "major":
|
||||
major, minor, patch = major + 1, 0, 0
|
||||
elif assessment == "minor":
|
||||
major, minor, patch = major, minor + 1, 0
|
||||
else:
|
||||
major, minor, patch = major, minor, patch + 1
|
||||
tag_name = f"{major}.{minor}.{patch}"
|
||||
|
||||
try:
|
||||
if verify_tag(tag_name, sha):
|
||||
sys.exit(0)
|
||||
created = request("/tags", method="POST", body={
|
||||
"tag_name": tag_name,
|
||||
"target": sha,
|
||||
"message": f"Heimdall {tag_name}",
|
||||
})
|
||||
except ApiError as error:
|
||||
if error.status in (409, 422) and verify_tag(tag_name, sha):
|
||||
sys.exit(0)
|
||||
fail(f"Could not create version tag {tag_name} (Gitea HTTP {error.status})")
|
||||
|
||||
created_sha = (created.get("commit") or {}).get("sha", "").lower()
|
||||
if created.get("name") != tag_name or created_sha != sha:
|
||||
fail("Gitea tag creation response did not confirm the requested immutable target")
|
||||
print(f"Created {tag_name} from {assessment} impact after CI policy passed; previous stable tag: {previous}; target commit: {sha}")
|
||||
@@ -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 jq python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git 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
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve the canonical digest for an immutable Docker Hub repository tag."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def endpoint(name, default, path):
|
||||
value = os.environ.get(name, default).rstrip('/')
|
||||
if not value.startswith('https://') or '@' in value:
|
||||
raise SystemExit('Registry endpoint must be HTTPS')
|
||||
return value + path
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
raise SystemExit('usage: dockerhub-tag-digest.py REPOSITORY IMMUTABLE_TAG')
|
||||
repository, tag = sys.argv[1:]
|
||||
if not re.fullmatch(r'[a-z0-9._-]+/[a-z0-9._-]+', repository):
|
||||
raise SystemExit('Invalid Docker Hub repository')
|
||||
if not re.fullmatch(r'sha-[0-9a-f]{40}', tag):
|
||||
raise SystemExit('Expected an immutable full-commit image tag')
|
||||
username = os.environ.get('DOCKERHUB_USERNAME', '')
|
||||
password = os.environ.get('DOCKERHUB_TOKEN', '')
|
||||
if not username or not password:
|
||||
raise SystemExit('Docker Hub credentials are required to resolve image digest')
|
||||
|
||||
token_url = endpoint('DOCKER_REGISTRY_TOKEN_URL', 'https://auth.docker.io',
|
||||
'/token?' + urlencode({'service': 'registry.docker.io',
|
||||
'scope': 'repository:' + repository + ':pull'}))
|
||||
registry_url = endpoint('DOCKER_REGISTRY_URL', 'https://registry-1.docker.io',
|
||||
'/v2/' + repository + '/manifests/' + tag)
|
||||
import base64
|
||||
credentials = base64.b64encode((username + ':' + password).encode()).decode('ascii')
|
||||
try:
|
||||
token_request = Request(token_url, headers={'Authorization': 'Basic ' + credentials,
|
||||
'Accept': 'application/json'})
|
||||
with urlopen(token_request, timeout=30) as response:
|
||||
token_data = json.load(response)
|
||||
bearer = token_data.get('token') or token_data.get('access_token')
|
||||
if not isinstance(bearer, str) or not bearer:
|
||||
raise SystemExit('Docker Hub did not return a registry bearer token')
|
||||
manifest_request = Request(registry_url, headers={
|
||||
'Authorization': 'Bearer ' + bearer,
|
||||
'Accept': ', '.join([
|
||||
'application/vnd.oci.image.index.v1+json',
|
||||
'application/vnd.docker.distribution.manifest.list.v2+json',
|
||||
'application/vnd.oci.image.manifest.v1+json',
|
||||
'application/vnd.docker.distribution.manifest.v2+json',
|
||||
]),
|
||||
})
|
||||
with urlopen(manifest_request, timeout=30) as response:
|
||||
digest = response.headers.get('Docker-Content-Digest', '')
|
||||
except (HTTPError, URLError, TimeoutError, OSError, ValueError):
|
||||
raise SystemExit('Unable to resolve immutable Docker Hub image digest')
|
||||
if not re.fullmatch(r'sha256:[0-9a-f]{64}', digest):
|
||||
raise SystemExit('Docker Hub returned an invalid image digest')
|
||||
print(digest)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,11 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
if [[ "${BUILD_REF:-}" == refs/tags/* ]]; then
|
||||
version=${BUILD_REF#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}")
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
|
||||
+18
-53
@@ -2,68 +2,33 @@
|
||||
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}"
|
||||
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
|
||||
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
|
||||
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
|
||||
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':['Agent native updater'], 'rids':['portable-framework-dependent'],
|
||||
'targets':['Web/PWA','Agent'], 'rids':['portable-framework-dependent'],
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
|
||||
installer_bundle="artifacts/packages/heimdall-installers-$version.zip"
|
||||
(cd artifacts/packages && sha256sum "$(basename "$installer_bundle")" > "$(basename "$installer_bundle").sha256")
|
||||
(cd artifacts/packages && sha256sum *.tar.gz provenance.json > SHA256SUMS)
|
||||
printf '%s' "$version" > artifacts/version
|
||||
+21
-13
@@ -33,19 +33,21 @@ 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/tags/* ]] || { echo 'Release publication is restricted to version tags MAJOR.MINOR.PATCH' >&2; exit 1; }
|
||||
tag=${BUILD_REF#refs/tags/}
|
||||
[[ "$BUILD_REF" == refs/tags/v* ]] || exit 1
|
||||
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'] != sys.argv[2] or p['ref'] != 'refs/tags/' + sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match the verified version tag')
|
||||
if p['commit'] != sys.argv[1] or 'v'+p['version'] != sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match checkout/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
|
||||
# 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.
|
||||
printf '%s' "${tag#v}" > 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.
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
|
||||
@@ -64,11 +66,17 @@ for component in server agent agent-gpu; do
|
||||
else
|
||||
image=$server_image
|
||||
fi
|
||||
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; }
|
||||
digest=$(python3 scripts/ci/dockerhub-tag-digest.py "$image" "sha-$sha")
|
||||
printf '%s@%s\n' "$image" "$digest" >> artifacts/image-digests.txt
|
||||
for image_tag in "sha-$sha" "${tag#v}"; 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
|
||||
done
|
||||
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
|
||||
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
|
||||
@@ -113,7 +121,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=package_version
|
||||
version='v'+package_version
|
||||
assets={}
|
||||
for path in root.glob('heimdall-agent-*.tar.gz'):
|
||||
suffix=f'-{package_version}.tar.gz'
|
||||
|
||||
+18
-18
@@ -1,14 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
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
|
||||
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
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
@@ -22,14 +17,19 @@ 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
|
||||
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"
|
||||
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"
|
||||
fi
|
||||
+19
-51
@@ -1,4 +1,4 @@
|
||||
"""Create/update the Gitea release for one verified version tag."""
|
||||
"""Create/update only a draft Gitea release; never log auth or response bodies."""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
@@ -8,11 +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 = 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
|
||||
@@ -28,53 +26,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_root = Path('artifacts/packages')
|
||||
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
|
||||
installer_checksum = package_root / f'{installer_bundle.name}.sha256'
|
||||
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
|
||||
required_assets = [installer_bundle, installer_checksum, package_root / 'agent-release-public.pem',
|
||||
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
|
||||
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
|
||||
if any(not path.is_file() for path in required_assets) or not agent_archives:
|
||||
raise SystemExit('Installer bundle or signed Agent update assets are missing')
|
||||
# CI provenance, image digests, and general checksum bookkeeping stay in the
|
||||
# build artifacts. Publish the installer bundle's checksum as a sidecar so
|
||||
# bootstraps can verify it when the Gitea asset API omits its digest field.
|
||||
package_files = sorted([*required_assets, *agent_archives])
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
|
||||
'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()})
|
||||
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:
|
||||
'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"):
|
||||
request(f"/releases/{release['id']}/assets/{asset['id']}", 'DELETE')
|
||||
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)
|
||||
|
||||
expected_prerelease = '-' in provenance['version']
|
||||
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'])
|
||||
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'])
|
||||
@@ -1,48 +0,0 @@
|
||||
"""Generate release notes from pull requests merged since the previous version tag."""
|
||||
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).')
|
||||
@@ -9,12 +9,12 @@ export function validateEndpoint(value) {
|
||||
try {
|
||||
parsed = new URL(value);
|
||||
} catch {
|
||||
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'https:' || parsed.username || parsed.password ||
|
||||
parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) {
|
||||
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
}
|
||||
|
||||
return parsed.href.replace(/\/$/, '');
|
||||
@@ -38,7 +38,7 @@ export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fet
|
||||
if (!response.ok) {
|
||||
const detail = response.status === 401 || response.status === 403
|
||||
? 'Check that RENOVATE_TOKEN is active and has repository read and write access.'
|
||||
: 'Check FORGEJO_API_ENDPOINT and the Forgejo API availability.';
|
||||
: 'Check GITEA_API_ENDPOINT and the Gitea API availability.';
|
||||
throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
|
||||
|
||||
test('accepts an HTTPS Forgejo API endpoint and trims its trailing slash', () => {
|
||||
test('accepts an HTTPS Gitea API endpoint and trims its trailing slash', () => {
|
||||
assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1');
|
||||
});
|
||||
|
||||
test('rejects non-HTTPS, malformed, and non-API endpoints', () => {
|
||||
for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) {
|
||||
assert.throws(() => validateEndpoint(value), /FORGEJO_API_ENDPOINT.*HTTPS URL ending in \/api\/v1/);
|
||||
assert.throws(() => validateEndpoint(value), /HTTPS URL ending in \/api\/v1/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+7
-38
@@ -9,8 +9,6 @@ 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]:
|
||||
@@ -21,30 +19,6 @@ 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
|
||||
@@ -57,11 +31,11 @@ def changed_files() -> list[str] | None:
|
||||
|
||||
def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
if changed is None:
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": [], "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, {}, "all")}
|
||||
return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]}
|
||||
|
||||
all_paths = {p.resolve() for p in ALL_PROJECTS}
|
||||
all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | {
|
||||
p.resolve() for p in (ROOT / "tests").glob("*/*.csproj")
|
||||
}
|
||||
graph = {project: references(project) for project in all_paths}
|
||||
changed_projects: set[Path] = set()
|
||||
broad = False
|
||||
@@ -85,12 +59,10 @@ 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": [], "build_projects": []}
|
||||
return {"mode": "affected", "changed": changed, "suites": []}
|
||||
|
||||
if broad or (changed and not changed_projects):
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": changed, "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, graph, "all")}
|
||||
return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]}
|
||||
|
||||
affected = set(changed_projects)
|
||||
while True:
|
||||
@@ -100,9 +72,7 @@ def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
affected |= additions
|
||||
|
||||
suites = [p.stem for p in TESTS if p.resolve() in affected]
|
||||
projects = build_targets(affected, suites, graph, "affected")
|
||||
return {"mode": "affected", "changed": changed, "suites": suites,
|
||||
"build_projects": projects}
|
||||
return {"mode": "affected", "changed": changed, "suites": suites}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -111,4 +81,3 @@ 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'}")
|
||||
+24
-152
@@ -1,4 +1,4 @@
|
||||
"""Contract tests for security gates and versioned release uploads, without network."""
|
||||
"""Contract tests for security gates and draft release uploads, without network."""
|
||||
import contextlib
|
||||
import io
|
||||
import importlib.util
|
||||
@@ -6,7 +6,6 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -16,87 +15,6 @@ 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 PublicationWorkflowTests(unittest.TestCase):
|
||||
def test_release_write_token_is_tag_only_and_not_a_long_lived_pat_secret(self):
|
||||
workflow = (REPO_ROOT/'.gitea/workflows/build.yml').read_text()
|
||||
self.assertNotIn('secrets.RELEASE_TOKEN', workflow)
|
||||
self.assertEqual(workflow.count('secrets.GITEA_TOKEN'), 3)
|
||||
publish = workflow.split(' publish:\n', 1)[1]
|
||||
self.assertIn("startsWith(gitea.ref, 'refs/tags/')", publish)
|
||||
self.assertIn(' contents: write', publish)
|
||||
self.assertIn(' pull-requests: read', publish)
|
||||
before_publish = workflow.split(' publish:\n', 1)[0]
|
||||
self.assertIn(' create_release_tag:\n', before_publish)
|
||||
self.assertIn("needs.policy.result == 'success'", before_publish)
|
||||
self.assertIn(' contents: write', before_publish)
|
||||
self.assertIn(' pull-requests: read', before_publish)
|
||||
self.assertNotIn('secrets.GITEA_TOKEN', before_publish.split(' create_release_tag:\n', 1)[0])
|
||||
|
||||
class PowerShellInstallerTests(unittest.TestCase):
|
||||
def test_optional_compose_commands_resolve_paths_from_install_root(self):
|
||||
linux_installer = (REPO_ROOT/'install/install-server.sh').read_text()
|
||||
windows_installer = (REPO_ROOT/'install/install-server.ps1').read_text()
|
||||
self.assertIn('compose_project_directory="$destination"', linux_installer)
|
||||
self.assertIn('compose_project_directory="$destination/optional"', linux_installer)
|
||||
self.assertIn('docker compose --project-directory "$compose_project_directory"',
|
||||
linux_installer)
|
||||
self.assertIn("$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }",
|
||||
windows_installer)
|
||||
self.assertIn("Invoke-DockerCompose @('--project-directory', $composeProjectDirectory,",
|
||||
windows_installer)
|
||||
|
||||
@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())
|
||||
@@ -125,12 +43,6 @@ 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)
|
||||
@@ -162,54 +74,20 @@ class TestPlanTests(unittest.TestCase):
|
||||
self.assertIn('Heimdall.E2E.Tests', suites)
|
||||
|
||||
def test_agent_change_does_not_run_unrelated_web_tests(self):
|
||||
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
|
||||
suites = plan['suites']
|
||||
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['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()
|
||||
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'], [])
|
||||
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
|
||||
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
|
||||
|
||||
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):
|
||||
@@ -285,7 +163,7 @@ class AdvisoryTests(unittest.TestCase):
|
||||
self.assertNotEqual(self.check(report), 0)
|
||||
|
||||
class ReleaseTests(unittest.TestCase):
|
||||
def execute(self):
|
||||
def execute(self, public=False):
|
||||
calls = []
|
||||
class Response(io.BytesIO):
|
||||
def __enter__(self): return self
|
||||
@@ -293,46 +171,40 @@ 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': '1.2.3',
|
||||
return Response(json.dumps({'id': 7, 'draft': not public,
|
||||
'html_url': 'https://example.test/releases/7'}).encode())
|
||||
if req.method == 'GET':
|
||||
names = ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
|
||||
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
|
||||
return Response(b'[{"id":8}]')
|
||||
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':'1.2.3'}))
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
|
||||
(directory/name).write_bytes(b'archive')
|
||||
(directory/'agent-release-public.pem').write_bytes(b'key')
|
||||
notes = Path(temp)/'release-notes.md'
|
||||
notes.write_text('- Feature from PR #3.\n')
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42'}))
|
||||
(directory/'package.tar.gz').write_bytes(b'archive')
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(temp)
|
||||
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
|
||||
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
|
||||
'RELEASE_NOTES_FILE':str(notes)}), \
|
||||
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/tags/v1.2.3','RELEASE_TOKEN':'dummy'}), \
|
||||
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
|
||||
try:
|
||||
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
||||
except SystemExit as result:
|
||||
if result.code != 0:
|
||||
raise
|
||||
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
||||
finally:
|
||||
os.chdir(original)
|
||||
return calls
|
||||
|
||||
def test_complete_published_release_is_not_mutated_on_rerun(self):
|
||||
def test_draft_assets_use_multipart_and_delete_accepts_204(self):
|
||||
calls = self.execute()
|
||||
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'])
|
||||
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)
|
||||
|
||||
class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
|
||||
@@ -340,8 +212,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('installer ZIP', result.stdout)
|
||||
self.assertIn('selective Docker Hub tags', result.stdout)
|
||||
self.assertIn('CPU/GPU image digests', result.stdout)
|
||||
self.assertIn('six simulated pushes', result.stdout)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: heimdall-agent-install-assets
|
||||
description: Serve and validate native Heimdall Agent installer assets from Central.
|
||||
---
|
||||
|
||||
# Native Agent installer assets
|
||||
|
||||
Read `AGENTS.md`, the `AGENT-INSTALL-ASSETS` Gitea issue, and `skills/compose-disposable-recipe/SKILL.md` before changing Central asset delivery.
|
||||
|
||||
`Heimdall.Web.csproj` publishes the Linux/Windows installers and supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files. The default MIME table does not recognize `.py`, so explicitly map `.py` with `FileExtensionContentTypeProvider`; otherwise the supervisor returns 404 even when the file exists in the publish output.
|
||||
|
||||
For acceptance, build Central from the changed source in a disposable Compose project. Require `/healthz` healthy and GET `/install/install-agent.sh` plus `/install/agent-supervisor.py`; both must return HTTP 200 and byte-for-byte match `install/` sources. Use generated credentials, isolated ports/project volumes/network, a unique local image tag, and an EXIT cleanup trap installed before build. Verify no project containers, volumes, or networks remain and remove/verify absence of the exact built tag. Keep shared base images.
|
||||
|
||||
This proves only source-built Central behavior. Verify the deployed Central after its image has been published and restarted before considering a field incident resolved.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: agent-runtime-acceptance
|
||||
description: Validate Heimdall Agent reconnect, camera configuration replacement, acknowledgement, and runtime diagnostics without camera hardware.
|
||||
---
|
||||
|
||||
# Heimdall Agent runtime acceptance
|
||||
|
||||
Read `AGENTS.md`, the relevant Agent Gitea issue, and `skills/heimdall-dotnet/SKILL.md` before changing Agent runtime behavior.
|
||||
|
||||
## Camera configuration synchronization
|
||||
|
||||
- `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically.
|
||||
- The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body.
|
||||
- Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again.
|
||||
- `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`.
|
||||
- Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values.
|
||||
|
||||
## Central log upload contract
|
||||
|
||||
- Agent log levels must use the exact `AgentLogLevel` names accepted by Central's parser: `Information` and `Warning` (not the common aliases `Info`/`Warn`), alongside `Trace`, `Debug`, `Error`, and `Critical`.
|
||||
- Keep `ToCentralLevel_MapsMicrosoftNamesToAgentContract` asserting both the emitted name and that Central's enum parser accepts it at the corresponding severity.
|
||||
- Agent logging is API-key authenticated. A source-built disposable Compose check can register a synthetic Agent, submit one entry at each severity to `/api/agents/{id}/logs`, and read them back through the authorized Central log query. Keep generated credentials and project resources isolated and clean up exact locally built tags per the Compose recipe.
|
||||
|
||||
## Local checks
|
||||
|
||||
```bash
|
||||
dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
|
||||
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore
|
||||
```
|
||||
|
||||
For `NetworkCameraScanner` TCP probes, bound connects with a linked cancellation token and await the connect task on both success and timeout. Do not race a live `TcpClient.ConnectAsync` against `Task.Delay` and return while the connect task is still running: closing the client can surface a later socket cancellation as an unobserved task exception. Keep a focused test proving the timeout cancels and observes the pending connect, and that caller cancellation still propagates.
|
||||
|
||||
For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon.
|
||||
|
||||
This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`.
|
||||
|
||||
For camera enable/disable timing, distinguish Central's requested state, the exact configuration digest acknowledged by the Agent, and actual FFmpeg process release. A status transition alone is not proof that capture stopped. Poll `/proc/<pid>/comm` (or an equivalent exact process identity that cannot match the harness command); measure stop convergence separately from config ACK convergence. The synthetic-camera acceptance must cover initial OFF, ON, OFF, ON, restart while ON, then OFF and restart while OFF with the persisted Agent identity, asserting the newest digest after each update. Record the observed OFF latency and keep the item open if it exceeds the product's 2-second expectation. Every attempt uses a new project and exact source-built Central/Agent tags, records both before build, and removes/verifies them plus all project resources in its EXIT trap.
|
||||
|
||||
## Acceptance boundary
|
||||
|
||||
In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment.
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: heimdall-agent-update-acceptance
|
||||
description: Validate Heimdall native Agent install, signed update, startup health, and rollback behavior.
|
||||
---
|
||||
|
||||
# Native Agent update acceptance
|
||||
|
||||
Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`.
|
||||
|
||||
## Linux rollback simulation
|
||||
|
||||
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
|
||||
- The test creates two synthetic release directories and a `current` link to the candidate, writes a pending-update marker, and injects a fake `dotnet` executable that exits immediately with failure.
|
||||
- Verify the supervisor returns 75, atomically points `current` back at the prior release, removes `pending-update.json`, and reports that the previous release was restored. The fixture must live in `TemporaryDirectory` and leave no files behind.
|
||||
- This covers only the startup-failure rollback branch. It does not validate HTTP update discovery, signed archive verification, a 60-second healthy startup window, systemd, Windows service behavior, or a real Agent host.
|
||||
|
||||
## Local and host acceptance boundary
|
||||
|
||||
- Keep `HEIMDALL_SOURCE_BASE_URL` limited to Heimdall-owned installer assets; vendor runtimes and dependencies must use their official distribution channels.
|
||||
- For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval.
|
||||
- Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory.
|
||||
- Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration.
|
||||
- The Linux installer retries the release metadata request at most three times for transport failures, HTTP 408/425/429, and HTTP 5xx, with 2s then 4s waits. Other HTTP statuses fail immediately. Acceptance should verify transient-then-success, persistent-5xx bounded failure, permanent-4xx no-retry behavior, and that release signature and archive digest checks remain required.
|
||||
|
||||
## Central installer asset delivery
|
||||
|
||||
- `Heimdall.Web.csproj` publishes the Linux/Windows Agent installers and their supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files.
|
||||
- ASP.NET Core's default MIME table does not recognize `.py`. Add `.py` to a `FileExtensionContentTypeProvider` explicitly or `/install/agent-supervisor.py` returns 404 despite being present in `wwwroot`.
|
||||
- For changes to these assets or static-file configuration, build Central from the current source in a disposable Compose project and GET `/install/install-agent.sh` and `/install/agent-supervisor.py`. Require HTTP 200 and byte-for-byte equality with their source files. Also require `/healthz` healthy.
|
||||
- Follow `skills/compose-disposable-recipe/SKILL.md`: use generated credentials, isolated ports/project volumes/network, a unique Central image tag, and an EXIT trap installed before build. Verify all project containers, volumes, and networks are gone and remove/verify absence of the exact local image tag. Keep shared base images.
|
||||
- A successful local acceptance proves the source-built Central serves the files; it does not prove a deployed Central image has been rebuilt or restarted. Confirm deployed endpoints separately before calling an incident resolved.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: analysis-job-pipeline
|
||||
description: Implement and verify analysis job types across Heimdall Central scheduling and Agent inference.
|
||||
---
|
||||
|
||||
# Heimdall analysis job pipeline
|
||||
|
||||
Read `AGENTS.md`, the PIPE-01/02 Gitea issue, and `skills/heimdall-dotnet/SKILL.md`. For database behavior, also follow `skills/ef-core-persistence/SKILL.md`.
|
||||
|
||||
## Current supported job types
|
||||
|
||||
- `ObjectDetection`: return every detection produced by the configured YOLO COCO model.
|
||||
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`).
|
||||
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result.
|
||||
- `MotionDetection`: capture two frames from the already active RTSP stream 500 ms apart, downscale both to 32×18, and compare normalized luminance. A changed pixel must differ by at least 0.12; at least 2% changed pixels returns one `motion` detection with changed-region bounds and changed-pixel ratio as confidence. This CPU-only temporal detector does not require the YOLO model; lighting changes and camera shake may produce motion, so tune/measure it against representative cameras before relying on alerts.
|
||||
- The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result.
|
||||
- Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection.
|
||||
- Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types.
|
||||
- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies.
|
||||
|
||||
## Required validation
|
||||
|
||||
1. Unit-test Agent type parsing, motion comparison for identical/changed frames, and exact COCO class filtering for the object/person/vehicle types, including empty results and unsupported types.
|
||||
2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior.
|
||||
3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400.
|
||||
4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical.
|
||||
5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands.
|
||||
6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance.
|
||||
|
||||
For event-handler unit tests, initialize every queried set on the `IApplicationDbContext` substitute with `MockDbSetHelper`, including empty optional sets such as `Recordings`. An unconfigured NSubstitute `DbSet` throws from EF's `IQueryable.Provider` when the handler applies `AsNoTracking` or async LINQ. Use PostgreSQL integration tests for provider translation and persistence behavior; this unit fixture is only for handler branching and notification behavior.
|
||||
|
||||
The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-help banner after each navigation. Loopback is a secure browser context, so PWA UI appears in these tests and can intercept clicks on dialogs; browser E2E assertions should exercise the intended application controls after dismissing that unrelated notice.
|
||||
|
||||
## Current local acceptance evidence
|
||||
|
||||
Result delivery has a focused Agent test: `SendResultAsync_DoesNotRetryPermanentClientRejection` returns after one HTTP 400. The supported result JSON uses web defaults (`classIndex`, not `ClassIndex`). The disposable source Compose acceptance below validates the Central job API and persisted result contract; keep transport retry behavior covered by the Agent HTTP-handler test.
|
||||
|
||||
On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference.
|
||||
|
||||
Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: backup-restore
|
||||
description: Validate Heimdall PostgreSQL and protected-volume backups using isolated Compose projects and the production backup/restore scripts.
|
||||
---
|
||||
|
||||
# Heimdall backup and restore
|
||||
|
||||
Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/restore*.sh`, the backup Compose, or the disaster-recovery runbook.
|
||||
|
||||
## Project-specific behavior
|
||||
|
||||
- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes.
|
||||
- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files.
|
||||
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
|
||||
- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
|
||||
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
|
||||
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
|
||||
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO.
|
||||
5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p <name> down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files even on a failed assertion. These fixtures use upstream PostgreSQL/RustFS images and build no local image unless a recipe change explicitly adds one; retain those upstream images. If adding a local build, record its unique tag and remove/verify that exact tag in the same trap after teardown. Never use `--rmi all` or broad prune commands.
|
||||
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation.
|
||||
7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed.
|
||||
8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data.
|
||||
|
||||
These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. Record `local image tags: none` for such a run. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown in the same EXIT trap, even on failure. Do not use image-prune commands.
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: camera-access-groups
|
||||
description: Implement and validate Heimdall user-to-camera grants and group camera access through the administration UI and API.
|
||||
---
|
||||
|
||||
# Camera access and groups
|
||||
|
||||
Camera visibility is the union of direct camera grants, site-wide grants, legacy user site assignments, and cameras granted to groups the user belongs to. Keep that union in `CameraAccessService` and `ResourceAccess`; do not reimplement partial scope rules in controllers or UI queries. Site and camera resource checks must continue to run at API/application boundaries, including snapshots, events, hubs, and agent assignment.
|
||||
|
||||
Manage group-camera membership through the authenticated `api/groups/{groupId}/cameras` endpoints. The administration page loads all sites and their cameras with bounded paging, displays site names beside cameras, and adds/removes grants through the API. Treat failed loads and mutations as errors; do not optimistically report success.
|
||||
|
||||
When changing this area, verify:
|
||||
|
||||
- `ResourceAccessTests` for the role/grant matrix, live group membership revocation, and union of direct plus group grants.
|
||||
- `HttpIsolationTests` and the affected API integration tests for real HTTP authorization outcomes.
|
||||
- `GroupsPageTests` for site/camera labels and the UI add/remove request sequence.
|
||||
- PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof.
|
||||
- The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes.
|
||||
- If Compose builds Central from source, record a project-unique tag and install an EXIT cleanup trap before build/start. After teardown remove and verify absence of that exact tag even on failure; retain shared base images and report cleanup errors.
|
||||
|
||||
Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: camera-assignment
|
||||
description: Implement and verify assignment of Heimdall cameras to online Agents using persisted assignment history and actual Agent capabilities.
|
||||
---
|
||||
|
||||
# Heimdall camera assignment
|
||||
|
||||
Read `AGENTS.md`, the camera/Agent assignment Gitea issue, and `skills/heimdall-dotnet/SKILL.md`. For persistence changes, also follow `skills/ef-core-persistence/SKILL.md`.
|
||||
|
||||
- Keep assignment scoped to the camera's site and online Agents. Persist assignment/release history and update `Camera.AgentId` in the same EF Core unit of work.
|
||||
- Assignment strategy must use evidence actually supplied by the relevant entity. Do not infer Agent inference hardware from camera-side protocol flags such as PTZ or camera-native motion detection.
|
||||
- `GpuPriority` prefers Agents reporting `HasGpu`; if none are GPU-capable, it falls back to all online Agents. Workload balancing remains deterministic within the eligible candidates.
|
||||
- Camera discovery currently does not populate `Camera.HasMotionDetection`; treat that legacy field as unknown/false and do not use it for Agent placement until a camera capability probe supplies verified data.
|
||||
- Add PostgreSQL relational tests for strategy selection, failover, and assignment history. Do not use EF InMemory to verify concurrency or transaction semantics.
|
||||
- For every behavior change, build a uniquely tagged disposable Docker Compose acceptance stack from the changed source, exercise the changed assignment through the API or service boundary against PostgreSQL, and use generated credentials, ports, volumes, and project name. Install an EXIT trap before build/start; tear down only that project, verify zero project containers/volumes/networks, remove each locally built image tag and verify it absent. Preserve shared base images and test exit status. Follow `skills/compose-disposable-recipe/SKILL.md`.
|
||||
|
||||
Current validated behavior: `GpuPriority` selects a GPU Agent for a camera even when camera motion capability is false; PostgreSQL test evidence is recorded in the linked Gitea issue.
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: camera-toggle-acceptance
|
||||
description: Validate that Central camera enable/disable changes stop and resume the real Agent FFmpeg capture process and persist across Agent restarts.
|
||||
---
|
||||
|
||||
# Camera enable/disable lifecycle
|
||||
|
||||
Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this flow.
|
||||
|
||||
## Implementation path
|
||||
|
||||
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central.
|
||||
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
|
||||
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
|
||||
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
|
||||
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
|
||||
|
||||
## Local verification
|
||||
|
||||
Run the focused Agent lifecycle suites:
|
||||
|
||||
```bash
|
||||
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter 'FullyQualifiedName~CameraStreamServiceTests|FullyQualifiedName~SnapshotPipelineServiceTests' --no-restore
|
||||
```
|
||||
|
||||
These tests cover session idempotence, process termination, and synchronization without claiming a full Central/Agent workflow.
|
||||
|
||||
## Central + Agent disposable acceptance
|
||||
|
||||
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
|
||||
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
|
||||
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
|
||||
- Toggle ON and confirm an Agent `ffmpeg` pull process exists against the synthetic path. Toggle OFF and verify the API says Disabled, Agent reports no assigned stream via its active process count and the FFmpeg process disappears in under 2 seconds. Toggle ON and verify the process returns within 10 seconds.
|
||||
- Restart the Agent while ON; verify it reuses its single existing identity and restarts capture within 10 seconds. Then toggle OFF, restart again, and verify the camera remains Disabled and no capture process returns.
|
||||
- Use `docker top` only to count FFmpeg processes; never print its command lines because they contain the RTSP URL. Record elapsed durations and sanitized HTTP statuses only.
|
||||
- Install an EXIT cleanup trap before the first build/start. Teardown only the named Compose project, verify zero containers/volumes/networks, remove each exact project-unique Central/Agent image tag and verify absent, then delete the temporary environment and scripts. Keep the original test status and fail if cleanup verification fails.
|
||||
|
||||
This acceptance proves the source-built Central/Agent software lifecycle with a synthetic RTSP stream. It does not validate hardware codecs, physical cameras, LAN multicast, or deployed-host timing.
|
||||
|
||||
## Observed simulator pitfalls
|
||||
|
||||
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
|
||||
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
|
||||
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
|
||||
- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle.
|
||||
|
||||
## Latest source-built run
|
||||
|
||||
The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding self-counting by the measurement shell. It confirmed the Disabled baseline at zero processes and progressed through ON, OFF, ON, then Agent restart while ON with capture restored. The next OFF returned Central state Disabled and effective Agent config `enabled=false`, with zero FFmpeg processes, but the latest config digest was not acknowledged inside the two-second OFF bound. Therefore the full OFF/ON/restart acceptance is still incomplete; do not mark #59/#199 complete. Investigate whether Agent ACK version is stale or the API config digest changes after toggle, while keeping the OFF process release measurement distinct from ACK convergence.
|
||||
|
||||
## Sixth source-built run
|
||||
|
||||
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: central-auto-updates
|
||||
description: Maintain Central server installation, Compose refresh, and Docker image auto-updates for Heimdall deployments.
|
||||
---
|
||||
|
||||
# Central installation and image updates
|
||||
|
||||
Use this skill when changing the Linux or Windows Central installer, its generated Compose, or Central container update behavior.
|
||||
|
||||
## Central and release endpoints
|
||||
|
||||
- The Central address embedded in generated Agent installation commands must come from the browser's exposed `NavigationManager.BaseUri`; do not store a deployment hostname in a Razor page or installer template. Preserve the path base and trim only its trailing slash.
|
||||
- The release API source is the global `updates.releaseapiurl` setting edited in Settings and read by `UpdatesController`; keep it empty until an operator configures an HTTPS API URL. Agent release checks must go through the authenticated Central `/api/updates/agent/latest` endpoint, which returns the configured manifest and asset URLs.
|
||||
- Native Agent installers require an explicit Central URL, and Docker Agent configuration must pass `Agent:CentralUrl` from the generated command or deployment environment. Localhost defaults are permitted only in explicitly local development Compose/configuration.
|
||||
- Optional Agent public-IP discovery has no built-in provider hostname; configure `Agent:PublicIpResolverUrl` with an HTTPS endpoint or leave it empty to report no public IP. Validate the URL before creating the HTTP client.
|
||||
- Server-side API calls from Blazor circuits must prefer the process's Kestrel loopback binding over a retained browser `Host`; a public reverse-proxy host may not be reachable from inside the Central container. Normalize wildcard Kestrel binds (`0.0.0.0`, `[::]`, and `+`) to loopback while preserving the bound port.
|
||||
- Installer scripts should embed the official Heimdall source base as their standalone default and allow `HEIMDALL_SOURCE_BASE_URL` to override it for reviewed revisions or mirrors. Use it only for Heimdall-owned source assets; keep vendor dependencies on their official distribution sources.
|
||||
- Configure the Gitea API endpoint used by Renovate through the Actions variable `GITEA_API_ENDPOINT`; do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
|
||||
- Keep Compose network names project-scoped by omitting a fixed `networks.*.name`, especially for disposable validation projects.
|
||||
|
||||
## Deployment behavior
|
||||
|
||||
- Keep the installer-generated core stack limited to PostgreSQL, Central, and the updater. Only Central receives the Watchtower enable label; do not update PostgreSQL automatically.
|
||||
- Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files.
|
||||
- Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned.
|
||||
- The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system.
|
||||
- For each published Ubuntu-based Central, CPU Agent, or CUDA Agent runtime image, update the package index, apply the package security updates required by current Trivy findings, install runtime packages, and clear apt lists in one layer. Keep a broader OS upgrade only where that image already establishes the policy (the CUDA image); verify every final image with the pinned Trivy scanner at HIGH/CRITICAL severity. A passing application build does not clear OS package advisories.
|
||||
|
||||
## Runtime image package security
|
||||
|
||||
- The server and CPU Agent runtime images inherit Ubuntu 24.04 from the pinned ASP.NET image. When Trivy identifies a fixed Ubuntu package in the shared base, remediate both Dockerfiles and enforce the minimum patched version at build time. For `CVE-2026-109518`, explicitly upgrade `apt` and `libapt-pkg6.0t64` to at least Ubuntu `2.8.4ubuntu0.1` before runtime packages. The NVIDIA Agent runtime keeps its existing full OS upgrade and asserts the patched APT version too.
|
||||
- Run Central + PostgreSQL from source in a disposable Compose project, verify health and native Agent asset URLs, then scan Central, CPU Agent, and any changed CUDA image with the same pinned Trivy scanner and HIGH/CRITICAL policy used by CI. Require no findings and perform exact-tag cleanup. See `skills/container-image-security/SKILL.md`.
|
||||
|
||||
## Re-running the installer
|
||||
|
||||
- A complete existing install can regenerate its Compose after validating the candidate. Keep a timestamped backup of the previous Compose before atomic replacement.
|
||||
- If the operator selects an existing optional service again, refresh its source assets through a temporary file and back up each replaced local asset.
|
||||
- Preserve `.env`, the PostgreSQL secret file, and Docker named volumes. Do not rotate existing credentials during an update.
|
||||
- When a newer Compose needs an absent env key, append a generated secret or documented default only if that key is missing. Never print secret values. Refuse to continue if the existing database URL or password file needed by PostgreSQL is missing.
|
||||
- If the user declines the Compose refresh, exit without changing the install. If only part of an install is present, stop and explain what is missing instead of creating a second set of credentials.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
|
||||
|
||||
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
|
||||
|
||||
If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup.
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
name: compose-disposable-recipe
|
||||
description: Build and acceptance-test Heimdall changes in a disposable Docker Compose stack, isolated from deployed data and configuration.
|
||||
---
|
||||
|
||||
# Disposable Compose acceptance
|
||||
|
||||
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
|
||||
|
||||
Track the change and its acceptance evidence in a Gitea issue; follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md). Put the project name, exact local image tags and cleanup verification in the issue or linked PR, and close the ticket only after the recipe and other required gates pass.
|
||||
|
||||
## Safety and isolation
|
||||
|
||||
- Build from the current source with a unique Compose project name. Do not test against the production hostname, database, image volumes, secrets, or credentials.
|
||||
- Put generated `.env` and secret files under a temporary directory outside the repository. Use synthetic test identities and cryptographically random local passwords.
|
||||
- Use an unused loopback host port and Compose-managed volumes whose names include the unique project name. Do not join production or shared networks.
|
||||
- Give each locally built acceptance image a project-unique tag, for example `heimdall:<project>-acceptance`; do not build under `latest`, `local`, or a tag that existed before the recipe. Use a temporary Compose override to set the unique image tag while preserving the source build context. Record all generated tags before starting.
|
||||
- Never use broad Docker cleanup such as `docker system prune`, `docker image prune`, or `docker rmi $(docker images -q)`. Remove only the test project with `docker compose -p <unique-name> down --volumes --remove-orphans`.
|
||||
- After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm <exact-recipe-tag>` if it exists, then verify `docker image inspect <exact-recipe-tag>` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project.
|
||||
- Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path.
|
||||
- A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched.
|
||||
- These requirements apply to every Docker-based acceptance recipe, including SDK-only test containers, third-party mocks, one-shot helpers, and failure/partial-build paths. Such recipes must explicitly state whether they build any local images. If they build none, leave upstream images intact and still verify cleanup of project containers, volumes, and networks. If they build any local image (Heimdall or helper), record its unique tag before build and remove/verify it absent in the same `EXIT` cleanup trap, even if Compose startup or the build fails.
|
||||
- Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images.
|
||||
- **Mandatory local image cleanup:** before the first build, enumerate and record every recipe-owned image tag that may be created (application, SDK/test harness, mock, one-shot helper). Use a unique tag for each locally built image. The EXIT trap must remove each exact recorded tag after project teardown and verify it is absent, regardless of whether build, startup, assertions, or teardown failed. Do not count an image as shared merely because its Dockerfile uses a shared base; only remove recipe-built tags, and retain upstream images. If no image is built locally, explicitly say so and verify the project resources are gone. Never leave recipe-created local images behind.
|
||||
|
||||
### Required cleanup trap pattern
|
||||
|
||||
Use one `EXIT` trap installed before the first build or Compose start. Record
|
||||
exact local tags in an array before building; leave the array empty when the
|
||||
recipe builds no images. Cleanup actions must be independent so a failed
|
||||
Compose teardown cannot skip image and temporary-file cleanup. Preserve the
|
||||
original status and return a failure if any cleanup verification fails:
|
||||
|
||||
```bash
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
down --volumes --remove-orphans || cleanup_failed=1
|
||||
# Query all three resource kinds by Compose project label; do not infer
|
||||
# absence from `compose down`'s exit code alone.
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
rm -rf -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
```
|
||||
|
||||
The label queries must succeed and return empty results for containers,
|
||||
volumes, and networks. Do not include upstream images in `local_image_tags`. Recipe records must state
|
||||
the project name, whether local images were built, exact tags and absence
|
||||
checks (or explicitly “none”), plus project-resource cleanup results. A Docker
|
||||
recipe that reports teardown without the image-tag check is incomplete.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port.
|
||||
2. Generate a temporary Compose image override. For example:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
heimdall:
|
||||
image: heimdall:${ACCEPTANCE_PROJECT}-central
|
||||
```
|
||||
|
||||
Put `ACCEPTANCE_PROJECT=<unique-name>` in the temporary env file and include both Compose files in every command. This overrides only the image tag; the checked-in source build context is retained. Use similarly unique tags for any Agent or helper image built from this checkout.
|
||||
3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml -f <temp-image-override> up -d --build`.
|
||||
4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
|
||||
5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
|
||||
6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete temporary environment, secrets, override, and copied-source files. Attempt each cleanup action even if an earlier cleanup action fails; surface any cleanup failure. Retain shared upstream/base images. Do not use Compose `--rmi all` or broad prune commands.
|
||||
|
||||
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: heimdall-container-image-security
|
||||
description: Diagnose and repair vulnerabilities in Heimdall Central and Agent container images.
|
||||
---
|
||||
|
||||
# Container image security updates
|
||||
|
||||
Read `AGENTS.md`, the image-scan/acceptance Gitea issue, `skills/compose-disposable-recipe/SKILL.md`, and `skills/central-auto-updates/SKILL.md` before changing runtime images or their publication path.
|
||||
|
||||
Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime layers. When Trivy reports a fixed Ubuntu package, update the affected packages unless the image already establishes a broader OS-upgrade policy. For `CVE-2026-109518`, all three runtime Dockerfiles explicitly upgrade `apt` and `libapt-pkg6.0t64` after `apt-get update` and assert that `apt` is at least `2.8.4ubuntu0.1` before installing runtime tools. The NVIDIA image retains its existing full OS upgrade as well. Keep Trivy severity and exit thresholds unchanged.
|
||||
|
||||
For acceptance, build Central, CPU Agent, and NVIDIA Agent from the changed checkout under unique Compose image tags with synthetic credentials, loopback ports, project-scoped volumes/network, and an EXIT cleanup trap. Verify Central health and the native Agent installer and supervisor URLs; build the NVIDIA image without claiming GPU runtime validation. Scan all three built images with the same pinned Trivy version, vulnerability DB repositories, and HIGH/CRITICAL exit policy used by `scripts/ci/security.sh`. A passing acceptance requires zero HIGH/CRITICAL findings, successful teardown, no project containers/volumes/networks, and removal plus absence checks for every exact local tag. Retain upstream base and scanner images.
|
||||
|
||||
The CI image scan is a merge gate. Do not publish or merge around a failed scan; inspect the report and correct the affected package, then rerun the complete workflow. Keep Gitea issue evidence split between disposable local acceptance and the actual CI publication run.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: deployment-guide-acceptance
|
||||
description: Keep Heimdall's Docker installation and backup guides aligned with the actual Compose assets and validate source-built installation flows in a disposable project.
|
||||
---
|
||||
|
||||
# Heimdall deployment guide acceptance
|
||||
|
||||
Read `AGENTS.md`, the linked Gitea issue, `docs/docker-compose.md`, and the relevant Compose and focused skills before changing deployment instructions. Follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) for status and acceptance evidence.
|
||||
|
||||
## Project-specific documentation checks
|
||||
|
||||
- Central production is PostgreSQL plus Heimdall Web. The development Compose builds Central from source; the interactive Linux/Windows installers create deployment files without cloning the repository.
|
||||
- Production Agent Compose is generated in Central for the selected site and pins the image digest. The repository's Agent Compose files are development or optional hardware overlays only.
|
||||
- Recording quota is configured through `RECORDING_STORAGE_QUOTA_MAX_BYTES`; absent an override, Central uses 1 TiB.
|
||||
- The Central image installs Tesseract plus English language data. `PLATE_OCR_ENABLED` is mapped to `PlateOcr__Enabled` by the development and production Compose files and both Linux/Windows installer templates. New installs default it to false; upgrades preserve an existing value and add false if absent. If documented, explain that OCR is an operator-uploaded crop processed locally, not automatic video detection or face recognition; mention temporary crop deletion and that OCR candidates do not establish identity.
|
||||
- The scheduled backup service installs AWS CLI, Bash, and GNU coreutils. The backup scripts select AWS CLI in this image and use S3-compatible configuration; do not instruct operators to download the retired MinIO `mc` URL.
|
||||
- Optional Compose projects depend on the documented external core network and, where stated, the Central data volume. Do not describe an optional service as part of required startup.
|
||||
|
||||
## Disposable installation acceptance
|
||||
|
||||
1. Follow the local development installation commands in `docs/docker-compose.md` from the changed checkout. Create a unique project, isolated bridge, generated database/JWT credentials and unused loopback ports under a temporary directory. Do not copy production `.env`, use the default credentials unchanged, or use deployed volumes/networks.
|
||||
2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR.
|
||||
3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy.
|
||||
4. Install an EXIT cleanup trap before build/start. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files even if build or assertions fail.
|
||||
5. Record a unique tag for each locally built Central/helper image before build. After teardown, remove and verify absence of each exact tag. Keep shared upstream runtime/database images, preserve test exit status, report cleanup errors, and never use `--rmi all` or prune images broadly.
|
||||
6. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets.
|
||||
|
||||
When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe.
|
||||
|
||||
## Latest local attempt
|
||||
|
||||
On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. These are partial recipe results: the reused application image was not a uniquely built image for this recipe, and no exact-tag removal/absence check is recorded. Repeat the source build and probe with a fresh project tag before treating deployment-guide Compose acceptance as complete. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: ef-core-persistence
|
||||
description: Implement or review database persistence in Heimdall with Entity Framework Core, including SQLite Agent stores and PostgreSQL behavior.
|
||||
---
|
||||
|
||||
# Heimdall EF Core persistence
|
||||
|
||||
Use this skill whenever changing how application or Agent data is read or written.
|
||||
|
||||
- Use EF Core LINQ and entity configurations for CRUD. Prefer projections, bounded result sets, asynchronous APIs, and `CancellationToken`; use `AsNoTracking` for read-only entity queries.
|
||||
- Create a short-lived `DbContext` per operation. Hosted services and concurrent workers should use `IDbContextFactory<TContext>` and dispose each context; never share a context across parallel work.
|
||||
- Evolve schemas through reviewed EF Core migrations. Preserve deployed data and test upgrades from every supported on-disk schema, including Agent-local SQLite outboxes.
|
||||
- Verify PostgreSQL translation, transaction boundaries, concurrency and deletion semantics against PostgreSQL integration tests when those behaviors matter. Do not use EF InMemory as proof of relational behavior.
|
||||
- Do not issue CRUD through ADO.NET or hand-written SQL. Raw SQL through EF is an exception for database-specific capabilities that LINQ cannot express or for measured performance needs. Keep it parameterized, add an adjacent `EF Core exception:` comment with the reason, and add a test for its behavior.
|
||||
- Migrations, test database setup, PostgreSQL maintenance/partition DDL, and locks with no portable EF equivalent are valid exceptions. Keep provider-specific code in Infrastructure or a dedicated adapter; do not spread it into use cases.
|
||||
- When adding an approved raw EF operation, add its exact source path and a short capability rationale to `scripts/ci/check-efcore-usage.py`'s `EF_CORE_EXCEPTIONS` allowlist, keep an adjacent `EF Core exception:` comment, and cover the behavior with a relational test. The scanner intentionally ignores comments when locating a call; a comment alone does not allowlist a new production source.
|
||||
- Never enable sensitive-data logging in production. Do not log connection strings or persisted secret values.
|
||||
|
||||
Before editing, inspect this repository's `AGENTS.md`, the linked Gitea issue, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the issue with evidence and remaining deployment checks.
|
||||
|
||||
## Microsoft references
|
||||
|
||||
- [EF Core efficient querying](https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying)
|
||||
- [EF Core tracking and no-tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking)
|
||||
- [EF Core raw SQL queries](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)
|
||||
- [EF Core migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/)
|
||||
- [SQLite provider for EF Core](https://learn.microsoft.com/en-us/ef/core/providers/sqlite/)
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: first-admin-bootstrap
|
||||
description: Implement or diagnose Heimdall's mandatory first administrator setup and restrict later account creation to admins.
|
||||
---
|
||||
|
||||
# First administrator setup
|
||||
|
||||
Use this skill when changing account bootstrap, signup, login routing, user creation, or initial deployment guidance.
|
||||
|
||||
- The first account is created through a dedicated setup assistant that is reachable only while the database has no users. Do not seed a production password or print credentials to logs.
|
||||
- Make first-admin creation one-time and race-safe at the server/API boundary. The UI hiding a link is not an authorization control.
|
||||
- After bootstrap, disable anonymous registration regardless of old public-registration settings. Further accounts are created through authenticated, admin-authorized user-management endpoints only.
|
||||
- Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users.
|
||||
- Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup.
|
||||
- For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available).
|
||||
- Record a unique tag for every source-built Central image and install an EXIT cleanup trap before build/start. Remove the project and verify zero containers/volumes/networks, then remove and verify absence of each exact local tag even after failure; retain shared PostgreSQL/.NET base images and report cleanup errors.
|
||||
|
||||
Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs.
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
name: gitea-ticket-workflow
|
||||
description: Create, maintain, link, and close Heimdall project tickets in Gitea as the sole work tracking system.
|
||||
---
|
||||
|
||||
# Gitea ticket workflow
|
||||
|
||||
Gitea issues are the source of truth for planned work, acceptance evidence, operational follow-up, and completion. Do not use a repository markdown checklist as a parallel backlog.
|
||||
|
||||
## Before implementation
|
||||
|
||||
1. Read `AGENTS.md` and the focused skill(s) for the affected area.
|
||||
2. Identify the repository from `git remote get-url origin`; use the configured Gitea API/CLI credentials without printing them. Never put tokens in URLs, command output, issue text, or PR descriptions.
|
||||
3. Search open and closed issues for the topic, identifiers, PRs, and acceptance gaps. Reuse the matching issue: reopen it when required work remains, or add a clearly scoped follow-up issue when the old issue is closed and represents a completed unit.
|
||||
4. Create one issue per independently deliverable behavior or operational validation. An issue must include:
|
||||
- a concise, outcome-oriented title and relevant component/priority labels;
|
||||
- a plain-language summary explaining the user/operator impact and why the work matters;
|
||||
- a short current-state section separating implemented behavior, local evidence, CI evidence, and real deployment/hardware evidence;
|
||||
- an analysis of the actual gap: what fails or is missing, what evidence proves it, likely causes where known, and what remains uncertain;
|
||||
- scope and explicit out-of-scope items, dependencies, risks, assumptions, and the expected owner/environment for external checks;
|
||||
- numbered implementation/validation steps in dependency order, including safe test data, observable outcomes, and cleanup;
|
||||
- independently checkable acceptance criteria, with no generic placeholder criteria;
|
||||
- relevant files, prior issue/PR/run links, and the focused skill.
|
||||
5. Apply the ticket labels described in **Ticket labels** below before handing the issue to implementation. Labels are metadata for filtering and triage; they do not replace the title, scope, or acceptance criteria.
|
||||
6. For UI/product work, decide whether a mockup materially clarifies the acceptance criteria. If needed, attach a mockup or link to a Penpot/Figma artifact; state the viewport, states, responsive breakpoints, and interactions it must cover. Do not block infrastructure work on an unnecessary mockup.
|
||||
7. Confirm the created/updated issue through the API and record its canonical URL/number in the branch/PR context.
|
||||
|
||||
## Ticket labels
|
||||
|
||||
Every issue should have, at minimum, one **type** label, one **priority** label, and one **domain** label. Add a **validation** label when the ticket is mainly about an acceptance/deployment check. Apply existing repository labels through the Gitea issue API or UI; if a required label is missing, create it once with a clear description and reuse it rather than inventing synonyms.
|
||||
|
||||
Use this vocabulary consistently:
|
||||
|
||||
| Group | Labels | Use |
|
||||
|---|---|---|
|
||||
| Type | `type:feature`, `type:bug`, `type:maintenance`, `type:docs`, `type:security` | Main nature of the work; select one. |
|
||||
| Priority | `priority:P0`, `priority:P1`, `priority:P2`, `priority:P3` | `P0` blocks release/security or causes an active outage; `P1` is important for the current release or core journey; `P2` is normal planned work; `P3` is low urgency. Select one and state why in the issue if not obvious. |
|
||||
| Domain | `area:ci`, `area:release`, `area:install`, `area:agent`, `area:camera`, `area:analysis`, `area:storage`, `area:notifications`, `area:auth`, `area:ui`, `area:monitoring`, `area:docs` | Main owning subsystem; use multiple only when work genuinely crosses boundaries. |
|
||||
| Validation | `validation:field`, `validation:deployment`, `validation:hardware`, `validation:backup-restore` | Add when closure depends on the corresponding real environment or external evidence. Do not apply to ordinary code-only acceptance. |
|
||||
| State marker | `blocked`, `needs-design`, `needs-decision` | Add only while the named condition is true; remove it when resolved. Explain the blocker/decision in the issue body. |
|
||||
|
||||
Before creating a label, search all repository labels and use an existing equivalent. Keep labels lowercase except the conventional priority spelling above. Do not create status labels such as `open`, `closed`, `in progress`, or `done`; Gitea issue state and assignee/project workflow own those concepts. Do not use labels to encode dynamic details such as a PR number, release version, user, camera, or site.
|
||||
|
||||
On backlog review, correct missing or stale labels when the scope changes. When splitting an issue, label each child for its own type, priority, domain, and validation requirement; do not blindly copy every parent label. A label change alone does not satisfy acceptance criteria or close the ticket.
|
||||
|
||||
## During implementation
|
||||
|
||||
- Keep the issue current with material discoveries, decisions, blockers, and validation evidence. Do not duplicate long-lived status in a local markdown backlog.
|
||||
- Reference the issue in branch and commit context where useful. Every PR body must link the issue with `Closes #N` when merge should close it, or `Refs #N` when the issue tracks work that remains after this PR.
|
||||
- A PR touching a subset of a larger ticket must say exactly which acceptance criteria it satisfies and which remain open. Split follow-up tickets when the remaining work is independently actionable.
|
||||
- Keep project-specific implementation and acceptance procedures in `skills/`; link the relevant skill from the issue and PR.
|
||||
- For external validation, create/update a focused ticket with owner, prerequisites, safe test data, procedure, expected evidence, and cleanup. Never mark an external integration validated based on mocks or configuration presence.
|
||||
|
||||
## Mockups and attachments
|
||||
|
||||
- Attach a mockup when layout, hierarchy, responsive behavior, or interaction flow is a substantial part of acceptance. Prefer an existing project design artifact; otherwise create a focused Penpot/Figma frame and attach/link it from the issue.
|
||||
- The issue describes what the mockup demonstrates and its status (proposed/approved/superseded). Keep source design links and exported images free of secrets or real customer data.
|
||||
- API, persistence, CI, and maintenance tickets generally need no mockup; state that only when ambiguity might otherwise cause delay.
|
||||
|
||||
## Human-readable issue layout
|
||||
|
||||
Use this order and keep each section focused:
|
||||
|
||||
1. **Résumé** — one or two sentences describing the intended result.
|
||||
2. **Pourquoi** — user/operator impact and the reason for prioritizing the work.
|
||||
3. **État actuel et preuves** — what is already implemented and exactly what tests/runs prove; distinguish synthetic/local/CI/production evidence.
|
||||
4. **Écart à résoudre** — the remaining failure or uncertainty in concrete terms; avoid starting with a fragment copied from a longer checklist sentence.
|
||||
5. **Analyse** — known cause, constraints, failure modes, security/data impact, assumptions, and unanswered decisions.
|
||||
6. **Plan de travail** — ordered steps with dependencies and observable outputs. Split independent work into linked child issues instead of making one ticket cover unrelated deliverables.
|
||||
7. **Critères d’acceptation** — concise checkboxes with measurable outcomes and evidence required.
|
||||
8. **Hors périmètre / dépendances** — identify related capabilities that must not be mistaken as delivered, required owners/access/hardware, and blockers.
|
||||
9. **Maquette** — attach/link only where UI design materially affects acceptance; otherwise say `Aucune maquette requise : ...` with a short reason.
|
||||
10. **Liens** — PRs, runs, skills, related issues and design artifacts.
|
||||
|
||||
Render long historical logs as a clearly separated `<details><summary>Historique détaillé</summary>` appendix. Lead with the latest state and the exact open work; do not make readers infer the task from a 1,000-word pasted paragraph. Use short paragraphs, bullets, and headings; expand acronyms on first use when the audience may not know them.
|
||||
|
||||
## Pull requests and closure
|
||||
|
||||
- Before opening/updating a PR, verify the issue number, link, acceptance criteria, focused skill, and test/acceptance evidence are present.
|
||||
- Use `Closes #N` only when the PR completes every criterion owned by that issue. For partial work use `Refs #N` and leave the issue open with unchecked criteria and evidence updated.
|
||||
- Gitea closes a `Closes #N` issue when the PR merges. After merge, verify the issue state changed; if not, close it manually only after checking all criteria and posting the merge/CI/acceptance evidence.
|
||||
- Do not close tickets merely because code was merged when required acceptance (including the disposable Compose recipe, CI gate, external deployment, camera, storage, or release run) remains outstanding. Create a separate validation issue if code delivery and external validation have different owners or timelines.
|
||||
- On completion, leave a concise final issue comment linking merged PR/commit, successful checks and acceptance record, plus explicit limits. Keep the ticket searchable; don't erase the completion trace.
|
||||
|
||||
## Backlog maintenance
|
||||
|
||||
- Review open issues before planning work; deduplicate, label, prioritize, split oversized work, and refresh stale acceptance criteria.
|
||||
- For discovered follow-up work during a PR, create/link a ticket before treating it as deferred. Avoid checklist fragments in commits, skills, or docs that become a second backlog.
|
||||
- Repository skills contain durable workflows, not per-task status. Update the relevant skill in the same PR when implementation or acceptance procedure changes.
|
||||
- When migrating a legacy backlog, carry each actionable incomplete item to an open issue; carry completed entries to closed issue history or a closed migration/traceability issue with original PR/run references. Verify issue counts, titles, states, and links before deleting the file.
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: heimdall-gpu-inference
|
||||
description: Build and verify Agent ONNX Runtime provider selection, CPU fallback, and GPU package variants in Heimdall.
|
||||
---
|
||||
|
||||
# Heimdall Agent ONNX inference
|
||||
|
||||
Use this skill when changing ONNX Runtime packages, execution provider configuration, Agent inference startup, or GPU deployment support.
|
||||
|
||||
## Project-specific workflow
|
||||
|
||||
- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. CUDA support is opt-in through `docker/Dockerfile.agent.gpu`, `docker/docker-compose.agent.dev.gpu-nvidia.yml`, and a separately signed release image manifest.
|
||||
- Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access.
|
||||
- Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies:
|
||||
|
||||
```sh
|
||||
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
|
||||
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode
|
||||
```
|
||||
|
||||
- The Agent checks for detected NVIDIA hardware before enumerating ONNX providers or creating a session; some ONNX Runtime GPU builds can fault during native provider discovery when no driver device is attached, before managed fallback handling is possible. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware.
|
||||
- Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference.
|
||||
- Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output.
|
||||
- Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution.
|
||||
- Record unique tags for the locally built CUDA Agent and any Central/helper fixture image before building. Install an EXIT trap before the build/start; after stopping the project, remove each exact local tag independently and verify it is absent, including after failed builds/assertions. Preserve the test exit status and report cleanup errors. Retain shared CUDA/runtime base layers; never use `--rmi all` or `docker image prune`.
|
||||
|
||||
- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest.
|
||||
|
||||
## Current limitation
|
||||
|
||||
The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from this source with locked GPU restore. Rendered Compose confirmed CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A local disposable runtime check launched the GPU image without NVIDIA devices on an isolated network and tmpfs state: logs confirmed no GPU detection, fallback to `CPUExecutionProvider`, and YOLO model initialization; a synthetic HTTP Central mock accepted registration and heartbeat (200/204), and `/healthz` returned 200. The repository `RealOnnx_CpuModel_ProcessesFullHdImage` test passed 1/1 with `HeimdallOnnxRuntime=GPU`. The mock did not implement configuration/jobs, so no camera frame traversed the Agent/Central loop; a synthetic frame and persisted inference observation remain open. The exact acceptance image tag and container were removed and verified absent; tmpfs, mock listener, and temporary state were gone. The earlier disposable Central/PostgreSQL bootstrap also passed. Physical CUDA execution still requires NVIDIA hardware.
|
||||
|
||||
Additional full-loop acceptance attempt, 5 November 2026: disposable Compose project `hmgpu-loop-929b670e` rendered with CUDA package selection, no NVIDIA reservation, and empty Sentry DSN. Central and the Agent GPU image were built from this checkout under `heimdall:hmgpu-loop-929b670e-central` and `heimdall-agent:hmgpu-loop-929b670e-gpu` (GPU image inspected at 3.56 GB). The Compose/Buildx client remained waiting after image export and before any service/container was created, so no Central bootstrap, Agent health, camera configuration, job, frame processing, or database observation was exercised. After stopping only that build handle, cleanup verified 0 containers/0 volumes/0 networks, both exact image tags absent, and the temporary directory absent. `docker buildx ls` and `docker ps` responded afterward; this does not establish successful runtime acceptance. Keep the frame-through-job-loop evidence open. An earlier duplicate-target attempt (`hmgpu-loop-e9377c0b`) was also cleaned with 0/0/0 and both exact image tags absent.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: group-access
|
||||
description: Implement and accept Heimdall group membership and camera grants through the Admin UI and protected API.
|
||||
---
|
||||
|
||||
# Group membership and camera access
|
||||
|
||||
The Admin group editor is `src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor`.
|
||||
Its API adapter is `HeimdallApiClient`; route templates must match
|
||||
`GroupsController`. Member listing is `GET /api/groups/{groupId}/users`, add is
|
||||
`POST /api/groups/{groupId}/users/{userId}`, and removal is
|
||||
`DELETE /api/groups/{groupId}/users/{userId}`. Camera grants use the sibling
|
||||
`/cameras` endpoints. Keep member selection name/email based in the UI; do not
|
||||
ask administrators to copy opaque user IDs.
|
||||
|
||||
Authorization is additive: effective camera access is the union of active
|
||||
site-wide, direct, legacy, and live group grants, subject to role permissions
|
||||
and deleted-resource checks. Removing one grant must preserve another valid
|
||||
grant. Soft-deleted groups must stop granting access immediately.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Run focused Web tests for `GroupsPageTests`, `HeimdallApiClientTests`, and
|
||||
`ResourceAccessTests`. Assert API HTTP method/path, UI member identity and
|
||||
camera/site labels, and add/remove behavior.
|
||||
2. Build the source in a uniquely named disposable Compose project with
|
||||
generated PostgreSQL/JWT credentials, loopback port, named volumes, and a
|
||||
project-specific network. Bootstrap the first Admin through the setup API;
|
||||
create a group, add a member using the production route, read the member
|
||||
list, remove the member, and verify the empty list. Use only synthetic data.
|
||||
3. Install an EXIT cleanup trap before build/start. Tear down that exact project
|
||||
with volumes and orphans, verify there are no project containers, volumes,
|
||||
or networks, remove exact local image tags and verify they are absent, and
|
||||
delete generated secret files even if an assertion fails.
|
||||
4. Record each project-unique local image tag before build. Retain shared
|
||||
upstream PostgreSQL/.NET runtime images; never use `--rmi all` or prune.
|
||||
5. Update the linked Gitea issue with the exact evidence and keep physical/deployment-only
|
||||
claims separate from local acceptance.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: heartbeat-failover
|
||||
description: Validate that stale Agents are marked offline and assigned cameras move safely to online peers.
|
||||
---
|
||||
|
||||
# Heimdall heartbeat and Agent failover
|
||||
|
||||
Read `AGENTS.md`, the Heartbeat/failover Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this path.
|
||||
|
||||
## Behavior contract
|
||||
|
||||
- Use the configured global heartbeat interval or per-Agent override, bounded to 5–300 seconds. A stale Agent is not eligible for new work.
|
||||
- The failover sweep owns the stale-to-Offline transition and camera reassignment. Do not add a competing heartbeat monitor that races this transition.
|
||||
- Preserve camera assignment history: close the old row and create a new active row for an online Agent in the same site. If there is no replacement, clear the active assignment and let periodic reconciliation retry when an Agent recovers.
|
||||
- Use short-lived EF Core contexts and test status, camera ownership, and assignment history against PostgreSQL.
|
||||
|
||||
## Required validation
|
||||
|
||||
1. Run the PostgreSQL tests in `HeartbeatMonitorJobTests`, `AgentFailoverJobTests`, and `CameraAssignmentServiceTests`.
|
||||
2. Run the integration scenario with two registered Agents: heartbeat both, assign a camera to the source, age only the source heartbeat past the maximum accepted timeout, execute the real `AgentFailoverJob` and `CameraAssignmentService`, then verify the source is Offline, the online peer owns the camera, and both assignment records retain the correct released/active state.
|
||||
3. Before any build/start, install an EXIT cleanup trap. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL.
|
||||
4. The trap tears down that project with volumes/orphans, verifies zero project containers, volumes and networks, then removes and verifies absence of the exact source-built Central image tag even on failure. Keep upstream Postgres/.NET base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad image pruning.
|
||||
5. Mark physical Agent loss, network partitions and multi-host timing as unverified unless exercised against deployed Agents.
|
||||
|
||||
## Current local evidence
|
||||
|
||||
5 November 2026: new relational integration scenario passed 1/1. Disposable source-built project `hmd-failover-1793882220-a9bc9c` registered two Agents, assigned the synthetic camera to the first, aged its heartbeat to 900 seconds, and observed the real Hangfire failover mark it Offline and move the camera to the still-online peer. PostgreSQL confirmed the previous assignment was released and the replacement assignment active. Teardown left zero containers/volumes/networks and removed/verified absence of the exact Central image tag. This proves the local scheduled path and relational state, not a real network partition or deployed multi-host timing.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: heimdall-dotnet
|
||||
description: Implement or review Heimdall .NET 10 application, EF Core persistence, and agent changes while preserving its clean architecture and audit backlog.
|
||||
---
|
||||
|
||||
# Heimdall .NET work
|
||||
|
||||
Read `AGENTS.md`, the relevant Gitea issue, and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) first. Trace a feature through `Domain` → `Application` → `Infrastructure` → `Web` or `Agent` before editing; update only the layers that own the behavior.
|
||||
|
||||
For persistence changes, inspect the entity configuration and latest migration, then verify PostgreSQL translation and transactions with focused integration tests. Keep migrations compatible with existing rows, record the data backfill or rollback requirement, and avoid client-side filtering on access-controlled queries.
|
||||
|
||||
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
|
||||
|
||||
For application commands, validate at the boundary, enforce site/camera scope in the use case, and make external side effects retry-safe. For agent work, account for disconnected operation, bounded queues, cancellation, and resource disposal.
|
||||
|
||||
After the change, run the smallest meaningful test suite plus the build when public contracts change. Update the issue with what passed and what still requires a deployed runner, camera, network, or object store. Link it from the PR and close it only when all acceptance criteria are verified.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: heimdall-identity
|
||||
description: Implement and review Heimdall account, password, session, email confirmation, lockout, and two-factor authentication flows built on ASP.NET Core Identity.
|
||||
---
|
||||
|
||||
# Heimdall Identity workflow
|
||||
|
||||
Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md), and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
|
||||
|
||||
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
|
||||
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
|
||||
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
|
||||
- Moving Identity model classes without changing tables should produce an explicit empty EF migration and a snapshot containing the Infrastructure entity types. Verify migration compatibility against PostgreSQL before release.
|
||||
- Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success.
|
||||
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
|
||||
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
|
||||
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
|
||||
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
|
||||
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
|
||||
- Keep the three supported role names seeded by Identity. Seed their default permission claims once using a durable role-claim marker; the Admin permission set stays immutable. Manage Supervisor/Viewer permission claims from `/admin/claims`, then include those persisted claims in login, refresh, cookie, and 2FA auth responses.
|
||||
- When role membership or role permissions change, rotate every affected user's security stamp and record the acting administrator in the audit log. Protect last-admin demotion, deletion, and lockout based on unlocked Admin accounts.
|
||||
- Apply `[Collection("E2E")]` on each concrete Playwright test class deriving from `E2ETestBase`; xUnit does not reliably inherit the PostgreSQL fixture attribute from its abstract base.
|
||||
- Configure Identity options explicitly and review changes to password, unique email, confirmed email, lockout, cookie, token-provider, and Data Protection behavior.
|
||||
- CI installs Chromium through the Playwright CLI already copied beside the Release E2E test assembly (`node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium`). This keeps browser tooling on the test project's locked Playwright dependency graph and avoids an independently restored C# script project.
|
||||
- Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility.
|
||||
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
|
||||
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
|
||||
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
|
||||
|
||||
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: mcp-global-configuration
|
||||
description: Keep Heimdall developer MCP integrations available across projects without storing machine credentials in the repository.
|
||||
---
|
||||
|
||||
# Heimdall developer MCP configuration
|
||||
|
||||
MCP integrations used while maintaining Heimdall belong in the developer's global Codex configuration, not in a repository `.mcp.json`. This keeps each project checkout free of personal service tokens and makes the integrations available in other projects.
|
||||
|
||||
## Configuration workflow
|
||||
|
||||
1. Before changing MCP setup, read this skill and the linked Gitea issue.
|
||||
2. Configure the intended servers in `~/.codex/config.toml`. Keep authentication values in user-level configuration or environment variables; never copy them into tracked files, examples, logs, or acceptance output.
|
||||
3. Remove any repository `.mcp.json` that duplicates global server configuration and contains credentials.
|
||||
4. Validate that the global TOML parses and run `codex mcp list`. Check that each expected server appears once and is enabled.
|
||||
5. For a server needed by the task, make a harmless read-only request (for example, list accessible GlitchTip organizations) to confirm authentication. Do not claim remote access from config presence alone.
|
||||
6. Update the corresponding Gitea issue with the local verification and any limits. Do not add an application Compose acceptance recipe for a developer-only MCP configuration change.
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: mdns-camera-discovery
|
||||
description: Implement and validate HomeKit camera discovery from DNS-SD mDNS announcements in Heimdall Agent.
|
||||
---
|
||||
|
||||
# Heimdall mDNS camera discovery
|
||||
|
||||
Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing discovery behavior.
|
||||
|
||||
## Ownership and data flow
|
||||
|
||||
- `Heimdall.Mdns/MdnsClient` owns UDP multicast and DNS-SD PTR/SRV/TXT/A parsing. Keep network operations cancellable and dispose sockets per operation.
|
||||
- `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records.
|
||||
- `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN.
|
||||
- Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback.
|
||||
- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (554 default for RTSP, 322 for RTSPS when omitted) or a probed RTSP port, HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it.
|
||||
|
||||
## Synthetic acceptance
|
||||
|
||||
- Build synthetic DNS response packets with PTR `_hap._tcp.local` → instance, SRV instance → hostname/port, TXT `ci`, `sf`, `id`, `md`, and A hostname → address. Include an unrelated A record to verify strict SRV association.
|
||||
- Verify camera and doorbell categories are kept, unrelated categories are filtered, `sf=0` maps to paired, and missing SRV-target A does not invent an address.
|
||||
- Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result.
|
||||
- Run the focused Agent tests and the full Agent test project after changes.
|
||||
- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists.
|
||||
- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping.
|
||||
|
||||
## Disposable Compose
|
||||
|
||||
Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
|
||||
|
||||
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: notification-delivery-acceptance
|
||||
description: Validate Heimdall's global SMTP and ntfy settings, test actions, and notification delivery without external providers.
|
||||
---
|
||||
|
||||
# Heimdall notification delivery acceptance
|
||||
|
||||
Read `AGENTS.md`, the PIPE-10/FEAT-05 Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing notification delivery.
|
||||
|
||||
## Configuration contract
|
||||
|
||||
- Settings created through the UI are stored with lowercase keys. `AppSettingReader` must normalize requested keys before its exact EF query; callers use mixed-case literals for legacy reasons.
|
||||
- SMTP reads `email.smtphost`, `email.smtpport`, `email.username`, `email.password`, `email.fromaddress`, `email.fromname`, and `email.usessl`.
|
||||
- ntfy reads `ntfy.baseurl` and `ntfy.token`; test messages use the same configured service and should fail visibly when it rejects or cannot be reached.
|
||||
- Keep SMTP/ntfy secrets out of responses and logs. Outbox delivery remains at-least-once; a provider acceptance followed by a lost DB acknowledgement can duplicate a notification.
|
||||
|
||||
## Required simulated validation
|
||||
|
||||
1. Run `AppSettingReaderTests`, notification service/outbox tests, and the PostgreSQL outbox integration tests.
|
||||
2. Use a disposable Compose project from the changed Central source with PostgreSQL, an isolated ntfy service and Mailpit. Generate database/JWT credentials, use an internal project-only network and no published ports, explicitly empty the Sentry DSN, and keep real SMTP/ntfy credentials out of the environment.
|
||||
3. Bootstrap a synthetic Admin and save SMTP/ntfy settings through `/api/settings`, matching UI key names. Call `/api/settings/ntfy/test` and `/api/settings/email/test`; verify ntfy returns success and Mailpit stores the synthetic recipient message.
|
||||
4. Install an EXIT cleanup trap before build/start. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, then remove/verify absence of the exact source-built Central image tag even on failure. Retain shared ntfy/Mailpit/PostgreSQL/Python base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad prune commands.
|
||||
5. Report local service acceptance separately from delivery to a real SMTP relay, hosted ntfy server, or user device.
|
||||
|
||||
## Current local evidence
|
||||
|
||||
On 5 November 2026, `AppSettingReaderTests` passed 9/9. The first disposable provider run showed ntfy success but SMTP failure: the UI stored lowercase keys while `EmailService` queried mixed-case values. `AppSettingReader.GetAsync` now lowercases trimmed keys; tests cover the SMTP and AI URL callers. The source-built isolated project `hmd-notify-mock-1793882996-2efa06` then passed both Admin settings/API test routes, ntfy HTTP 2xx, and SMTP test delivery captured in Mailpit. No ports were published and the bridge was internal. Cleanup verified zero containers/volumes/networks and removed/verified absence of the exact Central image tag. Real external delivery remains unvalidated.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
name: heimdall-pwa
|
||||
description: Implement and accept Heimdall's root-hosted, online-first Blazor PWA without persisting private application data.
|
||||
---
|
||||
|
||||
# Heimdall PWA
|
||||
|
||||
The supported PWA deployment is at the web origin root (`/`). The Blazor app uses Interactive Server, so camera, event, account and administration screens require a live server circuit. Offline mode is an informational page only; never add authenticated HTML, API results, media, credentials or SignalR traffic to CacheStorage or replay mutations offline.
|
||||
|
||||
## Implementation map
|
||||
|
||||
- `src/Heimdall.Web/Components/App.razor` links the web manifest and raster/Apple icons and loads `js/pwa-register.js`.
|
||||
- `wwwroot/manifest.webmanifest` defines stable root scope, standalone display and PNG/SVG icons.
|
||||
- `wwwroot/service-worker.js` caches only `/offline.html`, `/manifest.webmanifest` and `/pwa-icon.svg`. It falls back only for failed same-origin GET navigations and excludes API, auth, Blazor, hubs, health, metrics and operational/documentation paths.
|
||||
- The worker must remain waiting after an update. `pwa-register.js` shows a reload action for a waiting worker; only that action sends `ACTIVATE_UPDATE`, then reloads after `controllerchange`. Do not unconditionally call `skipWaiting()` or `clients.claim()` because this can replace resources during an active form or live session.
|
||||
- Installation UI is progressive: use `beforeinstallprompt` where the browser provides it; otherwise explain the platform's browser-menu installation steps. Browsers without PWA installation support must keep the site usable.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content.
|
||||
2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and install an EXIT cleanup trap before build/start. Remove the project, verify zero containers/volumes/networks, then remove and verify absence of each exact project-unique local image tag, even after failure; retain shared upstream images and report cleanup errors.
|
||||
Assign the locally built Central image a project-unique tag; remove and verify that exact tag after teardown, while retaining shared .NET/PostgreSQL bases.
|
||||
3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments.
|
||||
4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery.
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: release-automation
|
||||
description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests.
|
||||
---
|
||||
|
||||
# Heimdall tagged release workflow
|
||||
|
||||
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.
|
||||
|
||||
## Release invariants
|
||||
|
||||
- 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.
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: renovate-automation
|
||||
description: Diagnose and maintain Renovate dependency updates through Gitea Actions without exposing bot credentials.
|
||||
---
|
||||
|
||||
# Heimdall Renovate workflow
|
||||
|
||||
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
|
||||
|
||||
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `GITEA_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files.
|
||||
- The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
|
||||
- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR.
|
||||
- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials.
|
||||
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
|
||||
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
|
||||
- For operational changes, update the Renovate Gitea issue with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: server-healthchecks
|
||||
description: Keep Heimdall container health probes aligned with the HTTP methods accepted by its ASP.NET health endpoints.
|
||||
---
|
||||
|
||||
# Heimdall server health checks
|
||||
|
||||
Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing.
|
||||
|
||||
- Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy.
|
||||
- In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD.
|
||||
- Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required.
|
||||
- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Install an EXIT cleanup trap before build/start. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy. In cleanup remove only that project with `down --volumes --remove-orphans`, verify no labeled containers/volumes/networks remain, remove and inspect each exact local image tag even on failure, and retain shared base images. Preserve the test exit status and report cleanup failures.
|
||||
|
||||
## Metrics scrape acceptance
|
||||
|
||||
For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward.
|
||||
|
||||
On 5 November 2026, project hmd-metrics-scrape-1793874584 reused the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This is a partial Docker recipe result: it did not build a unique image for this scrape, so no exact-tag image removal was performed. Repeat the check with a fresh project-unique source-built tag before treating the Docker acceptance as complete. This local check does not validate a deployed Prometheus server or alert thresholds.
|
||||
|
||||
PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: signalr-client-lifecycle
|
||||
description: Avoid blocking SignalR client teardown in Heimdall Blazor components and services.
|
||||
---
|
||||
|
||||
# Heimdall SignalR client lifecycle
|
||||
|
||||
`NotificationsHubClient` is scoped to a Blazor circuit and owns a `HubConnection`. Components that use it should implement `IAsyncDisposable`, unsubscribe their event handlers, then await `Hub.DisposeAsync()`.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Do not call `.Wait()`, `.Result`, or `GetAwaiter().GetResult()` on SignalR stop/dispose operations. Network shutdown can block a renderer or request thread.
|
||||
- Centralize teardown in one asynchronous helper. Atomically detach the owned connection before awaiting shutdown so repeated disposal cannot dispose it twice.
|
||||
- `DisposeAsync()` awaits `StopAsync` and `DisposeAsync`, handling shutdown failures independently so failed stop still attempts resource disposal.
|
||||
- If compatibility requires synchronous `IDisposable`, it must return without blocking and start best-effort asynchronous cleanup. Keep `GC.SuppressFinalize(this)` on both dispose paths.
|
||||
- Log cleanup failures at debug level without access tokens, URLs containing credentials, or message payloads.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Build `src/Heimdall.Web/Heimdall.Web.csproj` with the SDK pinned by `global.json`; do not suppress analyzer warnings for blocking calls.
|
||||
2. Verify the component unsubscribes handlers and awaits async disposal.
|
||||
3. Run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique generated credentials, ports, project, and image tag; check `/healthz` and verify cleanup of project resources and that exact tag.
|
||||
4. Treat production GlitchTip recurrence as external evidence: local build and Compose do not prove the deployed client has stopped emitting events.
|
||||
|
||||
See Gitea issue [#233](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/233) for the current incident evidence.
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: site-ntfy-creation
|
||||
description: Maintain and accept the site-specific ntfy topic through Heimdall site creation.
|
||||
---
|
||||
|
||||
# Site ntfy creation
|
||||
|
||||
The site topic is an optional destination used by notification delivery. Creation crosses a JSON DTO, `SitesController`, `CreateSiteCommand`, `CreateSiteHandler`, and `Site`; every layer must carry `NtfyTopic`. Keep the optional DTO parameter last/defaulted to preserve existing clients. The Sites page already sends it in `CreateSiteAsync`.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Extend the PostgreSQL API integration test to POST a unique site name and `ntfyTopic`, then GET that site and assert `SiteResponse.NtfyTopic` equals the submitted topic. This catches JSON binding, controller mapping, and relational persistence together.
|
||||
2. Run the focused integration test against the repository PostgreSQL fixture.
|
||||
3. Follow `skills/compose-disposable-recipe/SKILL.md` to run a source-built disposable Compose stack. Bootstrap an isolated admin, create a site with a topic through `POST /api/sites`, read it back, and verify the topic. Remove the exact project and locally built tags and verify no project containers, volumes, or networks remain.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: video-recording
|
||||
description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention.
|
||||
---
|
||||
|
||||
# Heimdall video recording
|
||||
|
||||
Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses.
|
||||
|
||||
- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries.
|
||||
- Keep continuous recording (`RecordingEnabled`) and event-triggered recording (`EventRecordingEnabled`) as separate per-camera opt-ins. Event mode watches the same active Agent stream, durably records detection trigger windows under the Agent state directory with owner-only permissions, starts FFmpeg on the event, and stops 30 seconds after the latest event by default (`Agent:RecordingEventPostRollSeconds`, validated from 5 to 300 seconds). It does not record pre-roll. Disabling event mode, disabling/removing the camera assignment, or stopping its stream clears pending trigger windows and stops the process.
|
||||
- Map the primary video stream and optional first audio stream into MP4 segments. Copy compatible video without re-encoding and encode optional audio as AAC at a bounded 128 kbit/s so common RTSP audio codecs are playable in browsers; feeds without audio must still record successfully. Keep privacy/operator consent in the per-camera recording opt-in.
|
||||
- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port.
|
||||
- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback.
|
||||
- Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera.
|
||||
- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL.
|
||||
- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance.
|
||||
- Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior.
|
||||
- `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success.
|
||||
- For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag.
|
||||
- For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks.
|
||||
- Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture.
|
||||
- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera before attempting the HTTP event outbox write, so outbox capacity or delivery cannot suppress capture. Each qualifying event refreshes the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart.
|
||||
- For event-triggered acceptance, enable only `EventRecordingEnabled` through CameraDetail/API, use an assigned Agent and active synthetic RTSP stream, and prove the Agent starts capture and uploads a segment. Verify event association for both event-first and recording-first arrival. Restart the Agent during an active window and prove capture resumes from the marker; disable the toggle and prove uploads stop after configuration settles. Keep real-camera codec and timing validation separate.
|
||||
- For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`.
|
||||
- Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built.
|
||||
|
||||
On 5 November 2026, disposable Compose project `hmd-event-e2e-1793899172-25617` built Central and Agent from this source with locked .NET 10 restore. The actual Agent registered from the generated site token, consumed an animated H.264/AAC RTSP stream, emitted MotionDetected, uploaded an event-only segment while continuous recording remained off, and Central associated the event with that recording. Restarting the Agent while the post-roll marker was active produced another segment; disabling event recording through the API left the recording count stable after configuration settled. PostgreSQL event-first and recording-first association tests both pass. The focused `RecordingTriggerStoreTests` passed 3/3 in SDK Compose project `hmd-trigger-unit-1793899683-6893`. Cleanup traps removed exact local tags `heimdall:hmd-event-e2e-1793899172-25617-central` and `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, verified both absent, and confirmed zero project containers, volumes, and networks; the unit-test recipe built no local images and also left zero project resources. Synthetic motion thresholds were lowered for deterministic event generation. Real-camera codecs/timing remain unvalidated.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: vision-identity
|
||||
description: Implement Heimdall's opt-in, self-hosted plate OCR and preserve the licensing/privacy gates for camera face and plate identity.
|
||||
---
|
||||
|
||||
# Vision identity in Heimdall
|
||||
|
||||
Read `AGENTS.md` and the focused Gitea issue for FEAT-03/UI-02. Current API contract only supports a human-triggered OCR request with an operator-supplied JPEG/PNG plate crop. It does not infer plate boxes from video frames or recognize faces.
|
||||
|
||||
## Plate OCR currently implemented
|
||||
|
||||
- `PlateOcr:Enabled` defaults to false. Explicitly enable the on-prem Central option to offer OCR; the camera detail UI sends only the file the user selected.
|
||||
- Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance.
|
||||
- The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval.
|
||||
- OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path.
|
||||
- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it does not persist identity links during OCR. `CameraDetail` presents the suggestion for operator review; the operator must explicitly confirm a vehicle. The confirmation API requires a human principal with both camera and vehicle write permissions, verifies access to the camera, the event-to-observation association, and an exact normalized plate match, and writes the observation/event links together. Never treat OCR output as verified identity.
|
||||
- OCR observations remain unassigned until a human confirms an association; unassigned plate rows are purged after 30 days. `CleanupLicensePlatesJob` also removes `LicensePlateDetected` events older than 30 days, including their label and metadata. If an event has stored snapshots, it deletes those objects from the exact captured destination before deleting the database row. Events with missing/incomplete storage provenance are retained with a warning rather than deleting from a guessed destination. Vehicle-owned plate records remain governed by their explicit vehicle lifecycle. Keep the wider privacy review open before production enablement.
|
||||
|
||||
## Face-model gate
|
||||
|
||||
ONNX Runtime is already used by the Agent and is MIT licensed. A model runtime license does not grant rights to a particular model's weights or training data. InsightFace's model-zoo documentation restricts its distributed pretrained weights to non-commercial research. ONNX Model Zoo's ArcFace/UltraFace listing points to sourced models but does not establish one blanket weight/data license. Do not bundle SFace, ArcFace, YuNet, or plate-detector weights unless the exact asset and training-data rights are reviewed. An operator-provided model also needs a documented tensor/preprocessing contract, stable model ID stored with enrollments, explicit opt-in, deletion/retention semantics, and representative accuracy testing before face matches can create events.
|
||||
|
||||
Official sources reviewed:
|
||||
|
||||
- [Tesseract engine license and command-line formats](https://github.com/tesseract-ocr/tesseract)
|
||||
- [Official `tessdata_best` license](https://github.com/tesseract-ocr/tessdata_best)
|
||||
- [Official `tessdata` language-data license](https://github.com/tesseract-ocr/tessdata)
|
||||
- [Official Tesseract data-file compatibility guidance](https://github.com/tesseract-ocr/tessdoc/blob/main/Data-Files.md)
|
||||
- [ONNX Runtime repository license](https://github.com/microsoft/onnxruntime)
|
||||
- [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md)
|
||||
- [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md)
|
||||
|
||||
## Human confirmation workflow
|
||||
|
||||
- Keep mismatches and ambiguous candidate lists unlinked until an operator selects a vehicle and confirms.
|
||||
- Confirm with the observation ID, event ID and selected vehicle ID; reject anonymous or camera-scoped requests, mismatched plates, unrelated events, and conflicting existing links.
|
||||
- Preserve the matching UI/API behavior with component/controller tests and handler tests. API authorization and camera scope stay at the Web boundary; the application handler independently checks camera access before persistence.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test.
|
||||
2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. The historical entry does not record removal and exact-tag absence verification for the image; treat this recipe's image cleanup as unverified and repeat it before relying on that portion of acceptance.
|
||||
3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing.
|
||||
4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The historical record for this bootstrap does not name a locally built image tag or document an exact image absence check; treat image cleanup as unverified and repeat it before relying on that part of the acceptance. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used.
|
||||
5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked.
|
||||
6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning.
|
||||
7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or the suitability of the retention period under an external privacy review.
|
||||
8. Plate-event retention is covered by `CleanupLicensePlatesJobTests` (SQLite: expired plate event removed, recent plate and unrelated events retained; captured snapshot objects removed first; storage deletion failure retains the event) and `PlateEventRetentionPostgresTests` (PostgreSQL EF translation/deletion). The disposable Compose project `hmd-plate-retention-pg-1793885533-16210` ran the PostgreSQL test from the mounted changed source with locked restore, generated credentials, and project-scoped database/NuGet volumes; result 1/1. Teardown removed and verified zero project containers/volumes/networks. The recipe builds no Heimdall image; shared PostgreSQL/SDK base images are retained. This validates the local retention mechanics, not the external privacy policy or any production retention requirement.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Live WebRTC implementation and acceptance
|
||||
|
||||
The current vertical provides Agent RTSP re-publishing, Central camera-scoped
|
||||
Data Protection tickets and MediaMTX auth, and a camera detail WHEP player.
|
||||
`FEAT-01` stays open until the disposable synthetic acceptance below passes
|
||||
and external network behavior is measured.
|
||||
|
||||
## Required architecture
|
||||
|
||||
- Keep camera assignment and stream lifecycle in Agent. Only an enabled camera
|
||||
present in the current Central assignment snapshot may be published. Stop the
|
||||
publisher when assignment, enablement, configuration, or Agent lifetime ends.
|
||||
- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's
|
||||
browser-compatible H.264 stream to a camera-ID path. The relay passes video
|
||||
through and optionally maps the first audio track, transcoding it to Opus for
|
||||
WebRTC browser compatibility; a source without audio must still publish.
|
||||
Prefer passthrough when the source video codec is compatible; otherwise make
|
||||
video transcoding an explicit, bounded option. PTZ remains separate.
|
||||
- Central issues random, short-lived, purpose-separated publish and read claims
|
||||
scoped to one camera and one action. Protect claims with the shared Heimdall
|
||||
Data Protection key ring. MediaMTX HTTP auth must validate exact path, action,
|
||||
protocol, expiry, Agent assignment for publish, and current user camera rights
|
||||
for read. Never put RTSP credentials, Central API keys, or reusable TURN
|
||||
credentials in browser-visible URLs or logs.
|
||||
- Browser obtains a read session from the authenticated camera API and performs
|
||||
WHEP with that short-lived bearer token. ICE servers and public WHEP URL must
|
||||
come from deployment configuration, never source-code hostnames. Do not issue
|
||||
static TURN credentials to the browser.
|
||||
- Bound simultaneous Agent publishers and viewers, request duration, retries,
|
||||
FFmpeg process count, and session lifetime. Ensure cancellation/config changes
|
||||
reap child processes and release permits.
|
||||
|
||||
## Implementation references
|
||||
|
||||
Use MediaMTX's maintained documentation as the protocol reference:
|
||||
|
||||
- [WHEP/WebRTC read](https://mediamtx.org/docs/read/webrtc)
|
||||
- [HTTP authentication callbacks](https://mediamtx.org/docs/features/authentication)
|
||||
- [ICE, TURN, codec and latency details](https://mediamtx.org/docs/features/webrtc-specific-features)
|
||||
- [Configuration reference](https://mediamtx.org/docs/references/configuration-file)
|
||||
- [RTSP camera/source behavior](https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/08-rtsp-cameras-and-servers.md)
|
||||
- [MediaMTX license](https://github.com/bluenviron/mediamtx/blob/main/LICENSE)
|
||||
|
||||
Use H.264 without B-frames for browser compatibility and latency. Validate
|
||||
actual negotiation in browsers; a successful RTSP publish does not prove WHEP.
|
||||
|
||||
## Required acceptance
|
||||
|
||||
Run from changed source in an isolated disposable Compose project with unique
|
||||
project name, generated credentials, ports and volumes. The optional
|
||||
`docker/docker-compose.webrtc-test.yml` starts a local-only generated H.264
|
||||
camera feed. Use `docker/docker-compose.webrtc-local-test.yml` plus
|
||||
`docker/docker-compose.webrtc-test.yml` with the core `docker-compose.yml` in one
|
||||
unique project. Set unique generated database/JWT credentials, loopback ports,
|
||||
`HEIMDALL_NETWORK_NAME`, `HEIMDALL_MEDIAMTX_AUTH_URL`, WHEP/publish URLs, and the
|
||||
Central browser origin in an env file outside the repository. Start Central,
|
||||
MediaMTX and the synthetic feed first; bootstrap the first admin and site, then
|
||||
place the generated synthetic site token in the disposable env file and start
|
||||
the Agent. Configure its assigned camera against the host loopback RTSP port. Do not depend on a physical camera. Verify all of the following:
|
||||
|
||||
1. An assigned Agent receives only its assigned camera's short-lived publish
|
||||
credential and publishes synthetic H.264 to that camera path.
|
||||
2. An authorized user obtains a short-lived read claim and a browser-compatible
|
||||
WHEP session; the browser receives decoded frames. With synthetic audio,
|
||||
prove the browser negotiates audio and video; playback starts muted for
|
||||
autoplay compatibility and the native controls allow the viewer to enable it.
|
||||
3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired
|
||||
token, and user without camera access are rejected.
|
||||
4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the
|
||||
matching processes/sessions terminate and resource counts return to baseline.
|
||||
5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE
|
||||
secrets. Verify configured ICE/TURN candidate behavior separately.
|
||||
6. Install an EXIT trap before the first image build/start. Tear down only that
|
||||
Compose project with volumes/orphans, then verify its containers, volumes
|
||||
and network are gone. Independently remove and verify absence of every
|
||||
project-unique local image tag built by this recipe (Central, Agent, or
|
||||
helper), even after a failed build/assertion; preserve shared MediaMTX and
|
||||
other upstream base images. Preserve the test exit status and report cleanup
|
||||
failures. Do not use `--rmi all` or broad image-prune commands.
|
||||
|
||||
For this recipe the locally built tags are Central and Agent; record their
|
||||
exact project-unique values before building. The synthetic RTSP source uses
|
||||
the upstream MediaMTX and FFmpeg images, which remain installed. The cleanup
|
||||
record is complete only after both local tags have been removed and an
|
||||
exact-tag `docker image inspect` confirms absence.
|
||||
|
||||
Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and Agent relay tests pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN, external TURN and PTZ remain unvalidated. Synthetic audio codec and browser-track acceptance is recorded separately below; keep FEAT-01 open for its remaining external items.
|
||||
|
||||
## Synthetic audio acceptance
|
||||
|
||||
Run a disposable Compose source build plus a synthetic H.264+sine RTSP publisher. The source-built Agent tests must assert the relay command maps `0:a:0?`, converts audio to Opus, and does not disable audio. The Compose stream must be pulled from the relay and inspected to confirm H.264 video and Opus audio. Also run the authenticated WHEP browser flow and assert its media stream contains both tracks; no physical camera or external TURN claim follows from this recipe. Build app images with unique tags and remove/verify those exact tags in the same EXIT cleanup trap, or explicitly record `local image tags: none` for SDK/upstream-only test runs.
|
||||
|
||||
`LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` uses its fake peer by default for an isolated UI contract test. For the real-media path, set `HEIMDALL_TEST_LIVE_WHEP_URL` to the disposable MediaMTX `/path/whep` endpoint before running the same test. It then uses Chromium's real RTCPeerConnection and waits for a decoded video frame (`videoWidth > 0`) plus a live audio track. Pair this with a project-isolated MediaMTX service and synthetic H.264/Opus publisher, configured with a loopback WHEP port, a matching loopback ICE UDP candidate, and wildcard origins only on the throwaway test server. The test still mocks only Central's short-lived read-session response; the earlier Central permission/ticket test remains the evidence for that boundary. Teardown must remove and verify all project resources and any exact local image tags.
|
||||
|
||||
On 5 November 2026, disposable project `hmd-whep-audio-1793905588-381987` ran MediaMTX plus an animated 640×360 H.264 and 48 kHz sine/Opus publisher. The source-built Web/E2E assembly used the real `live-view.js` and Chromium against `http://127.0.0.1:<ephemeral>/live/whep`; `LiveViewTests` passed 1/1 with a decoded video frame, live audio track, and muted autoplay. Central's session response was stubbed, so this proves browser/media negotiation and decoding, not production auth or external ICE/TURN. Cleanup verified zero project containers, volumes and networks; no local images were built and the temporary Compose file was removed.
|
||||
@@ -14,15 +14,7 @@ public sealed class AgentOptions
|
||||
|
||||
/// <summary>URL of the Heimdall Central server, supplied by the installation or deployment configuration.</summary>
|
||||
[Required, Url]
|
||||
public string CentralUrl
|
||||
{
|
||||
get => string.IsNullOrWhiteSpace(_centralUrl)
|
||||
? ReadSystemdCredential("central-url") ?? string.Empty
|
||||
: _centralUrl;
|
||||
init => _centralUrl = value ?? string.Empty;
|
||||
}
|
||||
|
||||
private string _centralUrl = string.Empty;
|
||||
public string CentralUrl { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>Allow an unencrypted HTTP Central URL for isolated development networks only.</summary>
|
||||
public bool AllowInsecureHttp { get; init; }
|
||||
|
||||
@@ -171,7 +171,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
throw new InvalidOperationException(
|
||||
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
|
||||
|
||||
_logger.LogInformation("Registering agent with Central.");
|
||||
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
|
||||
|
||||
var maxRetries = _options.RegistrationMaxRetries;
|
||||
RegisterResponse? registration = null;
|
||||
@@ -246,11 +246,6 @@ public class AgentRegistrationService : BackgroundService
|
||||
_buffer.Count);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException ex) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// HttpClient.Timeout cancels only this request; keep the hosted service alive.
|
||||
_logger.LogWarning(ex, "Heartbeat timed out (will retry)");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Heartbeat error (will retry)");
|
||||
|
||||
@@ -11,7 +11,6 @@ namespace Heimdall.Agent.Services;
|
||||
/// </summary>
|
||||
public sealed class AnalysisJobPollingService : BackgroundService
|
||||
{
|
||||
internal const int MaxDetectionsPerResult = 500;
|
||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5);
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
private readonly AgentState _state;
|
||||
@@ -185,18 +184,13 @@ public sealed class AnalysisJobPollingService : BackgroundService
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<DetectionResult> SelectDetections(
|
||||
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections)
|
||||
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
|
||||
{
|
||||
IEnumerable<DetectionResult> selected = jobType switch
|
||||
{
|
||||
AnalysisJobType.ObjectDetection => detections,
|
||||
AnalysisJobType.PersonDetection => detections.Where(IsPerson),
|
||||
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle),
|
||||
_ => [],
|
||||
};
|
||||
|
||||
return selected.Take(MaxDetectionsPerResult).ToArray();
|
||||
}
|
||||
AnalysisJobType.ObjectDetection => detections,
|
||||
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
|
||||
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
|
||||
_ => [],
|
||||
};
|
||||
|
||||
private static bool IsPerson(DetectionResult detection) =>
|
||||
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
@@ -162,7 +162,6 @@ public sealed class DockerUpdateService : BackgroundService
|
||||
if (!string.IsNullOrEmpty(c.NetworkMode)) a.AddRange(["--network", c.NetworkMode]);
|
||||
if (!string.IsNullOrEmpty(c.RestartPolicy)) a.AddRange(["--restart", c.RestartPolicy]);
|
||||
foreach (var e in c.Environment) a.AddRange(["-e", e]);
|
||||
foreach (var group in c.Groups) a.AddRange(["--group-add", group]);
|
||||
foreach (var p in c.Ports) a.AddRange(["-p", p]);
|
||||
foreach (var v in c.Volumes) a.AddRange(["-v", v]);
|
||||
foreach (var d in c.Devices) a.AddRange(["--device", d]);
|
||||
@@ -293,7 +292,6 @@ public sealed class DockerUpdateService : BackgroundService
|
||||
c.CapAdd.AddRange(HostConfig.CapAdd ?? []);
|
||||
c.CapDrop.AddRange(HostConfig.CapDrop ?? []);
|
||||
c.SecurityOptions.AddRange(HostConfig.SecurityOptions ?? []);
|
||||
c.Groups.AddRange(HostConfig.GroupAdd ?? []);
|
||||
c.Privileged = HostConfig.Privileged;
|
||||
c.IpcMode = HostConfig.IpcMode;
|
||||
c.PidMode = HostConfig.PidMode;
|
||||
@@ -314,7 +312,6 @@ public sealed class DockerUpdateService : BackgroundService
|
||||
[JsonPropertyName("CapAdd")] public List<string>? CapAdd { get; init; }
|
||||
[JsonPropertyName("CapDrop")] public List<string>? CapDrop { get; init; }
|
||||
[JsonPropertyName("SecurityOpt")] public List<string>? SecurityOptions { get; init; }
|
||||
[JsonPropertyName("GroupAdd")] public List<string>? GroupAdd { get; init; }
|
||||
[JsonPropertyName("Privileged")] public bool Privileged { get; init; }
|
||||
[JsonPropertyName("IpcMode")] public string? IpcMode { get; init; }
|
||||
[JsonPropertyName("PidMode")] public string? PidMode { get; init; }
|
||||
@@ -353,7 +350,6 @@ internal sealed class ContainerConfig
|
||||
public string? ImageId { get; set; }
|
||||
public string? User { get; set; }
|
||||
public List<string> Environment { get; set; } = [];
|
||||
public List<string> Groups { get; set; } = [];
|
||||
public List<string> Ports { get; set; } = [];
|
||||
public List<string> Volumes { get; set; } = [];
|
||||
public List<string> Devices { get; set; } = [];
|
||||
|
||||
@@ -5,85 +5,20 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
internal interface ILiveRelayProcess : IDisposable
|
||||
/// <summary>Re-publishes assigned primary streams to the configured Central MediaMTX.</summary>
|
||||
public sealed class LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILogger<LiveCameraRelayService> logger) : BackgroundService
|
||||
{
|
||||
bool HasExited { get; }
|
||||
void KillEntireProcessTree();
|
||||
Task WaitForExitAsync(TimeSpan timeout);
|
||||
}
|
||||
|
||||
internal interface ILiveRelayProcessFactory
|
||||
{
|
||||
ILiveRelayProcess? Start(ProcessStartInfo startInfo);
|
||||
}
|
||||
|
||||
internal sealed class LiveRelayProcessFactory : ILiveRelayProcessFactory
|
||||
{
|
||||
public ILiveRelayProcess? Start(ProcessStartInfo startInfo)
|
||||
{
|
||||
var process = Process.Start(startInfo);
|
||||
if (process is null) return null;
|
||||
_ = DrainErrorsAsync(process);
|
||||
return new LiveRelayProcess(process);
|
||||
}
|
||||
|
||||
private static async Task DrainErrorsAsync(Process process)
|
||||
{
|
||||
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
|
||||
catch (IOException) { }
|
||||
}
|
||||
|
||||
private sealed class LiveRelayProcess(Process process) : ILiveRelayProcess
|
||||
{
|
||||
public bool HasExited => process.HasExited;
|
||||
public void KillEntireProcessTree() => process.Kill(entireProcessTree: true);
|
||||
public Task WaitForExitAsync(TimeSpan timeout) => process.WaitForExitAsync().WaitAsync(timeout);
|
||||
public void Dispose() => process.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-publishes assigned effective camera streams to the configured Central MediaMTX.</summary>
|
||||
public sealed class LiveCameraRelayService : BackgroundService
|
||||
{
|
||||
private readonly AgentState _state;
|
||||
private readonly IOptions<AgentOptions> _options;
|
||||
private readonly CameraConfigStore _cameras;
|
||||
private readonly IHttpClientFactory _clients;
|
||||
private readonly ILiveRelayProcessFactory _processFactory;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly ILogger<LiveCameraRelayService> _logger;
|
||||
private const int MaxPublishers = 2;
|
||||
private readonly Dictionary<Guid, Relay> _relays = [];
|
||||
private readonly Dictionary<Guid, DateTimeOffset> _retryAt = [];
|
||||
private sealed record Relay(ILiveRelayProcess Process, DateTimeOffset RenewAt, string SourceUrl);
|
||||
private sealed record Relay(Process Process, DateTimeOffset RenewAt);
|
||||
private sealed record PublishSession(string Url, DateTimeOffset RenewAt);
|
||||
|
||||
public LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILogger<LiveCameraRelayService> logger)
|
||||
: this(state, options, cameras, clients, new LiveRelayProcessFactory(), TimeProvider.System, logger) { }
|
||||
|
||||
internal LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILiveRelayProcessFactory processFactory,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<LiveCameraRelayService> logger)
|
||||
{
|
||||
_state = state;
|
||||
_options = options;
|
||||
_cameras = cameras;
|
||||
_clients = clients;
|
||||
_processFactory = processFactory;
|
||||
_timeProvider = timeProvider;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
@@ -92,7 +27,7 @@ public sealed class LiveCameraRelayService : BackgroundService
|
||||
{
|
||||
try { await SynchronizeAsync(stoppingToken); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
catch (Exception ex) { _logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
|
||||
catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
|
||||
try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
}
|
||||
@@ -100,27 +35,26 @@ public sealed class LiveCameraRelayService : BackgroundService
|
||||
finally { await StopAllAsync(); }
|
||||
}
|
||||
|
||||
internal async Task SynchronizeAsync(CancellationToken ct)
|
||||
private async Task SynchronizeAsync(CancellationToken ct)
|
||||
{
|
||||
var assigned = SelectAssignedCameras(_cameras);
|
||||
var assigned = SelectAssignedCameras(cameras);
|
||||
foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray())
|
||||
await StopAsync(id);
|
||||
|
||||
foreach (var camera in assigned.Values)
|
||||
{
|
||||
if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited &&
|
||||
relay.RenewAt > _timeProvider.GetUtcNow() &&
|
||||
string.Equals(relay.SourceUrl, camera.EffectiveRtspUrl, StringComparison.Ordinal)) continue;
|
||||
relay.RenewAt > DateTimeOffset.UtcNow) continue;
|
||||
await StopAsync(camera.CameraId);
|
||||
if (_state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(_state.ApiKey) ||
|
||||
_retryAt.GetValueOrDefault(camera.CameraId) > _timeProvider.GetUtcNow()) continue;
|
||||
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = _timeProvider.GetUtcNow().AddSeconds(20);
|
||||
if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) ||
|
||||
_retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue;
|
||||
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20);
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyDictionary<Guid, AgentCameraConfig> SelectAssignedCameras(CameraConfigStore cameras) =>
|
||||
cameras.HasCentralConfiguration
|
||||
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.EffectiveRtspUrl))
|
||||
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl))
|
||||
.Take(MaxPublishers).ToDictionary(c => c.CameraId)
|
||||
: new Dictionary<Guid, AgentCameraConfig>();
|
||||
|
||||
@@ -129,26 +63,26 @@ public sealed class LiveCameraRelayService : BackgroundService
|
||||
|
||||
private async Task<bool> StartAsync(AgentCameraConfig camera, CancellationToken ct)
|
||||
{
|
||||
var client = _clients.CreateClient();
|
||||
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", _state.ApiKey);
|
||||
var client = clients.CreateClient();
|
||||
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey);
|
||||
using var response = await client.PostAsync(
|
||||
$"{_options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{_state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
|
||||
$"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
|
||||
content: null, ct);
|
||||
if (!response.IsSuccessStatusCode) return false;
|
||||
var session = await response.Content.ReadFromJsonAsync<PublishSession>(cancellationToken: ct);
|
||||
if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false;
|
||||
|
||||
var sourceUrl = camera.EffectiveRtspUrl;
|
||||
var start = CreateStartInfo("ffmpeg", sourceUrl, destination);
|
||||
var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination);
|
||||
try
|
||||
{
|
||||
var process = _processFactory.Start(start);
|
||||
var process = Process.Start(start);
|
||||
if (process is null) return false;
|
||||
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30), sourceUrl);
|
||||
_logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
|
||||
_ = DrainErrorsAsync(process);
|
||||
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30));
|
||||
logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) { _logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
|
||||
catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
|
||||
}
|
||||
|
||||
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string source, Uri destination)
|
||||
@@ -161,20 +95,26 @@ public sealed class LiveCameraRelayService : BackgroundService
|
||||
return start;
|
||||
}
|
||||
|
||||
private static async Task DrainErrorsAsync(Process process)
|
||||
{
|
||||
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
|
||||
catch (IOException) { }
|
||||
}
|
||||
|
||||
private async Task StopAsync(Guid cameraId)
|
||||
{
|
||||
if (!_relays.Remove(cameraId, out var relay)) return;
|
||||
try
|
||||
{
|
||||
if (!relay.Process.HasExited) relay.Process.KillEntireProcessTree();
|
||||
await relay.Process.WaitForExitAsync(TimeSpan.FromSeconds(3));
|
||||
if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true);
|
||||
await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException)
|
||||
{ _logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
|
||||
{ logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
|
||||
finally { relay.Process.Dispose(); }
|
||||
}
|
||||
|
||||
internal async Task StopAllAsync()
|
||||
private async Task StopAllAsync()
|
||||
{
|
||||
foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
private readonly FrameResizer? _resizer;
|
||||
private readonly ILogger<SnapshotPipelineService> _logger;
|
||||
private readonly SemaphoreSlim _syncLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _configChanged = new(0, 1);
|
||||
private readonly Dictionary<Guid, string> _streamUrls = new();
|
||||
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
|
||||
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
|
||||
@@ -155,18 +154,8 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
// (e.g. camera settings applied before we subscribed).
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var periodicSyncDue = false;
|
||||
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
|
||||
{
|
||||
wait.CancelAfter(TimeSpan.FromSeconds(1));
|
||||
try { await _configChanged.WaitAsync(wait.Token); }
|
||||
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
periodicSyncDue = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || periodicSyncDue && DateTime.UtcNow.Second % 30 == 0)
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
|
||||
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0)
|
||||
await SyncStreamsAsync(stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -192,8 +181,6 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
private void OnCameraConfigChanged(object? sender, EventArgs e)
|
||||
{
|
||||
Interlocked.Exchange(ref _configDirty, 1);
|
||||
try { _configChanged.Release(); }
|
||||
catch (SemaphoreFullException) { }
|
||||
}
|
||||
|
||||
private async Task SyncStreamsAsync(CancellationToken ct)
|
||||
|
||||
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user