Author SHA1 Message Date
arnaud.dartois 95c73c3052 fix(agent): observe timed-out camera probes (#250)
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and scan server image (pull_request) Successful in 9m19s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 8m14s
Heimdall Gitea / CI policy (pull_request) Successful in 2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Successful in 20m7s
Heimdall Gitea / Build and tests (pull_request) Successful in 11m11s
2026-11-06 21:43:47 +01:00
162 changed files with 623 additions and 9025 deletions

No files matched your search

+2 -3
View File
@@ -6,7 +6,7 @@ Refs #
## Vérification
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
<!-- Liens des runs Gitea, suites exécutées, résultats et item actualisé dans todo.md. -->
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
@@ -19,7 +19,6 @@ Refs #
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
- [ ] Revue des changements de contrats/migrations/configuration
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
- [ ] Si tag : publication des images et release brouillon vérifiées
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 -70
View File
@@ -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,11 +100,21 @@ 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
verify:
name: Build and tests
@@ -75,7 +122,7 @@ jobs:
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
@@ -121,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
@@ -149,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
@@ -159,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: |
@@ -184,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()
@@ -204,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: |
@@ -229,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()
@@ -249,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: |
@@ -274,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: |
@@ -293,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
@@ -320,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
+1 -1
View File
@@ -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:
-2
View File
@@ -11,8 +11,6 @@
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
For Penpot design work, follow [skills/penpot-design-sync/SKILL.md](skills/penpot-design-sync/SKILL.md): always open Penpot and establish the authenticated session through the Orca browser, and keep the connected design synchronized with relevant shipped UI changes.
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
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
View File
@@ -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
View File
@@ -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/ ./
+4 -11
View File
@@ -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/ ./
-52
View File
@@ -150,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
@@ -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:
-3
View File
@@ -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
+7 -32
View File
@@ -3,41 +3,16 @@ services:
coturn:
image: coturn/coturn:4.6
pull_policy: always
# Local Compose secrets are read-only bind mounts and preserve the
# installer's 0600 owner-only permissions. Read the mounted file as a
# short-lived root initializer, write a private config into tmpfs, then
# run turnserver as nobody. The upstream binary does not exec with a
# reduced capability set; no-new-privileges still prevents elevation.
user: "0:0"
security_opt:
- no-new-privileges:true
tmpfs:
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
ports:
- "${COTURN_PORT:-3478}:3478/tcp"
- "${COTURN_PORT:-3478}:3478/udp"
- "${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
+4 -32
View File
@@ -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:
+3 -7
View File
@@ -12,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.
@@ -39,7 +35,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM installent le dépôt d’image avec le tag `latest`; Compose et `docker run` vérifient le registre au démarrage. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
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
+10 -28
View File
@@ -1,8 +1,8 @@
# Docker Compose deployment
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
separately on each camera-network host; the Central UI supplies 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
@@ -135,13 +135,11 @@ in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-ac
## Agent
Prefer the Compose shown in the Central UI's site installation panel. It uses
the Agent image's `latest` tag and includes the site token, public Central URL,
Agent name and release public key. Compose uses `pull_policy: always` so an
explicit `docker compose up` checks for the latest image. Save it as
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
contains the pinned trust key; no separate PEM file is required. Updates
dispatched later by Central continue to verify the digest in the signed release
manifest before replacing the running container.
the 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,
@@ -150,17 +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.
## Optional software
Start Central first to create the shared `heimdall-net` network. Optional
@@ -203,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:
+9 -6
View File
@@ -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,21 +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` :
Une version est publiée en poussant un tag `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Le workflow complet construit/scanne les images serveur, Agent CPU et Agent GPU une seule fois, puis publie leurs tags `sha-<SHA>` et version sur Docker Hub. Le job release réutilise ces images pour recueillir les digests; il ne les reconstruit pas et ne les rescane pas. Gitea reçoit `heimdall-installers-<version>.zip` pour Central, plus les archives Agent signées, leur clé publique, leur manifeste et les références d’images CPU/GPU nécessaires aux mises à jour natives. Provenance, liste de digests et checksums restent dans la sortie interne CI. Les couches Docker ne sont jamais attachées à Gitea. Les scripts Central `.sh` et `.ps1` récupèrent l’API de la dernière release stable, téléchargent le ZIP correspondant et exécutent son script épinglé à cette version; `HEIMDALL_INSTALLER_VERSION` permet de demander une version explicite. Le panneau d’installation Central confirme la release signée et masque les commandes natives tant que les assets nécessaires ne sont pas disponibles.
- `eltruncho/heimdall:latest` et `eltruncho/heimdall:sha-<commit complet>` ;
- `eltruncho/heimdall-agent:latest` et `eltruncho/heimdall-agent:sha-<commit complet>`.
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. Le job de tag utilise le jeton intégré `GITEA_TOKEN`, avec `contents: write` et `pull-requests: read`, uniquement dans ce job; aucun PAT durable `RELEASE_TOKEN` n’est requis et les PR ne reçoivent pas ce 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.
Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie.
Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` 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
+6 -53
View File
@@ -226,62 +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 : │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ 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.
```text
Système d'exploitation
[Linux] [Windows] [Docker]
Méthode
[Exécution] [Service systemd]
Configuration (Docker uniquement si l'image GPU est publiée)
[ ] Utiliser l'inférence GPU NVIDIA
Commandes
Installer
┌──────────────────────────────────────────────┐
│ commande/script [⧉]│
└──────────────────────────────────────────────┘
Lancer
┌──────────────────────────────────────────────┐
│ commande de démarrage [⧉]│
└──────────────────────────────────────────────┘
```
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, `MudSnackbar` (copié)
### États — Détail Site
@@ -625,10 +582,6 @@ Matrice complète des 15 permissions système avec coches par rôle
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
-1
View File
@@ -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
View File
@@ -151,7 +151,6 @@ if [[ "$RUN_MODE" == true ]]; then
HEIMDALL_DOTNET="$DOTNET_BIN" \
ASPNETCORE_ENVIRONMENT=Production \
Agent__CentralUrl="$CENTRAL_URL" \
Agent__AgentName="$AGENT_NAME" \
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
Agent__StateDirectory="$STATE_DIR" \
Agent__UpdateInstallRoot="$INSTALL_ROOT" \
+4 -72
View File
@@ -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."
+2 -67
View File
@@ -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
@@ -296,10 +236,6 @@ if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO
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"
@@ -322,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 "heimdall-${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/."
+1 -4
View File
@@ -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
+37 -261
View File
@@ -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 -1
View File
@@ -2,7 +2,7 @@
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y --no-install-recommends ca-certificates curl git 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
-34
View File
@@ -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()
-95
View File
@@ -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()
-66
View File
@@ -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 -5
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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'])
-48
View File
@@ -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).')
+3 -3
View File
@@ -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 -2
View File
@@ -2,13 +2,13 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
test('accepts an HTTPS 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
View File
@@ -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 -147
View File
@@ -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,82 +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'), 2)
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)
self.assertNotIn('secrets.GITEA_TOKEN', workflow.split(' publish:\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())
@@ -120,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)
@@ -157,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):
@@ -280,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
@@ -288,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):
@@ -335,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()
-21
View File
@@ -1,21 +0,0 @@
---
name: agent-heartbeat-timeout
description: Diagnose and validate Central heartbeat timeouts without terminating the Heimdall Agent background service.
---
# Agent heartbeat timeout
`AgentRegistrationService` sends periodic Central heartbeats through the named `Central` `HttpClient`, whose timeout is configured in `src/Heimdall.Agent/Program.cs`. An `HttpClient.Timeout` surfaces as `OperationCanceledException`/`TaskCanceledException`, even though the host's `stoppingToken` is not canceled. `SendHeartbeatAsync` must log this as a transient timeout and return to the loop. Preserve cancellation when `stoppingToken.IsCancellationRequested` so host shutdown remains cooperative.
## Change and test
- Keep the timeout handling local to `SendHeartbeatAsync`; registration cancellation and shutdown semantics have different retry behavior.
- Catch `OperationCanceledException` only under `!stoppingToken.IsCancellationRequested`, log it as a timeout, and allow the next loop iteration to retry. The existing general exception handler continues to cover other transient failures.
- In `tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs`, use an asynchronous HTTP handler that waits on the request cancellation token. Give its `HttpClient` a short timeout, then assert that a second heartbeat arrives. This verifies both the timeout source and continued service operation without waiting 10 seconds.
- Run `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter FullyQualifiedName~Heartbeat_HttpTimeout_DoesNotStopService_AndNextHeartbeatSucceeds`, then the full Agent test project.
## Disposable Compose acceptance
Run `bash skills/agent-heartbeat-timeout/acceptance.sh` from the repository root. The recipe builds the Agent image from `docker/Dockerfile.agent` in this checkout and a small local fake Central image. The fake Central delays the first heartbeat for 12 seconds (longer than the Agent's configured 10-second `Central` client timeout), then accepts later heartbeats. Acceptance requires the Agent health endpoint to respond after the timeout and the fake Central to observe a subsequent heartbeat. The script uses a random Compose project, random site token, Compose-managed isolated volume/network, dynamically assigned loopback Agent port, and unique local image tags. Its `EXIT` trap tears down only that project, verifies its containers/volumes/networks are gone, removes and verifies absence of both exact image tags, and removes temporary files. It retains shared SDK/runtime/base images.
This synthetic recipe proves local retry behavior only. It does not validate a production runner, Central instance, or post-deployment GlitchTip telemetry; record that follow-up on Gitea issue #248.
@@ -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
-38
View File
@@ -1,38 +0,0 @@
---
name: agent-startup-composition
description: Validate Heimdall Agent dependency-injection composition by starting its source-built container without a Central dependency.
---
# Agent startup composition
`src/Heimdall.Agent/Program.cs` constructs `SnapshotPipelineServiceOptions` in
the service-registration factory before registering the hosted service. Do not
register `SnapshotPipelineService` with the generic `AddHostedService<T>()`
unless every constructor dependency, including that options record, is
registered in DI. A missing dependency can prevent `Host.StartAsync` and leave
the Agent container unable to start.
## Acceptance
Run `bash skills/agent-startup-composition/acceptance.sh` from the repository
root. The recipe builds only the CPU Agent image from the current checkout with
a unique local tag and starts it in a disposable Compose project with generated
site-token data and an internal-only network. Its Central URL points to the
Agent container's own unused loopback port; it cannot reach a deployment.
The recipe proves that:
1. The Agent host starts and remains running with its production service
registrations, including `SnapshotPipelineService`.
2. `/health/live` responds successfully before registration with Central; the
readiness endpoint `/healthz` is intentionally not used because it reports
Unhealthy until Central registration succeeds.
3. Startup logs do not contain the missing
`SnapshotPipelineServiceOptions` dependency or a host-start failure.
4. Cleanup removes the exact Compose project, generated state volume/network,
and this recipe's one exact Agent image tag, then verifies their absence.
This checks DI and host startup only. It does not validate Central registration,
camera discovery, model inference, a published Agent, or a deployed installation.
The EXIT trap preserves the test result, attempts each cleanup independently,
and reports cleanup failures. The Dockerfile's shared .NET base images remain.
@@ -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"
-34
View File
@@ -7,40 +7,6 @@ description: Validate Heimdall native Agent install, signed update, startup heal
Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`.
For Docker Agent install/update changes, also inspect the generated Compose and
`docker run` commands in `SiteInstallPanel.razor`, plus both CPU and NVIDIA
Agent images. The Docker updater shells out to the Docker CLI and therefore
requires the CLI in the image and `/var/run/docker.sock` mounted into the
container. Validate the generated Compose and Docker-run command together;
document that mounting this socket grants broad control of the host. The Docker
Run panel must provide POSIX and PowerShell commands, use an immutable signed
image reference, initialize the state volume, and keep the health endpoint
reachable for update rollback checks. A disposable image acceptance should
build with a project-unique tag and assert `docker --version` inside the image,
then remove and verify absence of that exact tag. When Compose has multiple
services using the built Agent image, the acceptance override must retag every
service, including one-shot volume initialization, so it does not create an
untracked `:local` image.
For Windows Service installation, set `MODEL_PATH` to the installed
`current\models\yolov8n.onnx` path because the Service Control Manager does not
start services from the Agent release directory. Validate the service's model
path, enrollment, startup, signed update, and rollback on a real Windows host;
PowerShell parsing on Linux is not a substitute for that run.
For Linux systemd installs, preserve the site display name through the existing
`LoadCredential=agent-name` credential and `AgentOptions` fallback. The
foreground installer may pass `Agent__AgentName` directly; do not put arbitrary
site names in an unescaped systemd `Environment=` assignment.
Before accepting a native or Docker install flow, verify that Central's global
`updates.forgepublicurl` contains only the HTTPS public Forgejo origin and that
Central constructs `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` from
it. The calculated API URL is read-only in Settings. A published release must
contain the signed manifest, asset checksums, and required image digest. A
`main` Docker image build alone cannot supply the signed Agent release metadata
used by installers and the IHM.
## Linux rollback simulation
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
+3 -4
View File
@@ -9,14 +9,13 @@ Read `AGENTS.md`, the PIPE-01/02 Gitea issue, and `skills/heimdall-dotnet/SKILL.
## Current supported job types
- `ObjectDetection`: return detections produced by the configured YOLO COCO model in model order, capped at 500 because Central rejects larger successful results. The Agent truncates deterministically before serialization so the result can be persisted; detections after the first 500 are intentionally omitted.
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`), capped at 500 after filtering while preserving model order.
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`), capped at 500 after filtering while preserving model order. Keep the model label, confidence, box and class index in the result.
- `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.
- For every job type, cap successful result detections at Central’s 500-item limit in stable model order. For filtered types, filter first and then cap so unrelated model classes do not consume the result budget. Add boundary tests proving the output count and retained order for ObjectDetection and filtered types. This prevents Central’s permanent HTTP 400 rejection from silently discarding the whole result, while making the truncation explicit.
- 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,23 +0,0 @@
---
name: api-key-last-used-throttle
description: Preserve Heimdall API-key authentication while limiting LastUsedAt persistence to one atomic EF Core update per minute.
---
# API-key activity timestamp
`ApiKeyAuthenticationHandler` authenticates an agent API key for every protected request. `LastUsedAt` is an operator-facing activity indicator; it does not need request-level precision. Keep API-key validation, agent binding, authorization claims, and expiry checks on every request, while avoiding a database write for every heartbeat or telemetry call.
## Implementation
- Pass `HttpContext.RequestAborted` to each database read and write in the authentication handler.
- Update `LastUsedAt` with EF Core `ExecuteUpdateAsync`, using a database-side predicate that permits the write only when the timestamp is null or at least one minute old. The predicate and update must be one SQL statement so concurrent requests using the same key collapse to one write.
- Do not call `SaveChangesAsync` for this timestamp. The handler has no other pending changes, and the tracked API-key entity is only needed for validation and claims.
- Keep the timestamp semantics visible to operators: after a burst of requests, it reports recent use with up to one minute of delay.
## Acceptance
1. A PostgreSQL relational test verifies that a null timestamp is written, requests inside the one-minute window do not rewrite it, an expired window refreshes it, and concurrent requests produce no duplicate update within the window.
2. API-key authentication tests verify valid, expired, unbound, and invalid keys retain their existing outcomes and claims.
3. Run the CI EF Core persistence policy and the focused Infrastructure/Web test suites.
4. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique credentials, project name, ports, volumes, and local image tag. Verify authentication behavior, then verify that project resources and the exact locally built tag are absent after teardown.
5. Link the change to Gitea GlitchTip issues #200, #201, #202, #203, and #205. Record the actual local/CI/Compose results and keep post-deployment GlitchTip evidence distinct.
-25
View File
@@ -1,25 +0,0 @@
---
name: api-key-localization
description: Maintain and verify French and English localization for Heimdall's API key administration page and dialogs.
---
# API key localization
The API key administration UI is `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor`. Its text comes from `AdminApiKeys_*` entries in `src/Heimdall.Web/Localization/SharedResources.*.resx` through `UiText`; the active culture is selected by `UiLanguageService`.
## Updating strings
1. Keep every `AdminApiKeys_*` key present in the neutral resource and localized resources. Use `SharedResources.en.resx` as the English wording reference and translate all visible create, one-time-secret, revoke, validation, helper, and empty-state copy in `SharedResources.fr.resx`.
2. Replace placeholder values that repeat a key suffix (such as `ExpiryHelp`) with actual English fallback copy in `SharedResources.resx` and an actual French translation in `SharedResources.fr.resx`. Check the related `AdminAllAgents_EmptyDescription` entry when auditing the French admin empty states.
3. Preserve formatting tokens such as `{0}` in interpolated resource values and preserve the API date format when translating optional date labels.
4. Add or update focused bUnit tests under `tests/Heimdall.Web.Tests/Components/Pages/`. Render the page with `PageTestBase`, serve an empty API key list via `api/api-keys`, and assert the French empty-state description and create-dialog labels with key-suffix placeholders absent. For other dialogs, exercise the corresponding UI action and assert the rendered localized text.
## Acceptance
Run the focused tests with:
```sh
dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter 'FullyQualifiedName~ApiKeysPageTests|FullyQualifiedName~AllAgentsPageTests'
```
The acceptance evidence should record the command and result. A test run blocked by shared-runner contention is not a pass; rerun it when the runner is available. This localization-only change does not need a disposable Compose acceptance recipe because it changes no runtime behavior or deployment configuration.
+1 -4
View File
@@ -5,15 +5,12 @@ description: Validate Heimdall PostgreSQL and protected-volume backups using iso
# Heimdall backup and restore
For an explicitly authorized real backup/restore operation, follow [Infisical secrets](../infisical-secrets/SKILL.md) and retrieve only the selected environment's required key. Use generated credentials and disposable volumes for acceptance.
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.
- Preserve the entire Data Protection ring and `dp-cert.pfx` together. Expired keys can still be required to unprotect stored payloads; never replace/delete one file as part of a restore. Heimdall has no validated manual rotation process for the certificate that protects the ring at rest; keep certificate rotation separate until tested against existing payloads. See `docker/backup/README.md`.
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume.
@@ -22,7 +19,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. For actual RPO/RTO drills, use the timestamp, resource, host, and repeated-run procedure in `docker/backup/README.md` and record the operator-approved target separately.
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.
@@ -1,16 +0,0 @@
---
name: camera-access-async-admin-check
description: Keep camera and site authorization admin-role checks asynchronous in Heimdall.
---
# Async administrator checks in camera access
`CameraAccessService` uses `IIdentityPersistenceContext` for Identity role membership. Never call synchronous EF operators on `UserRoles` or `Roles` in this authorization path. The filter API is asynchronous because the admin bypass must be decided before building the grant-filtered camera query.
When changing this behavior:
- Use `AnyAsync` and pass the caller's `CancellationToken` through the role lookup and final camera/site query.
- Preserve the empty-user rejection and `AppRoles.Admin` predicate; ordinary users continue to use direct, site-wide, legacy, and live group grants.
- Keep camera scoping at API/application boundaries. Update `ICameraAccessService` consumers when changing its async filter contract.
- Run `CameraAccessServiceTests`, `ResourceAccessTests`, and `CameraAccessAdminPostgresTests`; mocks alone do not establish relational behavior.
- Run the EF Core persistence policy and disposable source-based Compose acceptance. Record exact image tags and cleanup evidence on the Gitea issue.
@@ -1,17 +0,0 @@
---
name: camera-access-nullable-select
description: Keep nullable camera-access grant selectors type-consistent in the Heimdall Blazor UI and verify site-wide and camera-specific grants.
---
# Camera access nullable selectors
The grant form in `src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor` stores the selected site and camera as `Guid?` because the form supports an unset selection. Keep each corresponding `MudSelect` and all of its `MudSelectItem` children explicitly typed as `Guid?`; cast non-nullable model IDs with `(Guid?)` in each item value. A plain `Guid` item can compile yet fail at runtime when MudBlazor dispatches the option click to its nullable parent.
When editing this form, preserve the two grant modes: site-wide grants save a site ID and null camera ID, while camera-specific grants save both IDs. Validate both selection interactions and the serialized saved grants.
## Acceptance workflow
1. Run the focused Web tests with `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` and build `src/Heimdall.Web/Heimdall.Web.csproj` using the SDK pinned in `global.json`.
2. For behavior changes, follow [the disposable Compose recipe](../compose-disposable-recipe/SKILL.md): build the changed source using unique local image tags and isolated credentials, project, ports, network, and volumes.
3. Bootstrap an isolated administrator, use a real browser/UI-capable test to select a site-wide option and a camera option, and verify the saved grants contain respectively a null and non-null camera ID with no `InvalidCastException`.
4. Tear down only that Compose project. Verify its containers, volumes, and networks are absent; remove and verify absence of only the recipe's exact locally built tags, preserving shared base images.
+3 -24
View File
@@ -9,19 +9,14 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
## Implementation path
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled.
- Agent status reports require the API key to resolve to the same Agent ID in the route and the camera to be assigned to that Agent. Authenticate and authorize both resources with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`.
- `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.
- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal.
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
## Local verification
The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract.
Run the focused Agent lifecycle suites:
```bash
@@ -32,8 +27,6 @@ These tests cover session idempotence, process termination, and synchronization
## Central + Agent disposable acceptance
Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap.
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
@@ -49,7 +42,7 @@ This acceptance proves the source-built Central/Agent software lifecycle with a
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external.
- 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
@@ -57,18 +50,4 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
## Sixth source-built run
The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source.
## Immediate config reconciliation regression test
`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance.
## Source-built acceptance — 2026-11-12
`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera.<id>.enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing.
## Camera status contract acceptance
For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, reject its report before camera assignment, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled.
A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence.
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.
@@ -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
+3 -7
View File
@@ -5,21 +5,17 @@ description: Maintain Central server installation, Compose refresh, and Docker i
# Central installation and image updates
For credentials needed by an explicitly requested real deployment, follow [Infisical secrets](../infisical-secrets/SKILL.md). Disposable Compose acceptance continues to use generated credentials and isolated resources.
Use this skill when changing the Linux or Windows Central installer, its generated Compose, or Central container update behavior.
For installer, Compose, image, and documentation work that can proceed independently, use [parallel development with Orca](../parallel-development/SKILL.md). Keep shared deployment contracts and the final isolated acceptance run coordinated and integrated before recording evidence.
## 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 source is the global `updates.forgepublicurl` setting edited in Settings. It stores only the public HTTPS Forgejo origin; `ForgeReleaseApiAddress` constructs the fixed Heimdall `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` endpoint, which Settings displays read-only. Startup migrates legacy `updates.releaseapiurl` values to their origin and removes the old row. Agent release checks must go through the authenticated Central `/api/updates/agent/latest` endpoint, which returns the configured manifest and asset URLs.
- 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 Forgejo API endpoint used by Renovate through the Actions variable `FORGEJO_API_ENDPOINT`; Forgejo reserves variable names beginning with `GITEA_`. Do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- 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
@@ -45,7 +41,7 @@ For installer, Compose, image, and documentation work that can proceed independe
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the corresponding `:latest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
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.
+2 -16
View File
@@ -5,12 +5,8 @@ description: Build and acceptance-test Heimdall changes in a disposable Docker C
# Disposable Compose acceptance
Follow [Infisical secrets](../infisical-secrets/SKILL.md) when the surrounding task also needs real credentials. Acceptance projects must always use generated synthetic values and must never retrieve deployment secrets from Infisical.
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`.
When implementation or acceptance preparation has independent branches, use [parallel development with Orca](../parallel-development/SKILL.md) to assign bounded work. Keep the final Compose run, cleanup verification, and acceptance evidence under one coordinator so the combined change is validated as a whole.
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
@@ -36,13 +32,6 @@ Compose teardown cannot skip image and temporary-file cleanup. Preserve the
original status and return a failure if any cleanup verification fails:
```bash
# Initialize these exact paths before installing the trap. Omit source_copy if
# the recipe does not create a source archive.
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
source_copy="$temp_dir/source-copy.tar"
cleanup() {
status=$?
trap - EXIT
@@ -59,10 +48,7 @@ cleanup() {
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
# Remove only the files this recipe generated; rmdir fails visibly if
# anything unexpected remains in the temporary directory.
rm -f -- "$env_file" "$compose_override" "$source_copy" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
rm -rf -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
status=1
@@ -93,6 +79,6 @@ recipe that reports teardown without the image-tag check is incomplete.
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 each explicitly named generated environment, secret, override, and copied-source file with `rm -f`. Finish with `rmdir` on the one temporary directory; a non-empty directory must make cleanup fail visibly. Attempt each cleanup action even if an earlier action fails. Retain shared upstream/base images. Do not use recursive deletion, Compose `--rmi all`, or broad prune commands.
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.
-2
View File
@@ -11,6 +11,4 @@ Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime lay
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.
When Trivy reports fixed .NET runtime advisories, update the pinned SDK and ASP.NET runtime manifest-list digests together across all three Dockerfiles and every SDK container in `.gitea/workflows/build.yml`. CI must use the SDK matching the updated lockfile, or locked restore fails against stale SDK reference assets. Confirm the new tags and digests against Microsoft's .NET release notes and `docker buildx imagetools inspect`; keep the SDK major/minor aligned with `global.json`. For the November 2026 ASP.NET Core 10.0.15 security update, the `10.0-noble` tags must resolve to images containing runtime 10.0.15, which fixes CVE-2026-114146, CVE-2026-114147, and CVE-2026-114149. Do not suppress these findings or change the CI severity threshold.
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.
@@ -1,17 +0,0 @@
---
name: dashboard-refresh-lifecycle
description: Maintain the Heimdall Web dashboard's post-render agent refresh loop and component shutdown behavior.
---
# Dashboard refresh lifecycle
The dashboard starts its 15-second agent refresh only after the first interactive render. Keep the loop task and its `CancellationTokenSource` owned by the component. Capture the token once when starting the loop; do not read the mutable source inside the loop because disposal or a restart can replace it.
When the component is disposed, mark it disposed under the same synchronization used to start the loop, cancel the source, and let the loop finish before disposing that source. Handle a request cancellation as a normal shutdown, keep transient/401 load failures from escaping the renderer, and do not schedule `StateHasChanged` after disposal.
## Acceptance
- Exercise component disposal while a refresh is pending and confirm no renderer exception escapes.
- Exercise an agent request failure (including unauthorized) and confirm dashboard rendering remains stable and no periodic work survives component disposal.
- Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj`.
- For behavior changes, run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, then verify project resource and exact locally built image tag cleanup.
@@ -1,28 +0,0 @@
---
name: dashboard-welcome-punctuation
description: Keep Heimdall's localized dashboard greeting punctuation consistent across its route aliases.
---
# Dashboard welcome punctuation
`Dashboard.razor` serves both `/` and `/dashboard`. The `WelcomeUser` resource
owns the punctuation at the end of the localized greeting (French and English
currently both end in a comma); the Razor markup must add only a space before
the display name.
## Change and acceptance workflow
1. Inspect `Dashboard.razor` and the `WelcomeUser` values in
`SharedResources.fr.resx` and `SharedResources.en.resx` before changing the
greeting. Keep one punctuation owner instead of composing punctuation in
both places.
2. In `DashboardTests`, render the component with `UiLanguageService` set to
each supported language and assert the rendered greeting contains exactly
the expected localized punctuation and display name.
3. Since `/` and `/dashboard` are aliases on the same component, verify both
route templates remain declared on the component and exercise this same
rendering assertion for the shared output.
4. Run the focused web test project. For behavior changes, also run the
disposable Compose acceptance recipe from
`compose-disposable-recipe/SKILL.md`, using unique project resources and
removing only recipe-owned image tags during cleanup.
@@ -1,22 +0,0 @@
---
name: database-migration-startup
description: Diagnose and validate Heimdall Central's EF Core PostgreSQL migration startup, including first boot, restart, retry exhaustion, and recovery.
---
# Database migration startup
`src/Heimdall.Web/Program.cs` calls `Program.ApplyMigrationsAsync` before configuring recurring Hangfire jobs and seeding identity data. The method uses one `AppDbContext`, retries a failed `Database.MigrateAsync` five times with exponential delays, logs the terminal exception at Critical, then rethrows so Central cannot become ready with a failed migration.
For startup incidents, correlate the EF `CommandError` with the following `Program` retry/final logs. A failed EF command log alone does not prove that startup failed: a later retry may have succeeded. Preserve the provider exception and SQLSTATE when available, but never record a connection string, password, user identifier, or database row. Do not suppress EF command errors to hide a symptom.
## Acceptance
Run `bash skills/database-migration-startup/acceptance.sh` from a clean checkout. The recipe builds Central from this source with one unique local image tag, uses a fresh PostgreSQL database and generated credentials, and checks:
1. First boot applies migrations and `/healthz` becomes healthy.
2. A second startup against the migrated database remains healthy.
3. A synthetic database role with access to the database/schema but no `SELECT` on `public.__EFMigrationsHistory` causes migration startup to exhaust all five attempts, emit the final Critical failure, and exit nonzero without logging migration success.
4. Granting that role `SELECT` and restarting Central allows migration startup and health checks to succeed.
5. The EXIT trap removes only this Compose project and its exact image tag, then verifies that its containers, volumes, network, and image are absent. Shared PostgreSQL and .NET base images are retained.
This synthetic permission failure verifies fail-closed and recovery behavior; it does not establish the cause of a separate deployment's EF error. Record production evidence only when an event includes the provider exception/SQLSTATE and correlated startup outcome.
@@ -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.'
-25
View File
@@ -1,25 +0,0 @@
---
name: detail-route-not-found
description: Keep Heimdall detail pages consistent when an API object no longer exists.
---
# Missing objects on detail routes
Use this workflow when a detail page already has an explicit “not found” state and an API read can return HTTP 404. Current routes covered are Agent (`AgentDetail.razor`), Camera (`CameraDetail.razor`), and Person (`PersonDetailPage.razor`).
## Implementation
- Keep the API client's normal `GetFromJsonAsync` behavior. A 404 raises `HttpRequestException` with `StatusCode == NotFound`. Agent and Camera resource-boundary checks intentionally return 403 for missing or out-of-scope records; treat that expected privacy response like the existing not-found rendering too. Person reads use 404.
- Preserve the generic error notification for unexpected failures. Do not treat 401, server, timeout, or malformed-response errors as “not found”.
- Do not fetch dependent page data after the primary object is absent. In particular, Camera must not load events, recordings, snapshots, or start periodic refresh, and Person must not load faces, vehicles, or events.
- Keep authorization and API responses unchanged. The UI behavior handles stale links and objects deleted between navigation and load.
## Acceptance
1. Add a component test for each route with a synthetic UUID and its expected hidden/missing response (Agent/Camera 403, Person 404).
2. Assert the existing not-found state is rendered, no snackbar is shown, and no dependent API call is made.
3. Retain or add an unexpected HTTP failure check proving the generic notification still appears.
4. Run the focused Web tests and Web build.
5. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`; verify all three routes through the app boundary using isolated synthetic data and record exact project/image cleanup evidence.
The route-level checks require an authenticated synthetic account. Do not create or retain real people, cameras, Agents, or camera connection data for acceptance.
-2
View File
@@ -7,8 +7,6 @@ description: Implement or review database persistence in Heimdall with Entity Fr
Use this skill whenever changing how application or Agent data is read or written.
For work spanning multiple persistence concerns, use [parallel development with Orca](../parallel-development/SKILL.md). Keep each `DbContext` operation isolated; assign migration/model ownership clearly and serialize edits that touch the same entity configuration or migration chain.
- 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.
-2
View File
@@ -5,8 +5,6 @@ description: Implement or diagnose Heimdall's mandatory first administrator setu
# First administrator setup
For deployment bootstrap credentials, follow [Infisical secrets](../infisical-secrets/SKILL.md) and retrieve only the explicitly selected environment's required keys. Disposable acceptance must use generated accounts and passwords, never vault credentials.
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.
-7
View File
@@ -5,14 +5,8 @@ description: Create, maintain, link, and close Heimdall project tickets in Gitea
# Gitea ticket workflow
For credentials used while investigating or validating tickets, follow [Infisical secrets](../infisical-secrets/SKILL.md). Never put secret values in issue descriptions or comments; use metadata-only existence checks when documenting prerequisites.
When a change is delivered through a PR, include its automatic release assessment using [pull request release assessment](../pr-release-versioning/SKILL.md); do not ask the user to choose whether or which version to release.
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.
For implementation work that has independent tasks, use [parallel development with Orca](../parallel-development/SKILL.md). Keep Gitea as the work-status source: create linked issues for independently deliverable outcomes, while Orca Runs/Tasks coordinate the execution and dependencies.
## Before implementation
1. Read `AGENTS.md` and the focused skill(s) for the affected area.
@@ -83,7 +77,6 @@ Render long historical logs as a clearly separated `<details><summary>Historique
## Pull requests and closure
- Before opening/updating a PR, verify the issue number, link, acceptance criteria, focused skill, and test/acceptance evidence are present.
- Keep `.gitea/PULL_REQUEST_TEMPLATE.md` aligned with this workflow: request the linked Gitea issue and observed CI/acceptance evidence; never direct contributors to update a markdown backlog.
- 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.
-23
View File
@@ -1,23 +0,0 @@
---
name: hangfire-startup-lock
description: Diagnose and recover Heimdall startup from transient Hangfire PostgreSQL recurring-job lock contention.
---
# Hangfire startup lock recovery
Heimdall registers all recurring jobs synchronously after database migrations in `src/Heimdall.Web/Program.cs`. Hangfire's PostgreSQL storage acquires a distributed lock per recurring-job id during `AddOrUpdate`; `agent-failover` is currently the first registration after removing the legacy `heartbeat-monitor` id.
## Implementation and diagnosis
- Inspect the GlitchTip event stack, app start time, event timestamps, and `Program.cs`/`JobSetup.cs` line references. A timeout names the contended job key; it proves lock contention, not the number or identity of competing processes.
- Because registration is on the startup path, an unhandled provider lock timeout terminates startup even when caused by another instance. Retry only `Hangfire.PostgreSql.PostgreSqlDistributedLockException`; do not retry arbitrary registration/configuration failures.
- Retry the complete idempotent `ConfigureRecurringJobs` sequence with a new DI scope per attempt. Keep delay bounded, observe application shutdown cancellation, log attempts without connection details, and propagate the final exception so missing recurring schedules are not reported as successful startup.
- Cover transient recovery with a focused test that injects the provider exception and verifies a subsequent full registration attempt.
## Acceptance
1. Run `dotnet test tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj --no-restore --filter FullyQualifiedName~RecurringJobStartupRetryTests` and build the Web project using the SDK pinned in `global.json`.
2. Run a disposable Compose project from the changed source with unique project name, generated credentials, loopback port, volume names, and a unique Heimdall image tag. Confirm the Web service becomes healthy and recurring Hangfire jobs are available in the isolated PostgreSQL storage.
3. Use an EXIT trap to tear down only that Compose project, verify its containers, volumes, and networks are absent, remove and verify absence of its exact locally built image tag, and remove temporary files. Preserve the original status and report cleanup failures.
The Compose check demonstrates isolated startup and Hangfire storage integration; the synthetic unit test demonstrates contention recovery. Neither establishes that a particular production deployment had one or multiple replicas. Record deployed telemetry separately in Gitea issue #214.
-2
View File
@@ -7,8 +7,6 @@ description: Implement or review Heimdall .NET 10 application, EF Core persisten
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 multi-layer work, use [parallel development with Orca](../parallel-development/SKILL.md) to dispatch non-overlapping layer tasks early, sequence shared contract decisions, and integrate the result before running combined verification.
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).
-6
View File
@@ -14,9 +14,6 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- 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.
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`.
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
@@ -26,11 +23,8 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- 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 cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
-182
View File
@@ -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
-30
View File
@@ -1,30 +0,0 @@
---
name: infisical-secrets
description: Retrieve and maintain Heimdall project credentials in the connected Infisical instance while keeping secret values out of repository files, transcripts, and logs.
---
# Heimdall secrets in Infisical
Use this workflow whenever a Heimdall skill needs a real credential, and link this skill from any skill that adds or changes a credential workflow. The connected MCP server is the supported interface to Infisical.
## Vault and scope
- Select project **Orca** (`orca-cc2-m`) explicitly; its project ID is `96fb3628-2ee3-45b5-b6a8-66a0212a5b46`. Use `dev`, `staging`, or `prod` only when the task names that environment. Never silently fall back from one environment to another.
- Use the MCP tools `list-projects`, `list-secrets`, `get-secret`, and `create-secret`. They are allowlisted in the local MCP configuration. Never use `create-secret` as an implicit overwrite operation: check the key first and explain/ask before replacing an existing value.
- `list-secrets` returns secret values as well as names. Treat its full response as sensitive even when only checking availability. Do not print, quote, summarize, or copy values into tool output, chat, shell history, command arguments, files in the repository, issue/PR text, or logs.
- Prefer retrieving only the needed key with `get-secret`. Pass the value directly to the one process that needs it using a protected stdin/temporary file outside the repository with mode `0600`, then remove that exact file. Never interpolate it into a command string or a checked-in Compose file.
- Use metadata-only checks to report which keys exist. Never test access by dumping a value. If a diagnostic accidentally emits a value, stop, do not repeat it, and tell the user that the credential should be rotated. Do not rotate it unless the user explicitly asks.
## Using secrets in skill workflows
- Distinguish real deployment credentials from disposable acceptance credentials. Compose acceptance recipes must generate unique synthetic credentials and must not fetch production or staging values from Infisical.
- For local manual integration work, fetch only the named development key needed by that skill. For a deployment task, use the explicitly requested environment and target. Never place fetched values in `.env.example`, tracked configuration, source, fixtures, or documentation.
- CI secrets remain in the CI secret store unless a task explicitly migrates the CI workflow. Infisical presence alone does not configure Gitea Actions or prove a runner can access the vault.
- When a workflow needs a credential not present in the selected environment, report its exact key name and purpose; do not substitute a similarly named credential or a different environment.
- When asked to persist a newly provided credential, use `create-secret` in the selected project/environment/path. First verify the key is absent, then create it, then verify presence by listing metadata only. Do not echo the supplied value.
## Current inventory verified 2026-11-10
The `dev` root currently contains `GITEA_ORCA_TOKEN`, `HEIMDALL_LOGIN`, `HEIMDALL_PASSWORD`, `HEIMDALL_PRIVATE_KEY_B64`, `HEIMDALL_URL`, `PENPOT_LOGIN`, `PENPOT_PASSWORD`, and `PENPOT_URL`. The `staging` and `prod` roots were empty at verification time. Treat this inventory as a dated snapshot; check metadata again before relying on it.
The development inventory does not include Heimdall deployment/database/JWT, RustFS, Agent site-token, Coturn, Redis, Sentry, Docker Hub, or release-signing credentials. Some are generated for disposable acceptance, some are optional, and CI publication credentials belong in Gitea Actions. Do not add real values simply to make the inventory look complete; report only keys required by the active task.
@@ -1,23 +0,0 @@
---
name: installer-checksum-acceptance
description: Build and verify the versioned Central installer checksum asset and both server bootstrap verification paths.
---
# Central installer checksum acceptance
Use this workflow when changing `install/install-server.sh`, `install/install-server.ps1`, `scripts/ci/package.sh`, or the release asset set in `scripts/ci/release-gitea.py`.
## Release contract
- `package.sh` creates `heimdall-installers-<version>.zip.sha256` beside the ZIP. Its single standard `sha256sum` line names the ZIP asset exactly, with no workspace-relative path.
- `release-gitea.py` requires and publishes both files before making a release visible. The sidecar is part of the exact expected asset set for already-published releases.
- The raw Linux and Windows bootstraps prefer a valid `sha256:<64 hex>` digest from the matching release API asset. If the digest is absent or null, they find the correspondingly named checksum asset, require an HTTPS download URL and exactly one checksum line naming the ZIP, download the ZIP, and compare its SHA-256 before extraction or execution.
- A malformed, non-null API digest fails closed. Do not fall back from an invalid digest or calculate the expected checksum from the ZIP that is being verified.
## Acceptance
1. Run `python3 scripts/ci/accept-release-offline.py` in a clean dedicated checkout. Its TLS loopback Gitea double and fake Docker CLI must prove release asset publication, the API digest-present path, the Forgejo-compatible `digest: null` sidecar path, rejection of a mismatched sidecar, and fail-closed behavior for a malformed non-null API digest. Assert the expected installer asset names and the sidecar content against the produced ZIP.
2. Run `python3 -m unittest scripts.ci.test_ci` (or the repository's equivalent CI policy test command) and verify release asset fixtures include the sidecar.
3. Run `bash -n install/install-server.sh`; if `pwsh` is available, parse `install/install-server.ps1` without invoking Windows-only installation actions.
4. For any disposable Compose validation required by the behavior change, follow `skills/compose-disposable-recipe/SKILL.md`: use source-built unique tags and isolated credentials/ports/volumes, install cleanup before build/start, and verify project resources and exact image tags are absent afterward.
5. Record local and CI evidence in the Gitea issue and PR. Do not claim a production Gitea release, `/releases/latest`, Docker Hub, runner, or deployed installer was validated by the offline API double.
+1 -5
View File
@@ -24,12 +24,8 @@ Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md
- 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.
## UDP receive lifetime at shutdown
`MdnsClient` owns each `UdpClient` for one probe/discovery call. When a receive window expires, cancel the receive with a linked token and await its task before leaving the socket scope; this observes the expected cancellation and prevents a pending receive task from surfacing later as `UnobservedTaskException`. Do not swallow unrelated `SocketException` failures: keep them observable (or log a sanitized exception type at the discovery boundary). The focused regression test `ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures` covers expected cancellation and an unexpected socket failure. Run the focused and full `Heimdall.Agent.Tests` suites after changes to this lifecycle.
## 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 recursively referenced source projects, plus root build props/targets and `global.json`, into a temporary archive outside the repository. Mount the archive read-only, extract it inside the SDK container with `tar --no-same-owner` into `/tmp` (the container filesystem there is writable), and restore with `--locked-mode`. For mDNS lifecycle changes, run `HomeKitMdnsProbeTests` and the focused receive-cancellation regression test; otherwise run the relevant focused Agent tests. Use a unique Compose project, project-scoped NuGet package volume, and isolated bridge; publish no ports and never use host networking. The container is read-only except for `/tmp`, `/root/.local/share/NuGet` (NuGet HTTP cache), and the project-scoped package volume. Do not mark the bridge `internal`: locked restore may need NuGet network access; the bridge remains isolated from host/production networks. 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 archive and Compose file, 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.
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`.
-17
View File
@@ -1,17 +0,0 @@
---
name: notification-center
description: Implement and accept the authenticated Heimdall in-app notification center.
---
# Notification center
The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser.
## Acceptance
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.
2. In disposable Central + PostgreSQL Compose, create only synthetic notifications for the disposable admin, open `/notifications` from the header bell, confirm notification content appears and `/events` is not loaded.
3. Mark one item read and all items read; verify displayed state and unread badge refresh. Confirm empty and API failure states render.
4. Use unique Compose project, generated credentials, loopback port, and project-owned image tag. Follow `compose-disposable-recipe` exactly: remove only that project and exact local tag, verify project containers/volumes/networks and image tag are absent, and retain shared images.
The empty and failed API states have focused bUnit coverage in `NotificationsPageTests`. Simulate the API error with an HTTP 500 response for `GET /api/notifications`; taking PostgreSQL offline also breaks server-side session validation before the page can handle the notification request.
-29
View File
@@ -1,29 +0,0 @@
---
name: optional-server-services
description: Keep installer-managed RustFS and coturn Compose services aligned with the server installer's paths and networking.
---
# Installer-managed optional services
The Linux and Windows server installers save service secrets in `<install-root>/optional/secrets/`, backup scripts in `<install-root>/optional/scripts/`, and pass the root `.env` for interpolation. Compose resolves relative paths from its project directory, which otherwise defaults to the directory containing the first `-f` file. RustFS and coturn Compose files reference `./optional/secrets/<name>`, so start them with `--project-directory <install-root>`. The backup Compose references `./scripts` and `./secrets/db_password`, so start it with `--project-directory <install-root>/optional`. Preserve these service-specific bases; applying the installation root to every optional Compose breaks the backup mounts.
## RustFS
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
- Verify actual optional-service invocations use the right project directory: `<install-root>` for RustFS/coturn and `<install-root>/optional` for backup. Confirm normalized secret and script bind sources point to exact generated files/directories. A successful `config` without checking normalized source paths is insufficient because Compose can accept an unintended path that happens to exist.
- Keep the named data volume and shared `heimdall-net` behavior intact.
## coturn
- Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`.
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
- Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings.
- Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults.
- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address.
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
## Acceptance
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose with each installer's explicit project directory. It asserts the normalized RustFS/coturn secret paths and backup secret/script bind sources exactly match the generated files before starting containers. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
@@ -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'
-45
View File
@@ -1,45 +0,0 @@
---
name: parallel-development
description: Plan and coordinate parallel Heimdall implementation work with Orca workers while preserving architecture, issue tracking, and acceptance evidence.
---
# Parallel development with Orca
Use this workflow for a Heimdall change that can be split into independent investigations or implementation tasks. Read `AGENTS.md`, the focused Gitea issue, the relevant domain skills, and the installed Orca `orchestration` guide first. The Orca CLI guide is also required when creating or managing worktrees. The version-matched instructions come from `orca-ide skills get orchestration` and `orca-ide skills get orca-cli`; follow the resolved executable specified by those guides.
## Find parallel work early
1. Map the requested outcome to the Heimdall boundaries: `Domain`, `Application`, `Infrastructure`, `Web`, and `Agent`. Also identify tests, migrations, documentation, and disposable acceptance work.
2. List concrete work packages with a single owner, bounded files or components, required inputs, and an observable deliverable. Mark each dependency explicitly.
3. Start every ready, independent investigation or implementation promptly. Keep sequential work (shared contract decisions, migration ordering, integration, final acceptance, ticket update, and PR) with the coordinator unless it is itself safely isolated.
4. Split independent, user-visible deliverables into linked Gitea issues before dispatch, following `gitea-ticket-workflow`. Keep one issue for coordinated subtasks that do not ship independently.
Choose the Orca coordination shape that matches the dependency graph:
- For a small set of independent tasks with clear, separate outputs, use the version-matched `worker-start --spec` workflow. Give workers precise scope and tell them to report evidence and blockers.
- For dependent tasks or several waves of work, create an Orca Run and Tasks with explicit dependencies, then start all Tasks reported ready. Recheck readiness after each worker report and start newly unblocked work without waiting for unrelated branches.
- Use a shared current worktree only when workers cannot conflict in files. If edits overlap or cannot be partitioned confidently, assign separate Orca worktrees and integrate their changes deliberately. Do not start concurrent workers that edit the same files.
- Do not parallelize a decision that needs one owner, duplicate the same task across workers, or turn a straightforward isolated change into coordination overhead.
## Heimdall task contracts
Every worker brief must include the user outcome, issue number, exact component/file ownership, architectural constraints, dependencies, acceptance evidence, and what to return. Ask for a concise report with files changed, commands/evidence, remaining risks, and any files or decisions needed from the coordinator. Do not provide credentials, production data, RTSP URLs, raw tokens, or real customer information in a worker prompt.
Workers must preserve these boundaries:
- Domain stays independent of infrastructure; use cases and interfaces belong in Application; adapters and EF Core persistence belong in Infrastructure; HTTP/UI composition belongs in Web; camera/runtime behavior belongs in Agent.
- EF Core and PostgreSQL requirements remain in force. Do not share a `DbContext` across concurrent work. Schema changes include reviewed migrations and relational verification.
- Each worker edits only its assigned scope. When shared contracts must change, have one owner define the contract first, then unblock dependent tasks in the Orca DAG.
- Each independent implementation still follows its focused skill and records results against the Gitea issue. Delegation does not waive authorization, security, CI runner, secret, or review rules.
## Integrate and validate once
1. Coordinate through Orca messages and worker reports, not by polling or steering worker terminals. Follow the version-matched guide's wake, recovery, and completion rules; do not treat silence as proof of completion.
2. Review each returned diff against its assigned scope and the issue criteria. Resolve overlapping changes in the coordinator's integration step; do not accept a report as proof without inspecting the relevant change/evidence.
3. Run shared builds, tests, persistence checks, and disposable Compose acceptance after integrating dependent changes. Avoid making every worker rerun the same full suite; ask each worker for focused evidence, then run the smallest combined checks once at integration.
4. Keep required project-specific acceptance intact. Behavior and deployment changes still use `compose-disposable-recipe`; account bootstrap and Central update changes use their additional focused recipes. Never claim external runner, registry, camera, or storage evidence from a worker's local mock.
5. Update the issue with completed criteria and actual evidence, create/update the PR with `Closes #N` only when every criterion is complete (otherwise `Refs #N`), and record unresolved external validation separately.
## Completion record
The issue or PR should make the coordination auditable without duplicating a long-lived backlog: note the Orca work packages at a high level, which were integrated, the combined checks actually run, and any tasks or acceptance gates still open. Close or settle worker Tasks only when their evidence is received; a reported failure remains open work.
-38
View File
@@ -1,38 +0,0 @@
---
name: penpot-design-sync
description: Open Heimdall's connected Penpot workspace through Orca, authenticate safely, update design source alongside UI work, and verify the saved frames.
---
# Heimdall Penpot design sync
Heimdall's connected Penpot file is part of the UI source of truth. Whenever a change affects a screen, interaction, responsive layout, installer, or visible state, update the corresponding Penpot design in the same change. Do not leave a known implementation/design mismatch for a later task. When a UI change does not affect the design, state why in the Gitea issue evidence.
## Required entry path: Orca browser
1. Read the Orca `orca-cli` and `orca-computer-use` skills when not already loaded. Use the Orca CLI to list/open tabs and inspect browser state; use computer-use only when a visible GUI action is necessary.
2. Open the Penpot site in the Orca browser and sign in there using credentials already present in the environment or Orca-managed account. Never echo, log, paste into issue comments, or otherwise expose credential values. Do not try public Penpot Cloud as a substitute when Heimdall uses its connected self-hosted Penpot instance.
3. Confirm the signed-in team, Heimdall file, and target page before editing. The current Heimdall file is `aadb42b1-1e8d-8014-8008-7dc15de6e3ff`, team `073c6639-4451-8006-8008-e66329727382`. Resolve the current page from the file; do not assume page IDs remain stable.
4. Use Penpot MCP design operations only after Orca has opened the authenticated workspace and the correct file. The browser is the required way to establish and verify the user session, even when MCP is used for precise shape edits.
5. If login, workspace access, or the connected Penpot tool fails, diagnose the actual browser/session path first. Do not claim that the design was updated. Continue independent code work when possible, then report the concrete access blocker and leave the issue open.
## Design update workflow
1. Read `AGENTS.md`, the focused UI skill (for the site Agent installer, `site-agent-installer-ui/SKILL.md`), the UI implementation, and `docs/ui-pages.md`. Review the current Penpot page in Orca before changing it.
2. Compare the shipped behavior with the existing frames. Preserve Heimdall's established visual language and component patterns while representing every meaningful state introduced by the change. Cover loading, success, error/unavailable, permissions, and empty states when they are relevant.
3. For responsive UI, represent desktop and narrow/mobile widths. For installers, show platform and method selection, optional configuration, copyable commands, and unavailable signed-release/image states. Keep fake credentials, real tokens, private URLs, and customer data out of design content.
4. Update the existing relevant frame in place where practical. Rename frames so their platform, viewport, and state are clear. Remove obsolete competing mockups or stale secret-bearing examples when they would mislead implementers; preserve unrelated page content.
5. Match text, labels, command behavior, option availability, selected states, and copy affordances to the implementation and localization. Do not introduce unsupported options simply to imitate another product. Keep `docs/ui-pages.md` consistent when it describes the same UI.
6. Save/commit the design through Penpot, then verify the resulting frames in the Orca browser. Inspect the actual canvas at a useful zoom and check hierarchy, clipping, responsive composition, and stale content. A successful MCP response alone is not visual acceptance.
7. Record the Penpot file/page link, frame names/states changed, and visual review outcome in the linked Gitea issue. Distinguish verified Penpot design work from code tests and real release/deployment evidence.
## Installer design reference
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation from the `latest` image tag, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
## Acceptance evidence
- Orca browser opened the self-hosted Penpot workspace and authenticated session was confirmed without exposing credentials.
- Correct Heimdall file and target page were confirmed before edits.
- Changed frames were inspected visually in the browser after the edit; list their names/states and link the file/page in the Gitea issue.
- Design and shipped UI/docs agree on supported choices, labels, states, and interaction behavior.
- If an external Penpot outage prevents completion, record the exact blocked step in Gitea and do not mark the design acceptance complete.
-32
View File
@@ -1,32 +0,0 @@
---
name: pr-release-versioning
description: Assess whether a Heimdall pull request needs a published release and select its SemVer increment from the change impact without asking the user.
---
# Pull request release assessment
Apply this assessment while preparing every Heimdall PR. Do not ask the user whether to release or which version to use. Record the decision, rationale, and proposed version in the PR description; update it if the diff changes.
## Decide whether a release is needed
- **No release** for documentation, skills, tests, CI-only changes, refactors with no externally observable change, or internal tooling changes. State `Release: no` and keep the current version unchanged.
- **Release required** when the PR changes behavior shipped to Heimdall users or operators, published images/installers/Agent assets, compatibility contracts, or security fixes that users need to receive.
- Do not create a release tag for a PR. A release tag points to a commit on `main`; assess the merged change after required checks pass and then follow the tag workflow in `release-automation`.
## Select the version automatically
Use the latest stable SemVer tag reachable from the integration branch (`MAJOR.MINOR.PATCH`); ignore prerelease tags when selecting the stable base. For multiple merged, unreleased changes, assess all changes since that tag together and use the highest required increment.
- **MAJOR** for a breaking API, configuration, data, or install/upgrade compatibility change.
- **MINOR** for a backward-compatible user-facing capability or operator feature.
- **PATCH** for backward-compatible bug fixes, security fixes, performance fixes, and shipped compatibility corrections.
- No release-worthy changes means no tag and no version increment.
Increment only the selected component and reset lower components to zero. For example, from `1.4.7`: breaking becomes `2.0.0`, a compatible feature becomes `1.5.0`, and a fix becomes `1.4.8`. If no stable tag exists, use `1.0.0` as the base only when the repository's first-release policy confirms that baseline; otherwise report the missing baseline instead of inventing one.
## PR and post-merge steps
- Put a short `Release assessment` section in every PR: `no release (reason)` or `release required; proposed version X.Y.Z (reason)`.
- For no-release PRs, do not create or push a tag. Keep the version unchanged.
- For a release-required PR, determine the exact next version from the current `main` tags after merge, verify it is unused, and create an annotated tag on the merged `main` commit only after required CI succeeds. If another merge changes the base before tagging, recalculate from the latest stable tag and all unreleased changes.
- Never overwrite or move an existing tag. If the change is prerelease-only or an emergency exception, explain the project-specific suffix/tag choice in the PR without asking the user to choose it.
-22
View File
@@ -1,22 +0,0 @@
---
name: release-api-responses
description: Safely consume configured Forgejo release manifests in Heimdall Central.
---
# Release API responses
The Central `UpdatesController` reads a configured Forgejo latest-release endpoint and serves the result to anonymous update checks and authenticated agents. Treat both the JSON document and subsequent release assets as untrusted network input.
## Implementation
- Keep the release endpoint HTTPS-only and preserve its current upstream failure behavior (`null` internally and HTTP 502 at the API boundary).
- Read the release document with a fixed byte limit before deserialization. Check `Content-Length` as an early rejection, but enforce the limit while streaming because the header can be missing or incorrect.
- Catch `JsonException` at the provider parsing boundary. Return unavailable data without logging response bodies; do not convert request cancellation into an ordinary provider failure.
- Keep asset downloads independently bounded and digest-verified. Do not expand this change to provider retries, endpoint configuration, or public response contracts without a separate acceptance requirement.
## Acceptance workflow
1. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` for malformed HTML, invalid JSON, a valid release document, and the response size limit.
2. Run the Web project build with the SDK pinned by `global.json`.
3. Run the disposable Compose procedure in `compose-disposable-recipe` from the exact changed source. Configure a synthetic HTTPS provider endpoint that can return a valid Forgejo document and an HTML 200 response; probe the public update endpoint and verify valid data succeeds while malformed provider data yields the established 502 response.
4. Record the unique Compose project, exact built image tag, sanitized HTTP outcomes, teardown verification for containers/volumes/networks, and tag absence in the linked Gitea issue. Never use production provider configuration or credentials.
+11 -30
View File
@@ -1,41 +1,22 @@
---
name: release-automation
description: Build and validate changed Heimdall images on pushes, then publish versioned Docker Hub images and signed installer assets for semver tags.
description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests.
---
# Heimdall build and release workflow
# Heimdall tagged release workflow
For every PR, follow [pull request release assessment](../pr-release-versioning/SKILL.md). Determine and record whether a release is needed and the proposed SemVer from the change impact; do not ask the user to decide. Documentation and skills-only changes do not create a release or change the version. Only tag a release after the merged commit is on `main` and required checks pass.
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.
For any local release investigation that needs credentials, follow [Infisical secrets](../infisical-secrets/SKILL.md). Keep publication credentials in Gitea Actions as specified below; do not assume that a key in Infisical is available to CI.
## Release invariants
Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_scope.py`, image build/push scripts, installer packages, release signing, or the Gitea release job.
## Delivery contract
- Pull requests run `verify` and build/scan only images affected by the changed project graph. They never receive Docker Hub or Gitea publication credentials.
- `test-plan.py` computes both affected test suites and build targets from transitive `ProjectReference` edges. PRs build only those test projects and any changed source projects not covered by them; the solution is built only for main/tag runs or broad CI/build-configuration changes. The solution restore remains locked and solution-wide for the dependency security report.
- A push to `main` validates the changed source and builds/scans/pushes only affected images. The affected image gets immutable `sha-<full-sha>` and mutable `latest` tags on Docker Hub. Main pushes do not create Gitea releases.
- Runs for the same ref are serialized so a slower older `main` run cannot overwrite a newer `latest` image.
- A `MAJOR.MINOR.PATCH` tag (optional prerelease suffix allowed) is a version release. It validates the complete source and builds/scans server, Agent CPU, and Agent GPU images once each. The verified images are pushed to Docker Hub as `sha-<full-sha>` and the application version.
- After merge of a release-worthy PR, use the current stable tag and all unreleased changes to calculate the SemVer increment according to `pr-release-versioning`. Fetch `main`, verify the merged commit is reachable from it, verify the selected tag is unused, create an annotated tag at the merged commit, and push it to trigger this workflow. Never ask the user to choose a version or release, infer a version from the PR title alone, or force-update an existing tag. Documentation and skills-only changes do not get a tag.
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, its `heimdall-installers-<version>.zip.sha256` sidecar, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and unrelated checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. The package job writes a checksum sidecar with the archive's exact asset filename. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), uses a valid Gitea SHA-256 asset digest when present and otherwise downloads and parses the published sidecar, then verifies the ZIP before running its version-pinned script. A malformed non-null Gitea digest is a hard failure; it must not be silently replaced by the sidecar. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
- Central stores only the public Forgejo origin in `updates.forgepublicurl` and constructs the canonical Heimdall `releases/latest` API route in code. Preserve the legacy setting migration and never make the derived API route editable in Settings.
- The Site Install panel displays the configured signed release version and only exposes native install commands when the signed manifest, key, and platform assets are available. Docker commands also require a verified image digest.
- Required publication secrets are `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, and `RELEASE_SIGNING_KEY_B64`; `RELEASE_SERVER_URL` must match the HTTPS origin in `BUILD_SERVER_URL`. Do not create or use a long-lived `RELEASE_TOKEN` PAT. The tag-only `publish` job gets Gitea's built-in `GITEA_TOKEN`, scoped to `contents: write` and `pull-requests: read`; PR jobs retain read-only contents access and never receive publication credentials.
- For the first signed release, when no Agent or signed manifest has been distributed, create one ECDSA P-256 key pair and save only the base64-encoded private PEM as the repository Actions secret `RELEASE_SIGNING_KEY_B64`. Keep an offline backup in an approved secret vault. The release publishes the derived public key, which becomes the trust root for new Agents; never rotate it after adoption without following the documented key-rotation procedure. Set `RELEASE_SERVER_URL` as an Actions variable to the exact HTTPS origin.
## Image change scope
`scripts/ci/change_scope.py` maps changed paths to the exact Docker build graphs. Shared build configuration and shared Domain/Application/Contracts projects affect both Central and Agent. Web/Infrastructure/installer assets affect Central; Agent and mDNS projects plus the model affect Agent CPU and GPU; each Dockerfile affects only its own image. Keep this map aligned with the `COPY` instructions and project references in the Dockerfiles. A version tag deliberately selects every image.
- 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. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP and its published checksum sidecar, installer bootstrap with both a valid API digest and `digest: null`, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
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.
For build-scope changes, validate that documentation-only, Central-only, Agent-only, and shared-project file sets produce the intended image outputs. For behavior/deployment changes, also run the required disposable source-built Compose recipe with generated credentials, ports, project name, and unique local image tags. Its EXIT trap must verify project containers, volumes, and networks are gone and remove/verify absence of only its exact image tags.
These simulations do not prove Actions permissions, signing secret availability, runner network, Docker Hub/Gitea publication, Central production configuration, or native Agent hardware/OS behavior. Record actual remote evidence in the focused Gitea issue; do not mark it complete based on offline simulation.
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.
+2 -3
View File
@@ -7,11 +7,10 @@ description: Diagnose and maintain Renovate dependency updates through Gitea Act
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `FORGEJO_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files. Forgejo reserves variable names beginning with `GITEA_` and rejects them.
- The endpoint must be the HTTPS Forgejo API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- 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.
- Run `bash skills/renovate-automation/acceptance.sh` after changing the preflight or its endpoint wiring. It exercises valid and rejected synthetic credentials over an isolated HTTPS mock in Compose; the test container trusts only the generated self-signed certificate for its local fixture.
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
- For operational changes, update the Renovate Gitea issue with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
-95
View File
@@ -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
-25
View File
@@ -1,25 +0,0 @@
---
name: site-agent-installer-ui
description: Maintain and accept the Heimdall site Agent installer panel using Pangolin's platform/method/configuration/commands interaction pattern.
---
# Site Agent installer UI
Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.razor`. Its interaction model follows Pangolin's `OptionSelect` and `CopyTextBox`: platform tiles, platform-specific method tiles, optional configuration, then titled command blocks with an inline copy control. Keep `docs/ui-pages.md` and the connected Penpot installer frames aligned with the shipped flow; cover desktop and narrow/mobile widths plus the signed-release-unavailable state. Always open Penpot and authenticate through the Orca browser before editing the design; follow [penpot-design-sync/SKILL.md](../penpot-design-sync/SKILL.md) for the full workflow and evidence requirements.
## Project-specific rules
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, but install the corresponding published `:latest` image. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
- For live installer verification, use the authenticated Orca browser session. Check for the dedicated Heimdall login only in the user secret store at `~/.config/heimdall/credentials.json`; never put account passwords in this skill, repository config, shell arguments, or Orca `fill` commands. The file fallback is owner-only (`0700` directory, `0600` file) and base64-encoded, not encrypted. If it is absent, provide the user-run masked helper `~/.local/bin/store-heimdall-credentials`; do not report the credentials as persisted until that helper succeeds. If Orca has no safe autofill path, ask the user to enter the password in the visible browser.
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
- Match Pangolin's control hierarchy and compact copy affordance while using Heimdall's MudBlazor theme and supported installation choices. Keep selection and copy feedback accessible with selected styling, tooltips/aria labels, and a check icon after copying.
## Acceptance workflow
1. Run the focused component suite: `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SiteDetailTests`.
2. Inspect rendered coverage for each platform and method, including the release-unavailable state and Docker image-unavailable state. Verify localization resources parse and `git diff --check` is clean.
3. For UI or install behavior changes, follow `compose-disposable-recipe/SKILL.md`: build from the changed source in an isolated Compose project, record exact generated image tags, then tear down only that project and verify its containers, volumes, network, and exact image tags are absent. Keep shared base images.
4. Update the linked Gitea issue with the observed results; distinguish component/local Compose evidence from real release, registry, or host installation evidence.
-32
View File
@@ -1,32 +0,0 @@
---
name: site-camera-credentials
description: Maintain the per-site camera credential API and its Site Detail and Cameras page flows.
---
# Site camera credentials
The Web client calls `api/sites/{id}/credentials` from both `SiteDetail.razor`
and `CamerasPage.razor`. Keep the GET, POST, and DELETE endpoints in
`SitesController` aligned with those client paths. Apply the existing
`Site.Read` or `Site.Write` policy and the global site resource-access filter
to every credential route.
Credential passwords are write-only. `SiteCredentialResponse` contains only
the credential ID, site ID, label, username, and timestamps; never return,
render, or log the stored password. Use the Application handlers and EF Core
through the existing application context for persistence.
## Change and acceptance workflow
1. Verify the client path and controller route agree for all three methods.
2. Test a site with no credentials and a site with a credential in both
`/sites/{id}` and `/sites/{id}/cameras`; distinguish a failed request from
a normal empty list.
3. Exercise add/list/delete with synthetic credentials. Assert the response
and list never contain the submitted password.
4. Verify unauthenticated requests are rejected and users without access to
the site receive a forbidden response.
5. Run focused Web and PostgreSQL integration tests, then follow
`compose-disposable-recipe` with an isolated Central/PostgreSQL project.
Record exact project resources and local image tags, and verify their
removal after teardown.
-17
View File
@@ -1,17 +0,0 @@
---
name: site-create-permission
description: Keep the Sites page site-creation controls aligned with Heimdall's Site.Write permission.
---
# Site creation permission in the Sites page
`AuthState` resolves role permissions into `Permissions`; check creation with `Auth.HasPermission("Site.Write")` in `SitesPage.razor`. Render both the create affordance and its overlay/dialog only when that permission exists, and route the button through a guarded open method so an event cannot set the dialog visible after access changes.
The API remains the enforcement boundary. Do not remove or weaken its `Site.Write` authorization policy as part of this UI behavior.
## Acceptance workflow
1. Add a focused bUnit test using `PageTestBase.LoginAs("Viewer")`; assert the create button and dialog fields/actions are absent after page load.
2. Keep an authorized creation test using an authorized role; exercise opening the dialog and completing a successful create response.
3. Run the focused test with `dotnet test tests/Heimdall.Web.Tests --filter FullyQualifiedName~SitesPageTests`.
4. For behavior acceptance, run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, record its isolated project/tag and cleanup evidence on the Gitea issue. UI component tests do not prove API authorization or field deployment behavior.
@@ -1,16 +0,0 @@
---
name: snapshot-gallery-responsive-filters
description: Keep the Heimdall snapshot gallery's search, event type, and load controls usable on phone widths while preserving the desktop row.
---
# Snapshot gallery responsive filters
The snapshot filter controls are owned by `src/Heimdall.Web/Components/Pages/SnapshotsPage.razor`. Keep them together in `.snapshot-filters`: its desktop grid uses three columns for search, event type, and load, and its 600 px breakpoint stacks those controls. Use `minmax(0, ...)` tracks and controls without fixed minimum widths so the page can shrink to a 320 px viewport.
## Acceptance workflow
1. Read Gitea issue [#285](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/285) and retain its criteria for 390 px, narrower phone widths, and desktop.
2. Update the `SnapshotsPageTests` bUnit coverage to check that search, event type, and load remain inside the filter layout and that the desktop and phone grid rules remain present without the old 300 px/180 px minimums.
3. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SnapshotsPageTests`.
4. For behavior changes, follow `skills/compose-disposable-recipe/SKILL.md` and record the disposable acceptance result, cleanup verification, and any browser viewport evidence on issue #285. A bUnit structure/CSS assertion does not by itself measure rendered document width; use a browser at 390 px and 320 px when available.
5. Keep issue #285 open until its desktop, 390 px, narrow-screen, and operational acceptance evidence is complete.
-17
View File
@@ -1,17 +0,0 @@
---
name: ui-unknown-route
description: Diagnose and verify unknown-route rendering in Heimdall's interactive Blazor UI.
---
# Unknown UI routes
Heimdall renders its root `Routes` component in an interactive server circuit with prerendering disabled (`Components/App.razor`). In .NET 10, configure `Router.NotFoundPage`; the legacy `<NotFound>` fragment is not supported by Blazor Web Apps. Unknown direct browser requests have no matched endpoint and cannot start the circuit, so `Program` must render a small static HTML 404 using the same `NotFoundPage_*` resources and `/dashboard` link. Skip API, hub, health, Hangfire, non-HTML, and file-like requests so their 404 responses keep their native format.
The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component.
## Acceptance workflow
1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response.
2. Verify client-side navigation from a known route to an unknown URL (for example `Blazor.navigateTo(...)`) and confirm the same page renders.
3. Confirm `/not-found` and a known route still render. Verify API 404 responses remain API responses and do not receive the UI document, even when the request accepts HTML.
4. Run the focused Playwright E2E tests and the disposable Central + PostgreSQL Compose acceptance from `compose-disposable-recipe`. Use generated credentials, unique project/port/volume/image names, probe the route through a browser after the health check, and verify cleanup of project resources and every exact local image tag.
@@ -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; } = [];
@@ -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)
@@ -82,10 +82,6 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
}
var refreshedUser = await _userManager.FindByIdAsync(user.Id, ct).ConfigureAwait(false);
if (refreshedUser is null)
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
user = refreshedUser;
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
}
@@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
var oldStatus = camera.Status;
var newStatus = camera.Status == CameraStatus.Disabled
? CameraStatus.Offline
? CameraStatus.Online
: CameraStatus.Disabled;
camera.SetStatus(newStatus);
@@ -44,5 +44,5 @@ public interface ICameraAccessService
/// Filters an <see cref="IQueryable{Camera}"/> to only cameras the user can access.
/// Admins see all cameras. Non-admins are filtered by UserCamera/UserSite.
/// </summary>
Task<IQueryable<Camera>> ApplyCameraFilterAsync(IQueryable<Camera> query, Guid userId, CancellationToken ct = default);
IQueryable<Camera> ApplyCameraFilter(IQueryable<Camera> query, Guid userId);
}
@@ -11,16 +11,7 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
{
builder.ToTable("UserCameraAccesses");
builder.HasKey(eca => eca.Id);
// A site-wide grant has a null CameraId, so it cannot participate in
// a primary key. Keep duplicate protection with two partial indexes.
builder.HasIndex(eca => new { eca.UserId, eca.SiteId })
.IsUnique()
.HasFilter("\"CameraId\" IS NULL");
builder.HasIndex(eca => new { eca.UserId, eca.SiteId, eca.CameraId })
.IsUnique()
.HasFilter("\"CameraId\" IS NOT NULL");
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
builder.HasOne<IdentityAppUser>()
.WithMany()
File diff suppressed because it is too large. Load diff
@@ -1,79 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AllowSiteWideCameraAccess : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses");
migrationBuilder.AlterColumn<Guid>(
name: "CameraId",
table: "UserCameraAccesses",
type: "uuid",
nullable: true,
oldClrType: typeof(Guid),
oldType: "uuid");
migrationBuilder.AddPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_UserId_SiteId",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId" },
unique: true,
filter: "\"CameraId\" IS NULL");
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId", "CameraId" },
unique: true,
filter: "\"CameraId\" IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses");
migrationBuilder.DropIndex(
name: "IX_UserCameraAccesses_UserId_SiteId",
table: "UserCameraAccesses");
migrationBuilder.DropIndex(
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
table: "UserCameraAccesses");
// Downgrade cannot preserve site-wide grants in the old schema.
// Setting NOT NULL without a default deliberately fails while any
// such grants exist; export/remove them before rolling back.
migrationBuilder.AlterColumn<Guid>(
name: "CameraId",
table: "UserCameraAccesses",
type: "uuid",
nullable: false,
oldClrType: typeof(Guid),
oldType: "uuid",
oldNullable: true);
migrationBuilder.AddPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId", "CameraId" });
}
}
}
@@ -2018,39 +2018,30 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid?>("CameraId")
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("SiteId")
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasKey("UserId", "SiteId", "CameraId");
b.HasIndex("CameraId");
b.HasIndex("SiteId");
b.HasIndex("UserId", "SiteId")
.IsUnique()
.HasFilter("\"CameraId\" IS NULL");
b.HasIndex("UserId", "SiteId", "CameraId")
.IsUnique()
.HasFilter("\"CameraId\" IS NOT NULL");
b.ToTable("UserCameraAccesses", (string)null);
});
@@ -45,10 +45,9 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
using var scope = _serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var cancellationToken = Context.RequestAborted;
var apiKeyEntity = await db.ApiKeys
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled, cancellationToken);
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled);
if (apiKeyEntity is null)
return AuthenticateResult.Fail("Invalid API key");
@@ -68,22 +67,13 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
// by the full verified hash, and reject ambiguous or stale bindings.
var agents = await db.Agents.AsNoTracking()
.Where(a => a.ApiKeyHash == apiKeyEntity.KeyHash && a.SiteId == apiKeyEntity.SiteId)
.Select(a => a.Id).Take(2).ToListAsync(cancellationToken);
.Select(a => a.Id).Take(2).ToListAsync(Context.RequestAborted);
if (agents.Count != 1 || !apiKeyEntity.SiteId.HasValue)
return AuthenticateResult.Fail("API key is not bound to one active agent");
// LastUsedAt is an administrative activity indicator, not an audit log.
// Updating it on every request creates avoidable writes and contention
// when an agent sends concurrent heartbeats and telemetry. The predicate
// and update execute atomically in PostgreSQL, so concurrent requests
// collapse to at most one write per key per minute.
var now = DateTime.UtcNow;
var updateBefore = now.AddMinutes(-1);
await db.ApiKeys
.Where(key => key.Id == apiKeyEntity.Id &&
(key.LastUsedAt == null || key.LastUsedAt <= updateBefore))
.ExecuteUpdateAsync(setters => setters.SetProperty(key => key.LastUsedAt, now), cancellationToken)
.ConfigureAwait(false);
apiKeyEntity.MarkUsed();
// Persist LastUsedAt update
await db.SaveChangesAsync();
var claims = new List<Claim>
{
@@ -10,10 +10,10 @@ namespace Heimdall.Infrastructure.Services;
public class CameraAccessService(IApplicationDbContext context, IIdentityPersistenceContext identity) : ICameraAccessService
{
public async Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default)
=> await (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).AnyAsync(c => c.Id == cameraId, ct);
=> await ApplyCameraFilter(context.Cameras, userId).AnyAsync(c => c.Id == cameraId, ct);
public async Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
=> await (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).Select(c => c.Id).ToListAsync(ct);
public Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
=> ApplyCameraFilter(context.Cameras, userId).Select(c => c.Id).ToListAsync(ct);
public async Task<List<Guid>> GetUserIdsWithCameraAccessAsync(Guid cameraId, CancellationToken ct = default)
{
@@ -41,23 +41,23 @@ public class CameraAccessService(IApplicationDbContext context, IIdentityPersist
.ConfigureAwait(false);
}
public async Task<List<Guid>> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default)
=> await (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).Where(c => c.SiteId == siteId).Select(c => c.Id).ToListAsync(ct);
public Task<List<Guid>> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default)
=> ApplyCameraFilter(context.Cameras, userId).Where(c => c.SiteId == siteId).Select(c => c.Id).ToListAsync(ct);
public async Task<List<Guid>> GetAccessibleSiteIdsAsync(Guid userId, CancellationToken ct = default)
{
if (await IsAdminAsync(userId, ct)) return await context.Sites.Select(s => s.Id).ToListAsync(ct);
var cameraSites = (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).Select(c => c.SiteId);
if (IsAdmin(userId)) return await context.Sites.Select(s => s.Id).ToListAsync(ct);
var cameraSites = ApplyCameraFilter(context.Cameras, userId).Select(c => c.SiteId);
return await context.Sites.Where(s => cameraSites.Contains(s.Id) ||
context.UserSites.Any(us => us.UserId == userId && us.SiteId == s.Id) ||
context.UserCameraAccesses.Any(a => a.UserId == userId && a.SiteId == s.Id && a.CameraId == null))
.Select(s => s.Id).ToListAsync(ct);
}
public async Task<IQueryable<Camera>> ApplyCameraFilterAsync(IQueryable<Camera> query, Guid userId, CancellationToken ct = default)
public IQueryable<Camera> ApplyCameraFilter(IQueryable<Camera> query, Guid userId)
{
if (userId == Guid.Empty) return query.Where(c => false);
if (await IsAdminAsync(userId, ct)) return query;
if (IsAdmin(userId)) return query;
return query.Where(c =>
context.UserCameraAccesses.Any(a => a.UserId == userId && a.SiteId == c.SiteId &&
(a.CameraId == null || a.CameraId == c.Id)) ||
@@ -68,8 +68,6 @@ public class CameraAccessService(IApplicationDbContext context, IIdentityPersist
context.UserGroups.Any(m => m.UserId == userId && m.GroupId == a.GroupId)));
}
private Task<bool> IsAdminAsync(Guid userId, CancellationToken ct) => userId != Guid.Empty
? identity.UserRoles.AnyAsync(ur => ur.UserId == userId &&
identity.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin), ct)
: Task.FromResult(false);
private bool IsAdmin(Guid userId) => userId != Guid.Empty && identity.UserRoles.Any(ur =>
ur.UserId == userId && identity.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
}
+1 -5
View File
@@ -10,8 +10,4 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.Agent.Tests" />
</ItemGroup>
</Project>
</Project>
+37 -63
View File
@@ -52,46 +52,44 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
// Try to receive within timeout
using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
receiveCts.CancelAfter(options.Timeout);
var receiveTask = udpClient.ReceiveAsync(receiveCts.Token).AsTask();
try
var receiveTask = udpClient.ReceiveAsync(ct).AsTask();
var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false);
if (completedTask != receiveTask)
{
var result = await receiveTask.ConfigureAwait(false);
var response = MdnsResponse.Parse(result.Buffer);
if (retry < options.MaxRetries)
continue; // retry
break; // timeout, try next service type
}
if (response is not null)
var result = await receiveTask.ConfigureAwait(false);
var response = MdnsResponse.Parse(result.Buffer);
if (response is not null)
{
// If it's a HomeKit device, parse HomeKit-specific info
if (response.Type == MdnsConstants.TypePtr &&
response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
{
// If it's a HomeKit device, parse HomeKit-specific info
if (response.Type == MdnsConstants.TypePtr &&
response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
{
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address,
HomeKitInfo = ParseHomeKitInfo(target, response)
};
}
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address
ResolvedAddress = response.Address,
HomeKitInfo = ParseHomeKitInfo(target, response)
};
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
if (retry < options.MaxRetries)
continue; // timeout, retry
break; // timeout, try next service type
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address
};
}
}
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
@@ -169,29 +167,17 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
{
using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var remaining = listenUntil - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
break;
receiveCts.CancelAfter(remaining);
var receiveTask = udp.ReceiveAsync(receiveCts.Token).AsTask();
try
{
var result = await receiveTask.ConfigureAwait(false);
var replies = ParsePacket(result.Buffer);
var receiveTask = udp.ReceiveAsync(ct).AsTask();
var completed = await Task.WhenAny(receiveTask, Task.Delay(options.ListenWindow, ct)).ConfigureAwait(false);
if (replies.Count > 0)
collected.AddRange(replies);
}
catch (SocketException ex)
{
_logger.LogWarning("mDNS multicast receive failed (error type {ErrorType})", ex.GetType().Name);
break;
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
break; // listen window elapsed; receive cancellation is observed here
}
if (completed != receiveTask)
break; // no more replies expected
var result = await receiveTask.ConfigureAwait(false);
var replies = ParsePacket(result.Buffer);
if (replies.Count > 0)
collected.AddRange(replies);
}
// Build devices from collected replies
@@ -215,18 +201,6 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
}
}
internal static async Task ObserveCanceledReceiveAsync(Task<UdpReceiveResult> receiveTask, CancellationToken operationToken)
{
try
{
await receiveTask.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!operationToken.IsCancellationRequested)
{
// The receive was canceled because its individual timeout elapsed.
}
}
// ─── DNS packet parsing (with compression pointers) ──────────────
private sealed record MdnsReply(
@@ -59,10 +59,6 @@
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never"
Breakpoint="Breakpoint.Sm" MiniVariantWidth="64px" @bind-MiniVariant="_miniVariant">
<MudNavMenu>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="px-4 py-2" data-testid="server-version">
Version @(_serverVersion ?? "—")
</MudText>
<MudDivider />
@if (Auth.IsLoggedIn)
{
<MudText Typo="Typo.overline" Color="Color.Secondary" Class="px-4 py-2">@Text["Navigation"]</MudText>
@@ -144,7 +140,6 @@
private bool _miniVariant;
private bool _darkMode = true;
private string _searchQuery = "";
private string? _serverVersion;
/// <summary>Sous-menu « Gestion des utilisateurs » : replié par défaut,
/// déplié automatiquement quand on est déjà sur une de ses pages.</summary>
@@ -161,13 +156,6 @@
protected override async Task OnInitializedAsync()
{
try
{
var version = await Api.GetServerVersionAsync();
_serverVersion = version?.Version;
}
catch { /* Keep the navigation usable while version metadata is unavailable. */ }
if (!Auth.IsLoggedIn) return;
try
{
@@ -902,17 +902,10 @@ else
_ = LoadUpdateInfoAsync();
}
}
catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex))
{
// Le filtre d'accès renvoie 403 pour masquer un agent absent ou non accessible.
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _loading = false; }
}
private static bool IsMissingOrHiddenResource(HttpRequestException exception) =>
exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden;
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
private async Task LoadMetricHistoryAsync(string range)
@@ -98,10 +98,10 @@
</MudSelect>
</MudItem>
<MudItem xs="12" md="6">
<MudSelect T="Guid?" @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
<MudSelect @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
@foreach (var site in _availableSites)
{
<MudSelectItem T="Guid?" Value="@((Guid?)site.Id)">@site.Name</MudSelectItem>
<MudSelectItem Value="@site.Id">@site.Name</MudSelectItem>
}
</MudSelect>
</MudItem>
@@ -109,10 +109,10 @@
@if (_newAccessType == AccessType.CameraSpecific)
{
<MudSelect T="Guid?" @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
<MudSelect @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
@foreach (var camera in _availableCameras)
{
<MudSelectItem T="Guid?" Value="@((Guid?)camera.Id)">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
<MudSelectItem Value="@camera.Id">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
}
</MudSelect>
}
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more