Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcc719d627 | ||
|
|
bc7ddccfe3 | ||
|
|
6e7f593cb3 | ||
|
|
622abb4454 | ||
|
|
9162e374f0 | ||
|
|
02783dd718 | ||
|
|
24a2400610 | ||
|
|
374b7f267f | ||
|
|
ace7746695 | ||
|
|
5b1255ad80 | ||
|
|
1d60f04691 | ||
|
|
e042b832d8 | ||
|
|
adf8d73476 | ||
|
|
b3d5ea5add | ||
|
|
2d28771945 | ||
|
|
4c790e0489 | ||
|
|
43e6752a31 | ||
|
|
38647d3623 | ||
|
|
5bcd4968a8 | ||
|
|
86d77dc462 | ||
|
|
188a9ad2d4 | ||
|
|
cae09e3698 | ||
|
|
1b512ab040 | ||
|
|
7869800ea5 | ||
|
|
62261f914e | ||
|
|
4498e39d34 | ||
|
|
938adbf3a8 |
No files matched your search
@@ -6,7 +6,7 @@ Refs #
|
||||
|
||||
## Vérification
|
||||
|
||||
<!-- Liens des runs Gitea, suites exécutées, résultats et item actualisé dans todo.md. -->
|
||||
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
|
||||
|
||||
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
|
||||
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
|
||||
@@ -19,6 +19,7 @@ Refs #
|
||||
|
||||
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
|
||||
- [ ] Revue des changements de contrats/migrations/configuration
|
||||
- [ ] Si tag : publication des images et release brouillon vérifiées
|
||||
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
|
||||
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
|
||||
|
||||
SonarQube, matériel et autres contrôles externes ne sont considérés validés que si une preuve réelle est jointe. Une protection de branche doit exiger le contexte Gitea constaté sur le run avant de compter sur le blocage d’un merge.
|
||||
+65
-112
@@ -3,24 +3,12 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'tests/**'
|
||||
- 'Heimdall.slnx'
|
||||
- 'global.json'
|
||||
- 'Directory.Build.*'
|
||||
- 'GitVersion*.yml'
|
||||
- '.dockerignore'
|
||||
- '.env.example'
|
||||
- '.gitea/workflows/**'
|
||||
- 'scripts/ci/**'
|
||||
- 'docker/**'
|
||||
- 'install/**'
|
||||
- 'models/**'
|
||||
- 'Makefile'
|
||||
tags: ['*.*.*']
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: heimdall-${{ gitea.ref }}
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
@@ -30,52 +18,28 @@ jobs:
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
outputs:
|
||||
run_validation: ${{ steps.filter.outputs.run_validation }}
|
||||
build_server: ${{ steps.filter.outputs.build_server }}
|
||||
build_agent: ${{ steps.filter.outputs.build_agent }}
|
||||
build_agent_gpu: ${{ steps.filter.outputs.build_agent_gpu }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Detect changes that need validation
|
||||
- name: Detect changed projects and images
|
||||
id: filter
|
||||
env:
|
||||
PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ gitea.event.before }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
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"
|
||||
REF: ${{ gitea.ref }}
|
||||
run: python3 scripts/ci/change_scope.py
|
||||
policy:
|
||||
name: CI policy
|
||||
if: always()
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image, dockerhub_latest, publish]
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image, publish]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
steps:
|
||||
- name: Require all applicable validation jobs to pass
|
||||
@@ -86,7 +50,6 @@ jobs:
|
||||
SERVER_IMAGE_RESULT: ${{ needs.server_image.result }}
|
||||
AGENT_IMAGE_RESULT: ${{ needs.agent_image.result }}
|
||||
AGENT_GPU_IMAGE_RESULT: ${{ needs.agent_gpu_image.result }}
|
||||
DOCKERHUB_RESULT: ${{ needs.dockerhub_latest.result }}
|
||||
RELEASE_RESULT: ${{ needs.publish.result }}
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
REF: ${{ gitea.ref }}
|
||||
@@ -100,21 +63,11 @@ jobs:
|
||||
fi
|
||||
|
||||
test "$VERIFY_RESULT" = success
|
||||
if [ "${{ needs.changes.outputs.build_server }}" = true ]; then test "$SERVER_IMAGE_RESULT" = success; fi
|
||||
if [ "${{ needs.changes.outputs.build_agent }}" = true ]; then test "$AGENT_IMAGE_RESULT" = success; fi
|
||||
if [ "${{ needs.changes.outputs.build_agent_gpu }}" = true ]; then test "$AGENT_GPU_IMAGE_RESULT" = success; fi
|
||||
case "$EVENT_NAME:$REF" in
|
||||
pull_request:*)
|
||||
test "$SERVER_IMAGE_RESULT" = success
|
||||
test "$AGENT_IMAGE_RESULT" = success
|
||||
test "$AGENT_GPU_IMAGE_RESULT" = success
|
||||
;;
|
||||
push:refs/heads/main)
|
||||
test "$SERVER_IMAGE_RESULT" = success
|
||||
test "$AGENT_IMAGE_RESULT" = success
|
||||
test "$AGENT_GPU_IMAGE_RESULT" = success
|
||||
test "$DOCKERHUB_RESULT" = success
|
||||
;;
|
||||
push:refs/tags/v*)
|
||||
test "$RELEASE_RESULT" = success
|
||||
;;
|
||||
push:refs/tags/*) test "$RELEASE_RESULT" = success ;;
|
||||
esac
|
||||
verify:
|
||||
name: Build and tests
|
||||
@@ -168,15 +121,16 @@ jobs:
|
||||
run: |
|
||||
python3 -m unittest discover -s scripts/ci -p 'test_*.py'
|
||||
python3 scripts/ci/check-efcore-usage.py
|
||||
- name: Validate Compose and build .NET solution
|
||||
- name: Validate Compose and restore .NET solution
|
||||
run: |
|
||||
mkdir -p artifacts/tests artifacts/security
|
||||
dotnet --info > artifacts/dotnet-info.txt
|
||||
bash scripts/ci/validate-compose.sh
|
||||
dotnet restore Heimdall.slnx --locked-mode
|
||||
dotnet build Heimdall.slnx -c Release --no-restore -m:2
|
||||
- name: Plan affected test suites
|
||||
run: python3 scripts/ci/test-plan.py
|
||||
- name: Build affected projects
|
||||
run: python3 scripts/ci/build-plan.py
|
||||
- name: Agent tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Agent.Tests
|
||||
- name: API tests
|
||||
@@ -195,8 +149,6 @@ jobs:
|
||||
run: python3 scripts/ci/check-camera-access-coverage.py artifacts/tests artifacts/tests/plan.json
|
||||
- name: Browser tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.E2E.Tests
|
||||
- name: Publish server PWA and agent archives
|
||||
run: bash scripts/ci/package.sh
|
||||
- name: NuGet dependency security gate
|
||||
run: bash scripts/ci/security.sh dependencies --no-restore
|
||||
- name: Reclaim build storage after job
|
||||
@@ -207,7 +159,7 @@ jobs:
|
||||
fi
|
||||
server_image:
|
||||
name: Build and scan server image
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_server == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
@@ -232,14 +184,17 @@ jobs:
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build server image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh server
|
||||
- name: Scan server image
|
||||
run: bash scripts/ci/security.sh server
|
||||
- name: Push immutable server image to Docker Hub
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh server
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
@@ -249,7 +204,7 @@ jobs:
|
||||
fi
|
||||
agent_image:
|
||||
name: Build and scan agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
@@ -274,14 +229,17 @@ jobs:
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build agent image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh agent
|
||||
- name: Scan agent image
|
||||
run: bash scripts/ci/security.sh agent
|
||||
- name: Push immutable agent image to Docker Hub
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh agent
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
@@ -291,7 +249,7 @@ jobs:
|
||||
fi
|
||||
agent_gpu_image:
|
||||
name: Build and scan NVIDIA Agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent_gpu == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
@@ -316,44 +274,18 @@ jobs:
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build NVIDIA Agent image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh agent-gpu
|
||||
- name: Scan NVIDIA Agent image
|
||||
run: bash scripts/ci/security.sh agent-gpu
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
dockerhub_latest:
|
||||
name: Publish Docker Hub latest tags
|
||||
if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main'
|
||||
needs: [changes, server_image, agent_image]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Docker prerequisites
|
||||
run: bash scripts/ci/bootstrap.sh
|
||||
- name: Move latest tags after both image scans pass
|
||||
- name: Push immutable NVIDIA Agent image to Docker Hub
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
run: bash scripts/ci/push-images.sh latest
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh agent-gpu
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
@@ -361,14 +293,15 @@ jobs:
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
publish:
|
||||
name: Publish versioned release
|
||||
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/v')
|
||||
needs: [changes, verify]
|
||||
name: Publish versioned installer release
|
||||
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/')
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
permissions:
|
||||
contents: read
|
||||
contents: write
|
||||
pull-requests: read
|
||||
actions: read
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
@@ -387,22 +320,42 @@ jobs:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- run: bash scripts/ci/bootstrap.sh
|
||||
- name: Require a release from main history
|
||||
run: git merge-base --is-ancestor HEAD origin/main
|
||||
- name: Rebuild release archives from verified commit
|
||||
- name: Build versioned installer and Agent archives
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_RUN_ID: ${{ gitea.run_id }}
|
||||
run: bash scripts/ci/package.sh
|
||||
- name: Publish immutable images and draft release
|
||||
- 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
|
||||
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.RELEASE_TOKEN }}
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_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
|
||||
@@ -11,6 +11,8 @@
|
||||
- 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).
|
||||
@@ -12,12 +12,19 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-rest
|
||||
|
||||
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 ffmpeg wget libgomp1 tzdata \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
&& 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/*
|
||||
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/ ./
|
||||
|
||||
@@ -13,6 +13,8 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003be
|
||||
|
||||
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 \
|
||||
@@ -24,8 +26,13 @@ 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 ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
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/* \
|
||||
&& 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/ ./
|
||||
|
||||
@@ -10,6 +10,8 @@ services:
|
||||
dockerfile: docker/Dockerfile.agent.gpu
|
||||
environment:
|
||||
Agent__InferenceExecutionProvider: CUDA
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
|
||||
@@ -7,6 +7,8 @@ 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
|
||||
@@ -19,6 +21,7 @@ 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
|
||||
|
||||
@@ -3,16 +3,24 @@ services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
pull_policy: always
|
||||
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
|
||||
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:
|
||||
- >-
|
||||
exec turnserver -n --use-auth-secret
|
||||
--static-auth-secret="$$(cat /run/secrets/coturn_secret)"
|
||||
--realm=${COTURN_REALM:-heimdall.local}
|
||||
--fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout
|
||||
--no-cli --listening-port=3478
|
||||
--min-port=${COTURN_RELAY_PORT_MIN:-49160}
|
||||
--max-port=${COTURN_RELAY_PORT_MAX:-49200}
|
||||
secrets:
|
||||
- coturn_secret
|
||||
restart: unless-stopped
|
||||
|
||||
secrets:
|
||||
coturn_secret:
|
||||
file: ./secrets/coturn_secret
|
||||
file: ./optional/secrets/coturn_secret
|
||||
@@ -30,9 +30,9 @@ volumes:
|
||||
|
||||
secrets:
|
||||
rustfs_access_key:
|
||||
file: ./secrets/rustfs_access_key
|
||||
file: ./optional/secrets/rustfs_access_key
|
||||
rustfs_secret_key:
|
||||
file: ./secrets/rustfs_secret_key
|
||||
file: ./optional/secrets/rustfs_secret_key
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
|
||||
@@ -12,11 +12,15 @@ 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 `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.
|
||||
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.
|
||||
|
||||
Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release.
|
||||
|
||||
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent ces références et leur SHA-256 est listé dans `SHA256SUMS`. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
|
||||
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent les références que Central utilise pour afficher et générer les commandes Docker; leurs sommes de contrôle restent dans la sortie CI. La release contient ces deux fichiers, `agent-update-manifest.sig` (signature ECDSA/SHA-256), la clé publique et les archives Agent. La clé publique permet de vérifier les valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
|
||||
|
||||
Avant de générer ou mettre à jour un Agent, configurer dans Central le réglage global `updates.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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+19
-3
@@ -148,6 +148,17 @@ 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
|
||||
@@ -190,9 +201,14 @@ 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`, configure the Central secret from the same
|
||||
protected secret source as `docker/secrets/coturn_secret`; protect the Central
|
||||
`.env` with owner-only permissions.
|
||||
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.
|
||||
|
||||
Start the core project first so its external `heimdall-net` network exists, then
|
||||
start MediaMTX with a separate project name:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CI Gitea et images Heimdall
|
||||
|
||||
La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et le build/scan de l’image Agent CUDA optionnelle, sans exiger de matériel GPU. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image`, `agent_image` et `agent_gpu_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur des runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version.
|
||||
La chaîne active est `.gitea/workflows/build.yml`. Le job `changes` détecte le graphe touché. Les PR compilent et testent le code concerné, puis construisent/scannent uniquement les images dont les fichiers ou dépendances ont changé. Les jobs d’image tournent en parallèle après `verify`. `CI policy` doit être configuré comme contrôle obligatoire de `main`.
|
||||
|
||||
## Sélection des runners
|
||||
|
||||
@@ -14,18 +14,15 @@ Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_EN
|
||||
|
||||
## Tests
|
||||
|
||||
`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne ensuite les suites affectées par une PR selon les fichiers modifiés et les `ProjectReference` transitifs. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toutes les suites. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `v*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés.
|
||||
`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne les suites affectées et leurs projets de build selon les fichiers modifiés et les `ProjectReference` transitifs; `build-plan.py` ne compile que ces cibles sur une PR. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toute la solution. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Le restore NuGet verrouillé reste solution-wide pour la vérification des dépendances, mais les compilations ciblées ne recompilent pas les graphes Agent/Web sans lien avec les fichiers touchés. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `*.*.*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés.
|
||||
|
||||
## Publication continue
|
||||
|
||||
Après validation de `verify` sur `main`, chaque job d'image publie son tag immuable `sha-<commit complet>` une fois son scan réussi. Le job `dockerhub_latest` attend les deux jobs, récupère les deux images publiées et déplace leurs tags `latest` :
|
||||
Les PR ne reçoivent aucun secret de publication et ne poussent aucune image. Les runs du même ref sont sérialisés pour qu’un build plus lent d’un commit ancien ne remette pas `latest` en arrière. Après validation sur `main`, chaque job touché publie sur Docker Hub son image `sha-<SHA>` et déplace uniquement son propre tag `latest`. Les builds inchangés sont sautés, y compris si le changement ne concerne que la documentation, le compose de déploiement ou un autre composant.
|
||||
|
||||
- `eltruncho/heimdall:latest` et `eltruncho/heimdall:sha-<commit complet>` ;
|
||||
- `eltruncho/heimdall-agent:latest` et `eltruncho/heimdall-agent:sha-<commit complet>`.
|
||||
Une version est publiée en poussant un tag `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Le workflow complet construit/scanne les images serveur, Agent CPU et Agent GPU une seule fois, puis publie leurs tags `sha-<SHA>` et version sur Docker Hub. Le job release réutilise ces images pour recueillir les digests; il ne les reconstruit pas et ne les rescane pas. Gitea reçoit `heimdall-installers-<version>.zip` pour Central, plus les archives Agent signées, leur clé publique, leur manifeste et les références d’images CPU/GPU nécessaires aux mises à jour natives. Provenance, liste de digests et checksums restent dans la sortie interne CI. Les couches Docker ne sont jamais attachées à Gitea. Les scripts Central `.sh` et `.ps1` récupèrent l’API de la dernière release stable, téléchargent le ZIP correspondant et exécutent son script épinglé à cette version; `HEIMDALL_INSTALLER_VERSION` permet de demander une version explicite. Le panneau d’installation Central confirme la release signée et masque les commandes natives tant que les assets nécessaires ne sont pas disponibles.
|
||||
|
||||
Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Renovate
|
||||
|
||||
|
||||
+53
-6
@@ -226,19 +226,62 @@ Dashboard shows agent offline state
|
||||
│ │ │ Token: a1b2c3d4-... (caché après création)│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ Commande Docker à exécuter sur le site distant : │ │
|
||||
│ │ Installer l'Agent │ │
|
||||
│ │ Déployez le connecteur sur la machine du site. │ │
|
||||
│ │ Release signée disponible : vX.Y.Z │ │
|
||||
│ │ │ │
|
||||
│ │ Système d'exploitation │ │
|
||||
│ │ [🐧 Linux] [⊞ Windows] [🐳 Docker] │ │
|
||||
│ │ │ │
|
||||
│ │ Méthode │ │
|
||||
│ │ [Exécution] [Service systemd] │ │
|
||||
│ │ │ │
|
||||
│ │ Configuration (Docker avec image GPU disponible)│ │
|
||||
│ │ [ ] Utiliser l'inférence GPU NVIDIA │ │
|
||||
│ │ │ │
|
||||
│ │ Commandes │ │
|
||||
│ │ Installer │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ docker run -e HEIMDALL_CENTRAL_URL=... │ │ │
|
||||
│ │ │ -e HEIMDALL_SITE_TOKEN=... │ │ │
|
||||
│ │ │ heimdall/agent:latest │ │ │
|
||||
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ Lancer │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ sudo systemctl start heimdall-agent [⧉]│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Copier la commande] [× Révoquer le token] │ │
|
||||
│ │ [× Révoquer le token] │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, `MudSnackbar` (copié)
|
||||
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, panneau installateur (`SiteInstallPanel`), commandes copiables avec `MudIconButton` et `MudTooltip`, `MudSnackbar` (copié)
|
||||
|
||||
### Parcours d'installation Agent
|
||||
|
||||
Le panneau suit le parcours de l'installateur Pangolin : choix de plateforme en tuiles, choix de méthode en tuiles, configuration optionnelle puis étapes de commandes. Les tuiles sont en trois colonnes sur écran large et s'empilent sur petit écran; les méthodes prennent toute la largeur disponible. La tuile sélectionnée garde un contour et un fond teinté de la couleur primaire.
|
||||
|
||||
```text
|
||||
Système d'exploitation
|
||||
[Linux] [Windows] [Docker]
|
||||
|
||||
Méthode
|
||||
[Exécution] [Service systemd]
|
||||
|
||||
Configuration (Docker uniquement si l'image GPU est publiée)
|
||||
[ ] Utiliser l'inférence GPU NVIDIA
|
||||
|
||||
Commandes
|
||||
Installer
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ commande/script [⧉]│
|
||||
└──────────────────────────────────────────────┘
|
||||
Lancer
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ commande de démarrage [⧉]│
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi une référence d'image vérifiée par digest. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
|
||||
|
||||
### États — Détail Site
|
||||
|
||||
@@ -582,6 +625,10 @@ 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
|
||||
|
||||
@@ -234,6 +234,7 @@ 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",
|
||||
|
||||
@@ -151,6 +151,7 @@ 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,12 +4,63 @@ param()
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$script:PackageReleaseVersion = 'unversioned'
|
||||
$script:ReleaseApiUrl = if ($env:HEIMDALL_RELEASE_API_URL) {
|
||||
$env:HEIMDALL_RELEASE_API_URL.TrimEnd('/')
|
||||
} else {
|
||||
'https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases'
|
||||
}
|
||||
$script:SourceBaseUrl = if ($env:HEIMDALL_SOURCE_BASE_URL) {
|
||||
$env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/')
|
||||
} else {
|
||||
'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main'
|
||||
}
|
||||
|
||||
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
|
||||
throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.'
|
||||
}
|
||||
|
||||
$installerVersion = if ($env:HEIMDALL_INSTALLER_VERSION) { $env:HEIMDALL_INSTALLER_VERSION } else { $script:PackageReleaseVersion }
|
||||
if ($script:PackageReleaseVersion -eq 'unversioned') {
|
||||
$releaseUri = "$script:ReleaseApiUrl/latest"
|
||||
if ($env:HEIMDALL_INSTALLER_VERSION) {
|
||||
$installerVersion = $env:HEIMDALL_INSTALLER_VERSION
|
||||
if ($installerVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
|
||||
throw 'Version Heimdall invalide.'
|
||||
}
|
||||
$releaseUri = "$script:ReleaseApiUrl/tags/$installerVersion"
|
||||
}
|
||||
$bootstrapRoot = Join-Path ([IO.Path]::GetTempPath()) ('heimdall-installer-' + [Guid]::NewGuid().ToString('N'))
|
||||
$bundlePath = Join-Path $bootstrapRoot 'installers.zip'
|
||||
$null = New-Item -ItemType Directory -Path $bootstrapRoot
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Get -Uri $releaseUri -TimeoutSec 30
|
||||
$resolvedVersion = [string]$release.tag_name
|
||||
if ($resolvedVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
|
||||
throw 'La release Heimdall retournée a une version invalide.'
|
||||
}
|
||||
$installerName = "heimdall-installers-$resolvedVersion.zip"
|
||||
$installerAsset = @($release.assets) | Where-Object { $_.name -eq $installerName } | Select-Object -First 1
|
||||
if (-not $installerAsset -or $installerAsset.browser_download_url -notmatch '^https://') {
|
||||
throw "La release ne contient pas son bundle d'installation versionné."
|
||||
}
|
||||
$expectedHash = [string]$installerAsset.digest -replace '^sha256:', ''
|
||||
if ($expectedHash -notmatch '^[A-Fa-f0-9]{64}$') { throw 'La release ne fournit pas le SHA-256 du bundle.' }
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $installerAsset.browser_download_url -OutFile $bundlePath -TimeoutSec 120
|
||||
$actualHash = (Get-FileHash -LiteralPath $bundlePath -Algorithm SHA256).Hash
|
||||
if ($actualHash -ne $expectedHash) { throw 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' }
|
||||
Expand-Archive -LiteralPath $bundlePath -DestinationPath $bootstrapRoot -Force
|
||||
$packagedScript = Join-Path $bootstrapRoot 'install\install-server.ps1'
|
||||
if (-not (Test-Path -LiteralPath $packagedScript)) { throw 'Le bundle ne contient pas install/install-server.ps1.' }
|
||||
$env:HEIMDALL_INSTALLER_VERSION = $resolvedVersion
|
||||
& $packagedScript
|
||||
if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
return
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $bootstrapRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
function Read-Answer {
|
||||
param([string]$Prompt, [string]$Default)
|
||||
$answer = Read-Host "$Prompt [$Default]"
|
||||
@@ -78,9 +129,6 @@ function Invoke-DockerCompose {
|
||||
if ($LASTEXITCODE -ne 0) { throw "docker compose a échoué (code $LASTEXITCODE)." }
|
||||
}
|
||||
|
||||
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
|
||||
throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.'
|
||||
}
|
||||
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw 'Docker est requis.' }
|
||||
& docker compose version | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Le plugin Docker Compose est requis.' }
|
||||
|
||||
@@ -7,6 +7,8 @@ if [[ -n "$SCRIPT_PATH" ]]; then
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)"
|
||||
fi
|
||||
readonly SOURCE_BASE_URL="${HEIMDALL_SOURCE_BASE_URL:-https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main}"
|
||||
readonly PACKAGE_RELEASE_VERSION="unversioned"
|
||||
readonly RELEASE_API_URL="${HEIMDALL_RELEASE_API_URL:-https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases}"
|
||||
REPO_ROOT=""
|
||||
if [[ -n "$SCRIPT_DIR" && -f "${SCRIPT_DIR}/../docker/docker-compose.ollama.yml" ]]; then
|
||||
REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
|
||||
@@ -26,11 +28,53 @@ if [[ ! -t 0 && (! -r /dev/tty || ! -w /dev/tty) ]]; then
|
||||
echo "Ce script nécessite un terminal interactif." >&2
|
||||
exit 2
|
||||
fi
|
||||
for command in docker openssl curl; do
|
||||
for command in docker openssl curl jq unzip; do
|
||||
command -v "$command" >/dev/null || { echo "Commande requise absente : $command" >&2; exit 1; }
|
||||
done
|
||||
docker compose version >/dev/null
|
||||
|
||||
# A raw-branch bootstrap resolves the latest stable installer bundle, then
|
||||
# re-enters the version-pinned script contained in that bundle. Packaged copies
|
||||
# already carry their version and never resolve a moving release again.
|
||||
installer_version="$PACKAGE_RELEASE_VERSION"
|
||||
if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
|
||||
release_api="$RELEASE_API_URL/latest"
|
||||
if [[ -n "${HEIMDALL_INSTALLER_VERSION:-}" ]]; then
|
||||
installer_version="$HEIMDALL_INSTALLER_VERSION"
|
||||
[[ "$installer_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
|
||||
echo 'Version Heimdall invalide.' >&2; exit 1;
|
||||
}
|
||||
release_api="$RELEASE_API_URL/tags/$installer_version"
|
||||
fi
|
||||
bootstrap_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimdall-installer.XXXXXX")"
|
||||
cleanup_bootstrap() { rm -rf -- "$bootstrap_dir"; }
|
||||
trap cleanup_bootstrap EXIT
|
||||
if ! curl --fail --silent --show-error --location "$release_api" --output "$bootstrap_dir/release.json"; then
|
||||
echo 'Impossible de récupérer la dernière release Heimdall.' >&2; exit 1
|
||||
fi
|
||||
resolved_version="$(jq -er '.tag_name | select(type == "string" and test("^[0-9]+\\.[0-9]+\\.[0-9]+([.-][0-9A-Za-z.-]+)?$"))' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release Heimdall retournée a une version invalide.' >&2; exit 1;
|
||||
}
|
||||
installer_asset="heimdall-installers-$resolved_version.zip"
|
||||
asset_json="$(jq -ce --arg name "$installer_asset" '.assets[] | select(.name == $name)' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release ne contient pas son bundle d’installation versionné.' >&2; exit 1;
|
||||
}
|
||||
installer_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$asset_json")" || {
|
||||
echo 'URL HTTPS du bundle d’installation invalide.' >&2; exit 1;
|
||||
}
|
||||
expected_sha256="$(jq -er '.digest | select(test("^sha256:[A-Fa-f0-9]{64}$")) | sub("^sha256:"; "")' <<<"$asset_json")" || {
|
||||
echo 'La release ne fournit pas le SHA-256 du bundle.' >&2; exit 1;
|
||||
}
|
||||
curl --fail --silent --show-error --location "$installer_url" --output "$bootstrap_dir/installers.zip"
|
||||
actual_sha256="$(sha256sum "$bootstrap_dir/installers.zip" | cut -d ' ' -f 1)"
|
||||
[[ "${actual_sha256,,}" == "${expected_sha256,,}" ]] || { echo 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' >&2; exit 1; }
|
||||
unzip -q "$bootstrap_dir/installers.zip" -d "$bootstrap_dir/bundle"
|
||||
packaged_script="$bootstrap_dir/bundle/install/install-server.sh"
|
||||
[[ -f "$packaged_script" ]] || { echo 'Le bundle ne contient pas install/install-server.sh.' >&2; exit 1; }
|
||||
HEIMDALL_INSTALLER_VERSION="$resolved_version" bash "$packaged_script" "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
copy_source_asset() {
|
||||
local relative_path="$1" destination_path="$2" asset_tmp="${2}.tmp.$$"
|
||||
if [[ -n "$REPO_ROOT" && -f "$REPO_ROOT/$relative_path" ]]; then
|
||||
|
||||
@@ -90,6 +90,9 @@ peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
|
||||
utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de
|
||||
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
|
||||
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
|
||||
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
|
||||
jour pilotées par Central; ce socket donne à l’Agent un contrôle étendu sur
|
||||
l’hôte. N’installez ce mode que sur un hôte de confiance.
|
||||
|
||||
### 3. Développement local
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline acceptance for package.sh and publish.sh using synthetic credentials and API doubles."""
|
||||
"""Offline acceptance for one tagged image and installer release with synthetic doubles."""
|
||||
import base64
|
||||
import email
|
||||
import hashlib
|
||||
@@ -19,7 +19,6 @@ from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REPOSITORY = 'arnaud.dartois/Heimdall'
|
||||
TAG = 'v1.2.3'
|
||||
DOCKER_TOKEN = 'offline-docker-token-not-valid'
|
||||
RELEASE_TOKEN = 'offline-gitea-token-not-valid'
|
||||
SERVER_DIGEST = 'sha256:' + '1' * 64
|
||||
@@ -51,7 +50,7 @@ def main():
|
||||
fakebin = temp / 'bin'
|
||||
fakebin.mkdir()
|
||||
docker_log = temp / 'docker-commands.jsonl'
|
||||
release_state = {'draft': None, 'assets': {}, 'authorized': 0}
|
||||
release_state = {'release': None, 'assets': {}, 'authorized': 0}
|
||||
|
||||
subprocess.run([
|
||||
'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes',
|
||||
@@ -68,14 +67,22 @@ args = sys.argv[1:]
|
||||
log = os.environ['OFFLINE_DOCKER_LOG']
|
||||
with open(log, 'a') as f: f.write(json.dumps(args) + '\n')
|
||||
if args[:1] == ['build']:
|
||||
target = args[args.index('-t') + 1]
|
||||
sys.exit(0)
|
||||
sys.exit(12) # Release publication must reuse the scanned image builds.
|
||||
if args[:2] == ['login', 'docker.io']:
|
||||
if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user':
|
||||
sys.exit(11)
|
||||
sys.exit(0)
|
||||
if args[:2] == ['manifest', 'inspect']:
|
||||
sys.exit(1) # Simulate absent remote tags; never call a registry.
|
||||
if args[:2] == ['compose', 'version']:
|
||||
marker = os.environ.get('OFFLINE_STOP_COMPOSE_MARKER')
|
||||
if marker:
|
||||
try:
|
||||
open(marker, 'x').close()
|
||||
except FileExistsError:
|
||||
sys.exit(37)
|
||||
print('Docker Compose version v2.offline')
|
||||
sys.exit(0)
|
||||
if args[:1] == ['pull']:
|
||||
sys.exit(0) # Synthetic registry pull; never contact Docker Hub.
|
||||
if args[:1] == ['tag']:
|
||||
sys.exit(0)
|
||||
if args[:1] == ['push']:
|
||||
@@ -88,7 +95,10 @@ if args[:2] == ['image', 'inspect']:
|
||||
digest = os.environ['OFFLINE_AGENT_DIGEST']
|
||||
else:
|
||||
digest = os.environ['OFFLINE_SERVER_DIGEST']
|
||||
print(image + '@' + digest)
|
||||
if '--format' in args and 'RepoDigests' in args[args.index('--format') + 1]:
|
||||
print(image + '@' + digest)
|
||||
elif '--format' in args and 'org.opencontainers.image.revision' in args[args.index('--format') + 1]:
|
||||
print(os.environ['OFFLINE_COMMIT'])
|
||||
sys.exit(0)
|
||||
if args[:1] == ['save']:
|
||||
from pathlib import Path
|
||||
@@ -113,6 +123,28 @@ sys.exit(12)
|
||||
docker_path = fakebin / 'docker'
|
||||
docker_path.write_text(docker_stub)
|
||||
docker_path.chmod(0o700)
|
||||
curl_stub = r'''#!/usr/bin/env python3
|
||||
import hashlib, json, os, shutil, sys
|
||||
args = sys.argv[1:]
|
||||
url = next(value for value in args if value.startswith('https://'))
|
||||
output = args[args.index('--output') + 1]
|
||||
with open(os.environ['OFFLINE_CURL_LOG'], 'a') as log:
|
||||
log.write(url + '\n')
|
||||
if url.endswith('/releases/latest'):
|
||||
payload = json.dumps({'tag_name':'1.2.3','assets':[{
|
||||
'name':'heimdall-installers-1.2.3.zip',
|
||||
'digest':'sha256:' + hashlib.sha256(open(os.environ['OFFLINE_INSTALLER_ZIP'],'rb').read()).hexdigest(),
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}]}).encode()
|
||||
open(output, 'wb').write(payload)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
|
||||
else:
|
||||
sys.exit(22)
|
||||
'''
|
||||
curl_path = fakebin / 'curl'
|
||||
curl_path.write_text(curl_stub)
|
||||
curl_path.chmod(0o700)
|
||||
curl_log = temp / 'installer-bootstrap-urls.txt'
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
@@ -133,11 +165,43 @@ sys.exit(12)
|
||||
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
|
||||
path = urlsplit(self.path).path
|
||||
if path.endswith('/releases/tags/' + TAG):
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
if '/compare/' in path:
|
||||
self._json(200, {'commits': [{'sha': 'synthetic-merge-commit'}]})
|
||||
elif path.endswith('/commits/synthetic-merge-commit/pull'):
|
||||
self._json(200, {'number': 42, 'merged': True, 'title': 'Offline acceptance feature',
|
||||
'html_url': 'https://gitea.test/pulls/42'})
|
||||
elif path.endswith('/releases/latest'):
|
||||
self._json(200, {'tag_name': '1.2.3', 'assets': [{
|
||||
'name': 'heimdall-installers-1.2.3.zip',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}]})
|
||||
elif path.endswith('/releases/tags/1.2.3'):
|
||||
self._json(404, {'message': 'not found'})
|
||||
elif path.endswith('/releases/7301/assets'):
|
||||
self._json(200, [])
|
||||
@@ -152,12 +216,16 @@ sys.exit(12)
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
|
||||
if path.endswith('/releases'):
|
||||
release = json.loads(body)
|
||||
assert release['tag_name'] == TAG
|
||||
assert release['tag_name'] == '1.2.3'
|
||||
assert release['name'] == '1.2.3'
|
||||
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['draft'] = release
|
||||
self._json(201, {'id': 7301, 'draft': True,
|
||||
release_state['release'] = release
|
||||
self._json(201, {'id': 7301, 'draft': True, 'prerelease': True,
|
||||
'tag_name': release['tag_name'],
|
||||
'html_url': 'https://gitea.test/releases/7301'})
|
||||
return
|
||||
if path.endswith('/releases/7301/assets'):
|
||||
@@ -175,6 +243,24 @@ sys.exit(12)
|
||||
return
|
||||
self._json(404, {'message': 'unexpected request'})
|
||||
|
||||
def do_PATCH(self):
|
||||
if not self._authorized():
|
||||
self._json(401, {})
|
||||
return
|
||||
path = urlsplit(self.path).path
|
||||
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', '0'))))
|
||||
if path.endswith('/releases/7301'):
|
||||
assert set(release_state['assets']) >= {
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'heimdall-installers-1.2.3.zip'}
|
||||
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
release_state['release']['draft'] = body['draft']
|
||||
release_state['release']['prerelease'] = body['prerelease']
|
||||
self._json(200, release_state['release'])
|
||||
return
|
||||
self._json(404, {'message': 'unexpected request'})
|
||||
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, private_cert_key)
|
||||
@@ -190,21 +276,60 @@ sys.exit(12)
|
||||
'SSL_CERT_FILE': str(cert),
|
||||
'NO_PROXY': '127.0.0.1,localhost',
|
||||
'no_proxy': '127.0.0.1,localhost',
|
||||
'BUILD_REF': 'refs/tags/' + TAG,
|
||||
'BUILD_REF': 'refs/tags/1.2.3',
|
||||
'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',
|
||||
]
|
||||
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'
|
||||
@@ -214,49 +339,69 @@ sys.exit(12)
|
||||
signature = temp / 'manifest.sig'
|
||||
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert manifest['version'] == TAG
|
||||
assert manifest['version'] == '1.2.3'
|
||||
assert manifest['containerImage'] == 'eltruncho/heimdall-agent'
|
||||
assert manifest['containerImageDigest'] == AGENT_DIGEST
|
||||
assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu'
|
||||
assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST
|
||||
provenance = json.loads(release_state['assets']['provenance.json'])
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/' + TAG
|
||||
provenance = json.loads((packages / 'provenance.json').read_text())
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/1.2.3'
|
||||
agent_image = json.loads(release_state['assets']['agent-image.json'])
|
||||
assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'}
|
||||
gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json'])
|
||||
assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'}
|
||||
for platform, digest in manifest['assets'].items():
|
||||
archive = f'heimdall-agent-{platform}-{TAG.removeprefix("v")}.tar.gz'
|
||||
archive = f'heimdall-agent-{platform}-1.2.3.tar.gz'
|
||||
assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest
|
||||
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key),
|
||||
'-signature', str(signature), str(packages / 'agent-update-manifest.json')],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
checksums = release_state['assets']['SHA256SUMS'].decode().splitlines()
|
||||
checksums = (packages / 'SHA256SUMS').read_text().splitlines()
|
||||
for line in checksums:
|
||||
digest, filename = line.split(maxsplit=1)
|
||||
filename = filename.lstrip('* ')
|
||||
assert filename in release_state['assets'], f'missing checksum asset {filename}'
|
||||
assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename
|
||||
image_digests = release_state['assets']['image-digests.txt'].decode().splitlines()
|
||||
assert len(image_digests) == 6
|
||||
assert sum(AGENT_DIGEST in item for item in image_digests) == 2
|
||||
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 2
|
||||
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
|
||||
assert sum(call[:1] == ['build'] for call in docker_calls) == 3
|
||||
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
|
||||
assert len(pushes) == 6
|
||||
assert pushes == {
|
||||
f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall: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 (packages / filename).is_file(), f'missing package checksum input {filename}'
|
||||
assert hashlib.sha256((packages / filename).read_bytes()).hexdigest() == digest, filename
|
||||
image_digests = (packages / 'image-digests.txt').read_text().splitlines()
|
||||
assert len(image_digests) == 3
|
||||
assert sum(AGENT_DIGEST in item for item in image_digests) == 1
|
||||
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 1
|
||||
with __import__('zipfile').ZipFile(packages/'heimdall-installers-1.2.3.zip') as bundle:
|
||||
assert 'install/install-server.sh' in bundle.namelist()
|
||||
assert 'install/install-server.ps1' in bundle.namelist()
|
||||
assert 'docker/docker-compose.yml' in bundle.namelist()
|
||||
server_script = bundle.read('install/install-server.sh').decode()
|
||||
windows_script = bundle.read('install/install-server.ps1').decode()
|
||||
assert '/raw/tag/1.2.3' in server_script
|
||||
assert 'eltruncho/heimdall:1.2.3' in server_script
|
||||
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in server_script
|
||||
assert "PackageReleaseVersion = '1.2.3'" in windows_script
|
||||
assert 'install/install-agent.sh' in bundle.namelist()
|
||||
assert 'install/install-agent.ps1' in bundle.namelist()
|
||||
expected_release_assets = {
|
||||
'heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'agent-image.json', 'agent-image-gpu.json',
|
||||
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
|
||||
}
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 1
|
||||
assert release_state['draft']['draft'] is True
|
||||
assert len(release_state['assets']) >= 9
|
||||
assert set(release_state['assets']) == expected_release_assets
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
|
||||
assert sum(call[:1] == ['build'] for call in docker_calls) == 0
|
||||
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
|
||||
assert len(pushes) == 9
|
||||
for image in ('eltruncho/heimdall', 'eltruncho/heimdall-agent', 'eltruncho/heimdall-agent-gpu'):
|
||||
assert f'{image}:sha-{commit}' in pushes
|
||||
assert f'{image}:latest' in pushes
|
||||
assert f'{image}:1.2.3' in pushes
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 7
|
||||
assert release_state['release']['draft'] is False
|
||||
assert release_state['release']['prerelease'] is False
|
||||
assert len(release_state['assets']) == len(expected_release_assets)
|
||||
assert release_state['authorized'] >= 7
|
||||
print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, CPU/GPU image digests, and six simulated pushes.')
|
||||
assert sum(call[:1] == ['push'] for call in docker_calls if call[0] != 'login') == 12
|
||||
print(f'Offline version release simulation passed: installer ZIP, Agent archives, P-256 signature, {len(release_state["assets"])} Gitea assets, immutable image refs, and selective Docker Hub tags.')
|
||||
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git jq python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
# Fail explicitly if a runner cannot provide the required Docker build service.
|
||||
docker version --format '{{.Server.Version}}'
|
||||
docker compose version
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build only the projects selected by test-plan.py after solution restore."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PLAN = ROOT / "artifacts" / "tests" / "plan.json"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
plan = json.loads(PLAN.read_text())
|
||||
targets = plan.get("build_projects")
|
||||
if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets):
|
||||
raise SystemExit("Test plan has an invalid build_projects list")
|
||||
if not targets:
|
||||
print("No .NET build targets selected")
|
||||
return
|
||||
|
||||
for target in targets:
|
||||
path = ROOT / target
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"Build target does not exist: {target}")
|
||||
print(f"Building affected target: {target}", flush=True)
|
||||
subprocess.run(
|
||||
["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Set Gitea workflow outputs for validation and affected container images."""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
|
||||
def changed_paths() -> list[str]:
|
||||
event = os.environ.get("EVENT_NAME", "")
|
||||
ref = os.environ.get("REF", "")
|
||||
if event == "push" and ref.startswith("refs/tags/"):
|
||||
tag = ref.removeprefix("refs/tags/")
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[.-][0-9A-Za-z.-]+)?", tag):
|
||||
raise SystemExit("Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix")
|
||||
return ["*"]
|
||||
if event == "pull_request":
|
||||
base = os.environ["PR_BASE_SHA"]
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", f"{base}...HEAD"], text=True
|
||||
).splitlines()
|
||||
before = os.environ.get("PUSH_BEFORE_SHA", "")
|
||||
current = os.environ.get("CURRENT_SHA", "HEAD")
|
||||
if before and before != "0" * 40:
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", before, current], text=True
|
||||
).splitlines()
|
||||
return ["*"]
|
||||
|
||||
|
||||
def under(path: str, *prefixes: str) -> bool:
|
||||
return any(path == prefix or path.startswith(prefix.rstrip("/") + "/") for prefix in prefixes)
|
||||
|
||||
|
||||
def scope_for(paths: list[str]) -> dict[str, bool]:
|
||||
all_images = "*" in paths
|
||||
validation_prefixes = ("src/", "tests/", "scripts/ci/", "docker/", "install/", "models/")
|
||||
validation_files = {
|
||||
"Heimdall.slnx", "global.json", ".dockerignore", ".env.example", "Makefile",
|
||||
"GitVersion.yml", "GitVersion.Agent.yml", "Directory.Packages.props", "NuGet.Config",
|
||||
}
|
||||
run_validation = all_images or any(
|
||||
under(path, *validation_prefixes) or path in validation_files or
|
||||
path.startswith(".gitea/workflows/") or path.startswith("Directory.Build.")
|
||||
for path in paths
|
||||
)
|
||||
|
||||
# Shared projects included by both Docker build graphs.
|
||||
shared = {
|
||||
"global.json", "Directory.Packages.props", "NuGet.Config", "GitVersion.yml",
|
||||
}
|
||||
shared_image_change = all_images or any(
|
||||
path in shared or path.startswith("Directory.Build.") for path in paths
|
||||
)
|
||||
server = shared_image_change or any(
|
||||
under(path, "src/Heimdall.Web", "src/Heimdall.Infrastructure",
|
||||
"src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts")
|
||||
or path == "docker/Dockerfile" or under(path, "install")
|
||||
for path in paths
|
||||
)
|
||||
agent_projects = (
|
||||
"src/Heimdall.Agent", "src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts", "src/Heimdall.Mdns",
|
||||
)
|
||||
agent_common = any(
|
||||
under(path, *agent_projects) or path == "models/yolov8n.onnx"
|
||||
for path in paths
|
||||
)
|
||||
agent = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
agent_gpu = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent.gpu" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
return {
|
||||
"run_validation": run_validation,
|
||||
"build_server": server,
|
||||
"build_agent": agent,
|
||||
"build_agent_gpu": agent_gpu,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
output = os.environ.get("GITEA_OUTPUT")
|
||||
if not output:
|
||||
raise SystemExit("GITEA_OUTPUT is required")
|
||||
with open(output, "a", encoding="utf-8") as stream:
|
||||
for name, selected in scope_for(changed_paths()).items():
|
||||
stream.write(f"{name}={'true' if selected else 'false'}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/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,7 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}")
|
||||
if [[ "${BUILD_REF:-}" == refs/tags/* ]]; then
|
||||
version=${BUILD_REF#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
|
||||
+51
-18
@@ -2,33 +2,66 @@
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
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]}
|
||||
version=${ref#refs/tags/}
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
|
||||
echo 'Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix.' >&2; exit 2;
|
||||
}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
mkdir -p artifacts/packages
|
||||
for component in Web Agent; do
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.$component" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
if [[ "$component" == Agent ]]; then
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
fi
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -n > "artifacts/packages/heimdall-${component,,}-$rid-$version.tar.gz"
|
||||
done
|
||||
component=Agent
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.Agent" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -1 -n > "artifacts/packages/heimdall-agent-$rid-$version.tar.gz"
|
||||
python3 - "$version" "$ref" <<'PY'
|
||||
import os,sys,zipfile
|
||||
from datetime import datetime,timezone
|
||||
from pathlib import Path
|
||||
|
||||
version, ref = sys.argv[1:]
|
||||
epoch = int(__import__('subprocess').check_output(['git','show','-s','--format=%ct','HEAD'],text=True))
|
||||
stamp = datetime.fromtimestamp(max(epoch, 315532800), timezone.utc).timetuple()[:6]
|
||||
tag = version
|
||||
source_base = f"https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/tag/{tag}"
|
||||
files = [Path('install/install-server.sh'), Path('install/install-server.ps1')]
|
||||
files += sorted(Path('install').glob('*.sh'))
|
||||
files += sorted(Path('install').glob('*.ps1'))
|
||||
files += sorted(Path('install').glob('*.py'))
|
||||
files += sorted(Path('docker').glob('docker-compose*.yml'))
|
||||
files += sorted(Path('docker/scripts').glob('*')) if Path('docker/scripts').exists() else []
|
||||
archive = Path(f'artifacts/packages/heimdall-installers-{version}.zip')
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
|
||||
for path in sorted(set(files)):
|
||||
if not path.is_file():
|
||||
continue
|
||||
data = path.read_bytes()
|
||||
if path.name in {'install-server.sh', 'install-server.ps1'} or path.name.startswith('docker-compose'):
|
||||
text = data.decode('utf-8')
|
||||
text = text.replace('https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main', source_base)
|
||||
text = text.replace('eltruncho/heimdall:latest', f'eltruncho/heimdall:{version}')
|
||||
text = text.replace('PACKAGE_RELEASE_VERSION="unversioned"', f'PACKAGE_RELEASE_VERSION="{version}"')
|
||||
text = text.replace("PackageReleaseVersion = 'unversioned'", f"PackageReleaseVersion = '{version}'")
|
||||
data = text.encode('utf-8')
|
||||
entry = zipfile.ZipInfo(path.as_posix(), stamp)
|
||||
entry.compress_type = zipfile.ZIP_DEFLATED
|
||||
entry.external_attr = (0o100755 if path.suffix in {'.sh', '.py'} else 0o100644) << 16
|
||||
bundle.writestr(entry, data)
|
||||
PY
|
||||
python3 - "$sha" "$version" "$ref" <<'PY'
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'commit':sys.argv[1], 'version':sys.argv[2], 'ref':sys.argv[3],
|
||||
'repository':os.environ.get('BUILD_REPOSITORY'), 'run_id':os.environ.get('BUILD_RUN_ID'),
|
||||
'targets':['Web/PWA','Agent'], 'rids':['portable-framework-dependent'],
|
||||
'targets':['Agent native updater'], 'rids':['portable-framework-dependent'],
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz provenance.json > SHA256SUMS)
|
||||
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
|
||||
printf '%s' "$version" > artifacts/version
|
||||
+13
-21
@@ -33,21 +33,19 @@ openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prim
|
||||
}
|
||||
openssl pkey -in "$signing_key" -pubout -out artifacts/packages/agent-release-public.pem
|
||||
(cd artifacts/packages && sha256sum agent-release-public.pem >> SHA256SUMS)
|
||||
[[ "$BUILD_REF" == refs/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 'v'+p['version'] != sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match checkout/tag')
|
||||
if p['commit'] != sys.argv[1] or p['version'] != sys.argv[2] or p['ref'] != 'refs/tags/' + sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match the verified version tag')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum --check SHA256SUMS)
|
||||
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.
|
||||
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.
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
|
||||
@@ -66,17 +64,11 @@ for component in server agent agent-gpu; do
|
||||
else
|
||||
image=$server_image
|
||||
fi
|
||||
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
|
||||
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
|
||||
done
|
||||
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
|
||||
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
|
||||
@@ -121,7 +113,7 @@ root=Path('artifacts/packages')
|
||||
image=json.loads((root/'agent-image.json').read_text())
|
||||
gpu_image=json.loads((root/'agent-image-gpu.json').read_text())
|
||||
package_version=Path('artifacts/version').read_text().strip()
|
||||
version='v'+package_version
|
||||
version=package_version
|
||||
assets={}
|
||||
for path in root.glob('heimdall-agent-*.tar.gz'):
|
||||
suffix=f'-{package_version}.tar.gz'
|
||||
|
||||
+18
-18
@@ -1,9 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:?Expected server, agent, agent-gpu or latest}
|
||||
case "$mode" in server|agent|agent-gpu|latest) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu|latest' >&2; exit 2 ;; esac
|
||||
mode=${1:?Expected server, agent or agent-gpu}
|
||||
case "$mode" in server|agent|agent-gpu) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu' >&2; exit 2 ;; esac
|
||||
sha=$(git rev-parse HEAD)
|
||||
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
|
||||
ref=${BUILD_REF:-}
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
@@ -17,19 +22,14 @@ repository() {
|
||||
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
|
||||
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
|
||||
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
|
||||
if [[ "$mode" == latest ]]; then
|
||||
# Move mutable tags only after both independently built images passed their scans.
|
||||
for component in server agent; do
|
||||
docker pull "$(repository "$component"):sha-$sha"
|
||||
done
|
||||
for component in server agent; do
|
||||
repo=$(repository "$component")
|
||||
docker tag "$repo:sha-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
done
|
||||
else
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:$version"
|
||||
docker push "$repo:$version"
|
||||
elif [[ "$ref" == refs/heads/main ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
fi
|
||||
+50
-19
@@ -1,4 +1,4 @@
|
||||
"""Create/update only a draft Gitea release; never log auth or response bodies."""
|
||||
"""Create/update the Gitea release for one verified version tag."""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
@@ -8,9 +8,11 @@ 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
|
||||
@@ -26,23 +28,52 @@ 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'
|
||||
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
|
||||
required_assets = [installer_bundle, package_root / 'agent-release-public.pem',
|
||||
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
|
||||
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
|
||||
if any(not path.is_file() for path in required_assets) or not agent_archives:
|
||||
raise SystemExit('Installer bundle or signed Agent update assets are missing')
|
||||
# CI provenance, image digests, and checksum bookkeeping stay in the build
|
||||
# artifacts. Gitea releases expose only the Central installer bundle and the
|
||||
# files Central/Agent need to verify and install native Agent updates.
|
||||
package_files = sorted([*required_assets, *agent_archives])
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': tag,
|
||||
'draft': True, 'prerelease': '-' in tag,
|
||||
'body': f"Commit: `{provenance['commit']}`\nActions run: {provenance['run_id']}\n"
|
||||
'Server/PWA and agent only; checksums and image digests attached.\n'
|
||||
'Draft: promote explicitly after reviewing publication evidence.'})
|
||||
if not release['draft']:
|
||||
raise SystemExit('Refusing to mutate an already public release')
|
||||
# Reruns replace draft assets; published releases remain immutable.
|
||||
for asset in request(f"/releases/{release['id']}/assets"):
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
|
||||
'draft': True, 'prerelease': '-' 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:
|
||||
request(f"/releases/{release['id']}/assets/{asset['id']}", 'DELETE')
|
||||
for path in sorted(Path('artifacts/packages').iterdir()):
|
||||
if path.is_file():
|
||||
boundary = uuid.uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
|
||||
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
|
||||
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
|
||||
'POST', payload, 'multipart/form-data; boundary='+boundary)
|
||||
print('Draft release: '+release['html_url'])
|
||||
for path in package_files:
|
||||
boundary = uuid.uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
|
||||
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
|
||||
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
|
||||
'POST', payload, 'multipart/form-data; boundary='+boundary)
|
||||
|
||||
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'])
|
||||
@@ -0,0 +1,48 @@
|
||||
"""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).')
|
||||
+38
-7
@@ -9,6 +9,8 @@ import xml.etree.ElementTree as ET
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon")
|
||||
SOURCES = sorted((ROOT / "src").glob("*/*.csproj"))
|
||||
ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")]
|
||||
|
||||
|
||||
def references(project: Path) -> set[Path]:
|
||||
@@ -19,6 +21,30 @@ def references(project: Path) -> set[Path]:
|
||||
}
|
||||
|
||||
|
||||
def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]:
|
||||
result: set[Path] = set()
|
||||
pending = list(graph.get(project, set()))
|
||||
while pending:
|
||||
dependency = pending.pop()
|
||||
if dependency in result:
|
||||
continue
|
||||
result.add(dependency)
|
||||
pending.extend(graph.get(dependency, set()))
|
||||
return result
|
||||
|
||||
|
||||
def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]],
|
||||
mode: str) -> list[str]:
|
||||
if mode == "all":
|
||||
return ["Heimdall.slnx"]
|
||||
|
||||
suite_projects = [project for project in TESTS if project.stem in suites]
|
||||
covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set()
|
||||
targets = [*suite_projects, *(project for project in SOURCES
|
||||
if project.resolve() in affected and project.resolve() not in covered_sources)]
|
||||
return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets})
|
||||
|
||||
|
||||
def changed_files() -> list[str] | None:
|
||||
if os.environ.get("GITEA_EVENT_NAME") != "pull_request":
|
||||
return None
|
||||
@@ -31,11 +57,11 @@ def changed_files() -> list[str] | None:
|
||||
|
||||
def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
if changed is None:
|
||||
return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]}
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": [], "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, {}, "all")}
|
||||
|
||||
all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | {
|
||||
p.resolve() for p in (ROOT / "tests").glob("*/*.csproj")
|
||||
}
|
||||
all_paths = {p.resolve() for p in ALL_PROJECTS}
|
||||
graph = {project: references(project) for project in all_paths}
|
||||
changed_projects: set[Path] = set()
|
||||
broad = False
|
||||
@@ -59,10 +85,12 @@ def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"}
|
||||
for name in changed
|
||||
):
|
||||
return {"mode": "affected", "changed": changed, "suites": []}
|
||||
return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []}
|
||||
|
||||
if broad or (changed and not changed_projects):
|
||||
return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]}
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": changed, "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, graph, "all")}
|
||||
|
||||
affected = set(changed_projects)
|
||||
while True:
|
||||
@@ -72,7 +100,9 @@ def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
affected |= additions
|
||||
|
||||
suites = [p.stem for p in TESTS if p.resolve() in affected]
|
||||
return {"mode": "affected", "changed": changed, "suites": suites}
|
||||
projects = build_targets(affected, suites, graph, "affected")
|
||||
return {"mode": "affected", "changed": changed, "suites": suites,
|
||||
"build_projects": projects}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -81,3 +111,4 @@ if __name__ == "__main__":
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}")
|
||||
print(f"Build targets: {', '.join(result['build_projects']) or 'none'}")
|
||||
+135
-24
@@ -1,4 +1,4 @@
|
||||
"""Contract tests for security gates and draft release uploads, without network."""
|
||||
"""Contract tests for security gates and versioned release uploads, without network."""
|
||||
import contextlib
|
||||
import io
|
||||
import importlib.util
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -15,6 +16,70 @@ 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):
|
||||
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
|
||||
def test_server_installer_has_valid_powershell_syntax(self):
|
||||
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
|
||||
result = subprocess.run([shutil.which('pwsh'), '-NoProfile', '-Command', parser],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
class PwaAssetTests(unittest.TestCase):
|
||||
def test_manifest_raster_icons_exist_with_declared_dimensions(self):
|
||||
manifest = json.loads((REPO_ROOT/'src/Heimdall.Web/wwwroot/manifest.webmanifest').read_text())
|
||||
@@ -43,6 +108,12 @@ def load_test_plan():
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_build_plan():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_efcore_policy():
|
||||
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -74,20 +145,54 @@ class TestPlanTests(unittest.TestCase):
|
||||
self.assertIn('Heimdall.E2E.Tests', suites)
|
||||
|
||||
def test_agent_change_does_not_run_unrelated_web_tests(self):
|
||||
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites']
|
||||
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
|
||||
suites = plan['suites']
|
||||
self.assertIn('Heimdall.Agent.Tests', suites)
|
||||
self.assertNotIn('Heimdall.Web.Tests', suites)
|
||||
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
|
||||
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
|
||||
|
||||
def test_web_change_does_not_rebuild_agent(self):
|
||||
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
|
||||
self.assertIn('Heimdall.Web.Tests', plan['suites'])
|
||||
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
|
||||
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
|
||||
|
||||
def test_solution_change_runs_all_and_docs_change_runs_none(self):
|
||||
planner = load_test_plan()
|
||||
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
|
||||
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
|
||||
solution = planner.plan(['global.json'])
|
||||
self.assertEqual(len(solution['suites']), len(planner.TESTS))
|
||||
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
|
||||
docs = planner.plan(['docs/README.md'])
|
||||
self.assertEqual(docs['suites'], [])
|
||||
self.assertEqual(docs['build_projects'], [])
|
||||
|
||||
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
|
||||
planner = load_test_plan()
|
||||
result = planner.plan(['todo.md'])
|
||||
self.assertEqual(result['mode'], 'all')
|
||||
self.assertEqual(len(result['suites']), len(planner.TESTS))
|
||||
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
|
||||
|
||||
class BuildPlanTests(unittest.TestCase):
|
||||
def test_builds_only_existing_targets_from_the_plan(self):
|
||||
builder = load_build_plan()
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
|
||||
project = root/target
|
||||
project.parent.mkdir(parents=True)
|
||||
project.write_text('<Project />')
|
||||
plan_path = root/'artifacts/tests/plan.json'
|
||||
plan_path.parent.mkdir(parents=True)
|
||||
plan_path.write_text(json.dumps({'build_projects':[target]}))
|
||||
builder.ROOT = root
|
||||
builder.PLAN = plan_path
|
||||
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
|
||||
builder.main()
|
||||
run.assert_called_once_with(
|
||||
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
|
||||
cwd=root, check=True)
|
||||
|
||||
class GpuAgentImageTests(unittest.TestCase):
|
||||
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
|
||||
@@ -163,7 +268,7 @@ class AdvisoryTests(unittest.TestCase):
|
||||
self.assertNotEqual(self.check(report), 0)
|
||||
|
||||
class ReleaseTests(unittest.TestCase):
|
||||
def execute(self, public=False):
|
||||
def execute(self):
|
||||
calls = []
|
||||
class Response(io.BytesIO):
|
||||
def __enter__(self): return self
|
||||
@@ -171,40 +276,46 @@ class ReleaseTests(unittest.TestCase):
|
||||
def fake_request(req, timeout):
|
||||
calls.append(req)
|
||||
if req.method == 'GET' and '/releases/tags/' in req.full_url:
|
||||
return Response(json.dumps({'id': 7, 'draft': not public,
|
||||
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': '1.2.3',
|
||||
'html_url': 'https://example.test/releases/7'}).encode())
|
||||
if req.method == 'GET':
|
||||
return Response(b'[{"id":8}]')
|
||||
names = ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
|
||||
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
|
||||
if req.method == 'DELETE': return Response(b'')
|
||||
return Response(b'{"id":9}')
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)/'artifacts/packages'
|
||||
directory.mkdir(parents=True)
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42'}))
|
||||
(directory/'package.tar.gz').write_bytes(b'archive')
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'1.2.3'}))
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
|
||||
(directory/name).write_bytes(b'archive')
|
||||
(directory/'agent-release-public.pem').write_bytes(b'key')
|
||||
notes = Path(temp)/'release-notes.md'
|
||||
notes.write_text('- Feature from PR #3.\n')
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(temp)
|
||||
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
|
||||
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/tags/v1.2.3','RELEASE_TOKEN':'dummy'}), \
|
||||
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
|
||||
'RELEASE_NOTES_FILE':str(notes)}), \
|
||||
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
|
||||
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
||||
try:
|
||||
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
||||
except SystemExit as result:
|
||||
if result.code != 0:
|
||||
raise
|
||||
finally:
|
||||
os.chdir(original)
|
||||
return calls
|
||||
|
||||
def test_draft_assets_use_multipart_and_delete_accepts_204(self):
|
||||
def test_complete_published_release_is_not_mutated_on_rerun(self):
|
||||
calls = self.execute()
|
||||
uploads = [x for x in calls if x.method == 'POST']
|
||||
self.assertEqual(len(uploads), 2)
|
||||
for request in uploads:
|
||||
self.assertTrue(request.get_header('Content-type').startswith('multipart/form-data; boundary='))
|
||||
self.assertIn(b'name="attachment"', request.data)
|
||||
self.assertEqual(sum(x.method == 'DELETE' for x in calls), 1)
|
||||
|
||||
def test_public_release_cannot_be_mutated(self):
|
||||
with self.assertRaisesRegex(SystemExit, 'already public'):
|
||||
self.execute(public=True)
|
||||
self.assertTrue(any('/releases/tags/1.2.3' in call.full_url for call in calls))
|
||||
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
|
||||
|
||||
class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
|
||||
@@ -212,8 +323,8 @@ class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
[sys.executable, str(ROOT/'accept-release-offline.py')],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('CPU/GPU image digests', result.stdout)
|
||||
self.assertIn('six simulated pushes', result.stdout)
|
||||
self.assertIn('installer ZIP', result.stdout)
|
||||
self.assertIn('selective Docker Hub tags', result.stdout)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
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.
|
||||
Executable
+188
@@ -0,0 +1,188 @@
|
||||
#!/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
|
||||
@@ -28,6 +28,8 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m
|
||||
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore
|
||||
```
|
||||
|
||||
For `NetworkCameraScanner` TCP probes, bound connects with a linked cancellation token and await the connect task on both success and timeout. Do not race a live `TcpClient.ConnectAsync` against `Task.Delay` and return while the connect task is still running: closing the client can surface a later socket cancellation as an unobserved task exception. Keep a focused test proving the timeout cancels and observes the pending connect, and that caller cancellation still propagates.
|
||||
|
||||
For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon.
|
||||
|
||||
This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`.
|
||||
|
||||
@@ -7,6 +7,40 @@ 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`.
|
||||
|
||||
@@ -9,13 +9,14 @@ Read `AGENTS.md`, the PIPE-01/02 Gitea issue, and `skills/heimdall-dotnet/SKILL.
|
||||
|
||||
## Current supported job types
|
||||
|
||||
- `ObjectDetection`: return every detection produced by the configured YOLO COCO model.
|
||||
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`).
|
||||
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result.
|
||||
- `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.
|
||||
- `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
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
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.
|
||||
@@ -5,6 +5,8 @@ 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
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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.
|
||||
@@ -5,12 +5,16 @@ 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 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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
@@ -5,8 +5,12 @@ 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
|
||||
@@ -32,6 +36,13 @@ 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
|
||||
@@ -48,7 +59,10 @@ cleanup() {
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
|
||||
done
|
||||
rm -rf -- "$temp_dir" || cleanup_failed=1
|
||||
# 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
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
|
||||
status=1
|
||||
@@ -79,6 +93,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 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.
|
||||
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.
|
||||
|
||||
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
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.
|
||||
@@ -7,6 +7,8 @@ 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.
|
||||
|
||||
@@ -5,6 +5,8 @@ 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.
|
||||
|
||||
@@ -5,8 +5,14 @@ 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.
|
||||
@@ -77,6 +83,7 @@ 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.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
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.
|
||||
@@ -7,6 +7,8 @@ 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).
|
||||
|
||||
@@ -14,6 +14,8 @@ 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.
|
||||
- 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.
|
||||
@@ -23,6 +25,7 @@ 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.
|
||||
- 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.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
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.
|
||||
@@ -24,8 +24,12 @@ 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 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.
|
||||
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.
|
||||
|
||||
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
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 run optional Compose files with the installation root as the current directory. They save service secrets in `optional/secrets/` and pass the root `.env` for interpolation. Therefore, Compose secret `file:` entries must use `./optional/secrets/<name>`, not `./secrets/<name>` or paths relative to `optional/`.
|
||||
|
||||
## RustFS
|
||||
|
||||
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
|
||||
- Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files.
|
||||
- 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 shell entrypoint and pass it to `--static-auth-secret`. Do not print the value.
|
||||
- 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.
|
||||
- Set `COTURN_EXTERNAL_IP` only when NAT requires coturn to advertise an explicit public address. The operator must forward the listener and relay range through firewalls/NAT.
|
||||
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run both services in one uniquely named disposable Compose project using generated secrets and unique loopback listener ports. Use `docker compose --project-directory <install-root> --env-file <generated-env> -f <source-compose> -p <project> config` to prove the installer root resolves `optional/secrets/` correctly. Start RustFS and coturn; verify RustFS `/health` and S3 authentication and coturn startup plus a TURN REST authenticated allocation from a test client if available. State separately whether the real TURN allocation succeeded. Tear down only that project, verify its containers/volumes/networks are absent, and keep upstream images. No local images should be built by this recipe.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: penpot-design-sync
|
||||
description: Open Heimdall's connected Penpot workspace through Orca, authenticate safely, update design source alongside UI work, and verify the saved frames.
|
||||
---
|
||||
|
||||
# Heimdall Penpot design sync
|
||||
|
||||
Heimdall's connected Penpot file is part of the UI source of truth. Whenever a change affects a screen, interaction, responsive layout, installer, or visible state, update the corresponding Penpot design in the same change. Do not leave a known implementation/design mismatch for a later task. When a UI change does not affect the design, state why in the Gitea issue evidence.
|
||||
|
||||
## Required entry path: Orca browser
|
||||
|
||||
1. Read the Orca `orca-cli` and `orca-computer-use` skills when not already loaded. Use the Orca CLI to list/open tabs and inspect browser state; use computer-use only when a visible GUI action is necessary.
|
||||
2. Open the Penpot site in the Orca browser and sign in there using credentials already present in the environment or Orca-managed account. Never echo, log, paste into issue comments, or otherwise expose credential values. Do not try public Penpot Cloud as a substitute when Heimdall uses its connected self-hosted Penpot instance.
|
||||
3. Confirm the signed-in team, Heimdall file, and target page before editing. The current Heimdall file is `aadb42b1-1e8d-8014-8008-7dc15de6e3ff`, team `073c6639-4451-8006-8008-e66329727382`. Resolve the current page from the file; do not assume page IDs remain stable.
|
||||
4. Use Penpot MCP design operations only after Orca has opened the authenticated workspace and the correct file. The browser is the required way to establish and verify the user session, even when MCP is used for precise shape edits.
|
||||
5. If login, workspace access, or the connected Penpot tool fails, diagnose the actual browser/session path first. Do not claim that the design was updated. Continue independent code work when possible, then report the concrete access blocker and leave the issue open.
|
||||
|
||||
## Design update workflow
|
||||
|
||||
1. Read `AGENTS.md`, the focused UI skill (for the site Agent installer, `site-agent-installer-ui/SKILL.md`), the UI implementation, and `docs/ui-pages.md`. Review the current Penpot page in Orca before changing it.
|
||||
2. Compare the shipped behavior with the existing frames. Preserve Heimdall's established visual language and component patterns while representing every meaningful state introduced by the change. Cover loading, success, error/unavailable, permissions, and empty states when they are relevant.
|
||||
3. For responsive UI, represent desktop and narrow/mobile widths. For installers, show platform and method selection, optional configuration, copyable commands, and unavailable signed-release/image states. Keep fake credentials, real tokens, private URLs, and customer data out of design content.
|
||||
4. Update the existing relevant frame in place where practical. Rename frames so their platform, viewport, and state are clear. Remove obsolete competing mockups or stale secret-bearing examples when they would mislead implementers; preserve unrelated page content.
|
||||
5. Match text, labels, command behavior, option availability, selected states, and copy affordances to the implementation and localization. Do not introduce unsupported options simply to imitate another product. Keep `docs/ui-pages.md` consistent when it describes the same UI.
|
||||
6. Save/commit the design through Penpot, then verify the resulting frames in the Orca browser. Inspect the actual canvas at a useful zoom and check hierarchy, clipping, responsive composition, and stale content. A successful MCP response alone is not visual acceptance.
|
||||
7. Record the Penpot file/page link, frame names/states changed, and visual review outcome in the linked Gitea issue. Distinguish verified Penpot design work from code tests and real release/deployment evidence.
|
||||
|
||||
## Installer design reference
|
||||
|
||||
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, digest-pinned Docker image requirements, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
|
||||
|
||||
## Acceptance evidence
|
||||
|
||||
- Orca browser opened the self-hosted Penpot workspace and authenticated session was confirmed without exposing credentials.
|
||||
- Correct Heimdall file and target page were confirmed before edits.
|
||||
- Changed frames were inspected visually in the browser after the edit; list their names/states and link the file/page in the Gitea issue.
|
||||
- Design and shipped UI/docs agree on supported choices, labels, states, and interaction behavior.
|
||||
- If an external Penpot outage prevents completion, record the exact blocked step in Gitea and do not mark the design acceptance complete.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,22 +1,41 @@
|
||||
---
|
||||
name: release-automation
|
||||
description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests.
|
||||
description: Build and validate changed Heimdall images on pushes, then publish versioned Docker Hub images and signed installer assets for semver tags.
|
||||
---
|
||||
|
||||
# Heimdall tagged release workflow
|
||||
# Heimdall build and release workflow
|
||||
|
||||
Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gitea.py`, release signing, Docker image tags, or the Gitea release job.
|
||||
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.
|
||||
|
||||
## Release invariants
|
||||
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.
|
||||
|
||||
- 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.
|
||||
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`, 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 checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
|
||||
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
|
||||
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), verifies the Gitea SHA-256 asset digest, downloads that version's ZIP, and runs its version-pinned script. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
|
||||
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
|
||||
- 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.
|
||||
|
||||
## Offline end-to-end acceptance
|
||||
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. The acceptance script invokes the real `package.sh` and `publish.sh`, but creates disposable ECDSA P-256 credentials and substitutes both publication boundaries: a local TLS Gitea API double records only draft release/assets, and a fake Docker CLI records tags and simulates registry digests. It verifies archive hashes, manifest signature, checksums, asset uploads, and expected image tags/digests. The fake CLI must never call a registry, and the API server must bind only to loopback, suppress request logging, and reject non-synthetic authorization.
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
|
||||
|
||||
This simulation proves local packaging/signing/orchestration only. It does not prove the Actions secrets, runner network, Docker Hub/Gitea behavior, native Agent installation, or rollback. Keep the focused Gitea release issue open until a real tagged run and the relevant host validation have succeeded.
|
||||
For 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.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: signalr-client-lifecycle
|
||||
description: Avoid blocking SignalR client teardown in Heimdall Blazor components and services.
|
||||
---
|
||||
|
||||
# Heimdall SignalR client lifecycle
|
||||
|
||||
`NotificationsHubClient` is scoped to a Blazor circuit and owns a `HubConnection`. Components that use it should implement `IAsyncDisposable`, unsubscribe their event handlers, then await `Hub.DisposeAsync()`.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Do not call `.Wait()`, `.Result`, or `GetAwaiter().GetResult()` on SignalR stop/dispose operations. Network shutdown can block a renderer or request thread.
|
||||
- Centralize teardown in one asynchronous helper. Atomically detach the owned connection before awaiting shutdown so repeated disposal cannot dispose it twice.
|
||||
- `DisposeAsync()` awaits `StopAsync` and `DisposeAsync`, handling shutdown failures independently so failed stop still attempts resource disposal.
|
||||
- If compatibility requires synchronous `IDisposable`, it must return without blocking and start best-effort asynchronous cleanup. Keep `GC.SuppressFinalize(this)` on both dispose paths.
|
||||
- Log cleanup failures at debug level without access tokens, URLs containing credentials, or message payloads.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Build `src/Heimdall.Web/Heimdall.Web.csproj` with the SDK pinned by `global.json`; do not suppress analyzer warnings for blocking calls.
|
||||
2. Verify the component unsubscribes handlers and awaits async disposal.
|
||||
3. Run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique generated credentials, ports, project, and image tag; check `/healthz` and verify cleanup of project resources and that exact tag.
|
||||
4. Treat production GlitchTip recurrence as external evidence: local build and Compose do not prove the deployed client has stopped emitting events.
|
||||
|
||||
See Gitea issue [#233](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/233) for the current incident evidence.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: site-agent-installer-ui
|
||||
description: Maintain and accept the Heimdall site Agent installer panel using Pangolin's platform/method/configuration/commands interaction pattern.
|
||||
---
|
||||
|
||||
# Site Agent installer UI
|
||||
|
||||
Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.razor`. Its interaction model follows Pangolin's `OptionSelect` and `CopyTextBox`: platform tiles, platform-specific method tiles, optional configuration, then titled command blocks with an inline copy control. Keep `docs/ui-pages.md` and the connected Penpot installer frames aligned with the shipped flow; cover desktop and narrow/mobile widths plus the signed-release-unavailable state. Always open Penpot and authenticate through the Orca browser before editing the design; follow [penpot-design-sync/SKILL.md](../penpot-design-sync/SKILL.md) for the full workflow and evidence requirements.
|
||||
|
||||
## Project-specific rules
|
||||
|
||||
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
|
||||
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
|
||||
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require a digest-pinned image reference and update key. Preserve these gates so the panel never offers a nonfunctional installer.
|
||||
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
|
||||
- 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.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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,6 +246,11 @@ 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,6 +11,7 @@ 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;
|
||||
@@ -184,13 +185,18 @@ public sealed class AnalysisJobPollingService : BackgroundService
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<DetectionResult> SelectDetections(
|
||||
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
|
||||
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections)
|
||||
{
|
||||
AnalysisJobType.ObjectDetection => detections,
|
||||
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
|
||||
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
|
||||
_ => [],
|
||||
};
|
||||
IEnumerable<DetectionResult> selected = jobType switch
|
||||
{
|
||||
AnalysisJobType.ObjectDetection => detections,
|
||||
AnalysisJobType.PersonDetection => detections.Where(IsPerson),
|
||||
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle),
|
||||
_ => [],
|
||||
};
|
||||
|
||||
return selected.Take(MaxDetectionsPerResult).ToArray();
|
||||
}
|
||||
|
||||
private static bool IsPerson(DetectionResult detection) =>
|
||||
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
@@ -162,6 +162,7 @@ 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]);
|
||||
@@ -292,6 +293,7 @@ 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;
|
||||
@@ -312,6 +314,7 @@ 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; }
|
||||
@@ -350,6 +353,7 @@ 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; } = [];
|
||||
|
||||
@@ -614,17 +614,39 @@ public NetworkCameraScanner(
|
||||
var tasks = CameraPorts.Select(async port =>
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
|
||||
var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
|
||||
if (completed == connectTask && client.Connected)
|
||||
if (await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(IPAddress.Parse(ip), port, token), PortTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
open.Add(port);
|
||||
client.Close();
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
return [.. open.Order()];
|
||||
}
|
||||
|
||||
internal static async Task<bool> ConnectWithTimeoutAsync(
|
||||
Func<CancellationToken, ValueTask> connectAsync,
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutSource.CancelAfter(timeout);
|
||||
|
||||
try
|
||||
{
|
||||
await connectAsync(timeoutSource.Token).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<HttpProbe?> ProbeHttpAsync(string ip, int port, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -1104,9 +1126,9 @@ public NetworkCameraScanner(
|
||||
{
|
||||
var uri = new Uri(url);
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(uri.Host, uri.Port, ct).AsTask();
|
||||
var connected = await Task.WhenAny(connectTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false);
|
||||
if (connected != connectTask || !client.Connected)
|
||||
if (!await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(uri.Host, uri.Port, token), RtspTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
return false;
|
||||
|
||||
var options = $"OPTIONS rtsp://{uri.Host}:{uri.Port}/ RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: HeimdallAgent/1.0\r\n\r\n";
|
||||
@@ -1188,11 +1210,10 @@ public NetworkCameraScanner(
|
||||
var password = credentials.Length > 1 ? Uri.UnescapeDataString(credentials[1]) : "";
|
||||
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(host, port, ct).AsTask();
|
||||
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
||||
if (connected != connectTask || !client.Connected)
|
||||
if (!await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(host, port, token), DvripTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
return false;
|
||||
await connectTask.ConfigureAwait(false);
|
||||
|
||||
var stream = client.GetStream();
|
||||
|
||||
@@ -1315,11 +1336,10 @@ public NetworkCameraScanner(
|
||||
var port = uri.IsDefaultPort ? 1935 : uri.Port;
|
||||
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
||||
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
||||
if (connected != connectTask || !client.Connected)
|
||||
if (!await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
return false;
|
||||
await connectTask.ConfigureAwait(false);
|
||||
|
||||
var stream = client.GetStream();
|
||||
|
||||
@@ -1370,11 +1390,10 @@ public NetworkCameraScanner(
|
||||
var path = string.IsNullOrEmpty(uri.AbsolutePath) ? "/bubble/live?ch=0&stream=0" : uri.PathAndQuery;
|
||||
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
||||
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
||||
if (connected != connectTask || !client.Connected)
|
||||
if (!await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
return false;
|
||||
await connectTask.ConfigureAwait(false);
|
||||
|
||||
var stream = client.GetStream();
|
||||
|
||||
@@ -1431,11 +1450,10 @@ public NetworkCameraScanner(
|
||||
var port = uri.IsDefaultPort ? 8080 : uri.Port;
|
||||
|
||||
using var client = new TcpClient();
|
||||
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
||||
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
||||
if (connected != connectTask || !client.Connected)
|
||||
if (!await ConnectWithTimeoutAsync(
|
||||
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
|
||||
.ConfigureAwait(false))
|
||||
return false;
|
||||
await connectTask.ConfigureAwait(false);
|
||||
|
||||
var stream = client.GetStream();
|
||||
var request = $"GET /accessories HTTP/1.1\r\nHost: {uri.Host}\r\n\r\n";
|
||||
|
||||
@@ -82,6 +82,10 @@ 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
IQueryable<Camera> ApplyCameraFilter(IQueryable<Camera> query, Guid userId);
|
||||
Task<IQueryable<Camera>> ApplyCameraFilterAsync(IQueryable<Camera> query, Guid userId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -11,7 +11,16 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
|
||||
{
|
||||
builder.ToTable("UserCameraAccesses");
|
||||
|
||||
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
|
||||
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.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
|
||||
Generated
+2906
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,79 @@
|
||||
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,30 +2018,39 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("CameraId")
|
||||
b.Property<Guid?>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("UserId", "SiteId", "CameraId");
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
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,9 +45,10 @@ 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);
|
||||
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled, cancellationToken);
|
||||
|
||||
if (apiKeyEntity is null)
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
@@ -67,13 +68,22 @@ 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(Context.RequestAborted);
|
||||
.Select(a => a.Id).Take(2).ToListAsync(cancellationToken);
|
||||
if (agents.Count != 1 || !apiKeyEntity.SiteId.HasValue)
|
||||
return AuthenticateResult.Fail("API key is not bound to one active agent");
|
||||
|
||||
apiKeyEntity.MarkUsed();
|
||||
// Persist LastUsedAt update
|
||||
await db.SaveChangesAsync();
|
||||
// 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);
|
||||
|
||||
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 ApplyCameraFilter(context.Cameras, userId).AnyAsync(c => c.Id == cameraId, ct);
|
||||
=> await (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).AnyAsync(c => c.Id == cameraId, 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>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
=> await (await ApplyCameraFilterAsync(context.Cameras, userId, ct)).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 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>> 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 async Task<List<Guid>> GetAccessibleSiteIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
if (IsAdmin(userId)) return await context.Sites.Select(s => s.Id).ToListAsync(ct);
|
||||
var cameraSites = ApplyCameraFilter(context.Cameras, userId).Select(c => c.SiteId);
|
||||
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);
|
||||
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 IQueryable<Camera> ApplyCameraFilter(IQueryable<Camera> query, Guid userId)
|
||||
public async Task<IQueryable<Camera>> ApplyCameraFilterAsync(IQueryable<Camera> query, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
if (userId == Guid.Empty) return query.Where(c => false);
|
||||
if (IsAdmin(userId)) return query;
|
||||
if (await IsAdminAsync(userId, ct)) 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,6 +68,8 @@ public class CameraAccessService(IApplicationDbContext context, IIdentityPersist
|
||||
context.UserGroups.Any(m => m.UserId == userId && m.GroupId == a.GroupId)));
|
||||
}
|
||||
|
||||
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));
|
||||
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);
|
||||
}
|
||||
@@ -10,4 +10,8 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Heimdall.Agent.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -52,44 +52,46 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
|
||||
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
|
||||
|
||||
// Try to receive within timeout
|
||||
var receiveTask = udpClient.ReceiveAsync(ct).AsTask();
|
||||
var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false);
|
||||
|
||||
if (completedTask != receiveTask)
|
||||
using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
receiveCts.CancelAfter(options.Timeout);
|
||||
var receiveTask = udpClient.ReceiveAsync(receiveCts.Token).AsTask();
|
||||
try
|
||||
{
|
||||
if (retry < options.MaxRetries)
|
||||
continue; // retry
|
||||
break; // timeout, try next service type
|
||||
}
|
||||
var result = await receiveTask.ConfigureAwait(false);
|
||||
var response = MdnsResponse.Parse(result.Buffer);
|
||||
|
||||
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 (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)
|
||||
{
|
||||
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,
|
||||
HomeKitInfo = ParseHomeKitInfo(target, response)
|
||||
ResolvedAddress = response.Address
|
||||
};
|
||||
}
|
||||
|
||||
return new MdnsProbeResult
|
||||
{
|
||||
Target = target,
|
||||
ServiceType = response.Name,
|
||||
InstanceName = response.PtrName,
|
||||
HostName = response.Address?.ToString(),
|
||||
ResolvedAddress = response.Address
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
if (retry < options.MaxRetries)
|
||||
continue; // timeout, retry
|
||||
break; // timeout, try next service type
|
||||
}
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
||||
@@ -167,17 +169,29 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
|
||||
|
||||
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
|
||||
{
|
||||
var receiveTask = udp.ReceiveAsync(ct).AsTask();
|
||||
var completed = await Task.WhenAny(receiveTask, Task.Delay(options.ListenWindow, ct)).ConfigureAwait(false);
|
||||
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);
|
||||
|
||||
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);
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Build devices from collected replies
|
||||
@@ -201,6 +215,18 @@ 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,6 +59,10 @@
|
||||
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never"
|
||||
Breakpoint="Breakpoint.Sm" MiniVariantWidth="64px" @bind-MiniVariant="_miniVariant">
|
||||
<MudNavMenu>
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="px-4 py-2" data-testid="server-version">
|
||||
Version @(_serverVersion ?? "—")
|
||||
</MudText>
|
||||
<MudDivider />
|
||||
@if (Auth.IsLoggedIn)
|
||||
{
|
||||
<MudText Typo="Typo.overline" Color="Color.Secondary" Class="px-4 py-2">@Text["Navigation"]</MudText>
|
||||
@@ -140,6 +144,7 @@
|
||||
private bool _miniVariant;
|
||||
private bool _darkMode = true;
|
||||
private string _searchQuery = "";
|
||||
private string? _serverVersion;
|
||||
|
||||
/// <summary>Sous-menu « Gestion des utilisateurs » : replié par défaut,
|
||||
/// déplié automatiquement quand on est déjà sur une de ses pages.</summary>
|
||||
@@ -156,6 +161,13 @@
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var version = await Api.GetServerVersionAsync();
|
||||
_serverVersion = version?.Version;
|
||||
}
|
||||
catch { /* Keep the navigation usable while version metadata is unavailable. */ }
|
||||
|
||||
if (!Auth.IsLoggedIn) return;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -902,10 +902,17 @@ 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 @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
|
||||
<MudSelect T="Guid?" @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
|
||||
@foreach (var site in _availableSites)
|
||||
{
|
||||
<MudSelectItem Value="@site.Id">@site.Name</MudSelectItem>
|
||||
<MudSelectItem T="Guid?" Value="@((Guid?)site.Id)">@site.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
@@ -109,10 +109,10 @@
|
||||
|
||||
@if (_newAccessType == AccessType.CameraSpecific)
|
||||
{
|
||||
<MudSelect @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
|
||||
<MudSelect T="Guid?" @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
|
||||
@foreach (var camera in _availableCameras)
|
||||
{
|
||||
<MudSelectItem Value="@camera.Id">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
|
||||
<MudSelectItem T="Guid?" Value="@((Guid?)camera.Id)">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
}
|
||||
|
||||
@@ -372,14 +372,24 @@ else
|
||||
_eventRecordingEnabled = _camera.EventRecordingEnabled;
|
||||
}
|
||||
}
|
||||
catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex))
|
||||
{
|
||||
// Le filtre d'accès renvoie 403 pour masquer une caméra absente ou non accessible.
|
||||
}
|
||||
catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
|
||||
await LoadEventsAsync();
|
||||
await LoadRecordingsAsync();
|
||||
await LoadLatestSnapshotAsync();
|
||||
if (_camera is not null)
|
||||
{
|
||||
await LoadEventsAsync();
|
||||
await LoadRecordingsAsync();
|
||||
await LoadLatestSnapshotAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsMissingOrHiddenResource(HttpRequestException exception) =>
|
||||
exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden;
|
||||
|
||||
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
|
||||
|
||||
// L'auto-refresh démarre après le premier rendu : une boucle infinie
|
||||
@@ -389,7 +399,7 @@ else
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender && !_autoRefreshStarted)
|
||||
if (firstRender && !_autoRefreshStarted && _camera is not null)
|
||||
{
|
||||
_autoRefreshStarted = true;
|
||||
await StartAutoRefresh();
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
@Text["Dashboard"]
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body1" Class="mb-2">
|
||||
@Text["WelcomeUser"], <strong>@Auth.User?.DisplayName</strong>
|
||||
@Text["WelcomeUser"] <strong>@Auth.User?.DisplayName</strong>
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Update" Size="Size.Small" Class="mr-1" />
|
||||
@@ -282,6 +282,8 @@
|
||||
// infinie awaitée dans OnInitializedAsync bloque le rendu initial
|
||||
// (SSR/prerender attend la fin du cycle de vie) → page lente.
|
||||
private CancellationTokenSource? _refreshCts;
|
||||
private Task? _refreshTask;
|
||||
private readonly object _refreshLock = new();
|
||||
private bool _disposed;
|
||||
private bool _autoRefreshStarted;
|
||||
|
||||
@@ -290,18 +292,24 @@
|
||||
if (firstRender && !_autoRefreshStarted)
|
||||
{
|
||||
_autoRefreshStarted = true;
|
||||
await StartAutoRefresh();
|
||||
lock (_refreshLock)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
_refreshCts = new CancellationTokenSource();
|
||||
_refreshTask = RunAutoRefreshAsync(_refreshCts.Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartAutoRefresh()
|
||||
private async Task RunAutoRefreshAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_refreshCts = new CancellationTokenSource();
|
||||
try
|
||||
{
|
||||
while (!_refreshCts.Token.IsCancellationRequested)
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), _refreshCts.Token);
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), cancellationToken);
|
||||
if (_disposed) return;
|
||||
// Rafraîchit uniquement la section agents (léger) : les stats
|
||||
// globales restent au refresh manuel pour éviter le flash.
|
||||
@@ -311,6 +319,10 @@
|
||||
var agentsPage = await Api.GetAllAgentsAsync(1, 5);
|
||||
_agents = agentsPage?.Items?.ToList();
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch { /* keep last state */ }
|
||||
finally
|
||||
{
|
||||
@@ -320,6 +332,7 @@
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { /* arrêt volontaire */ }
|
||||
catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested) { /* arrêt concurrent */ }
|
||||
}
|
||||
|
||||
private async Task LoadData()
|
||||
@@ -401,9 +414,29 @@
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
CancellationTokenSource? refreshCts;
|
||||
lock (_refreshLock)
|
||||
{
|
||||
_disposed = true;
|
||||
refreshCts = _refreshCts;
|
||||
_refreshCts = null;
|
||||
}
|
||||
Language.LanguageChanged -= OnLanguageChanged;
|
||||
_refreshCts?.Cancel();
|
||||
_refreshCts?.Dispose();
|
||||
if (refreshCts is not null)
|
||||
{
|
||||
try { refreshCts.Cancel(); }
|
||||
catch (ObjectDisposedException) { /* shutdown already completed */ }
|
||||
_ = DisposeRefreshAsync(refreshCts, _refreshTask);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DisposeRefreshAsync(CancellationTokenSource refreshCts, Task? refreshTask)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (refreshTask is not null) await refreshTask;
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
finally { refreshCts.Dispose(); }
|
||||
}
|
||||
}
|
||||
@@ -131,19 +131,19 @@
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
Logger.LogInformation("Login attempt for email: {Email}", _email);
|
||||
Logger.LogInformation("Login attempt");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await Api.LoginAsync(_email, _password);
|
||||
if (result is null)
|
||||
{
|
||||
Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email);
|
||||
Logger.LogWarning("Login failed: invalid credentials");
|
||||
_errorMessage = Text["LoginPage_InvalidCredentials"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa);
|
||||
Logger.LogInformation("Login succeeded. Requires 2FA: {Requires2fa}", result.Requires2fa);
|
||||
|
||||
// Check if 2FA is required
|
||||
if (result.Requires2fa)
|
||||
@@ -152,7 +152,7 @@
|
||||
_password = "";
|
||||
_requires2fa = true;
|
||||
_loading = false;
|
||||
Logger.LogInformation("2FA required for {Email}", _email);
|
||||
Logger.LogInformation("2FA required");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Login error for {Email}", _email);
|
||||
Logger.LogError("Login flow failed (error type {ErrorType})", ex.GetType().Name);
|
||||
_errorMessage = UiErrors.OperationFailed();
|
||||
}
|
||||
finally { _loading = false; }
|
||||
@@ -170,31 +170,31 @@
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_twoFactorCode))
|
||||
{
|
||||
Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email);
|
||||
Logger.LogWarning("2FA verification attempted with an empty code");
|
||||
_errorMessage = Text["LoginPage_TwoFactorCodeRequired"];
|
||||
return;
|
||||
}
|
||||
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
Logger.LogInformation("2FA verification attempt for {Email}", _email);
|
||||
Logger.LogInformation("2FA verification attempt");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim());
|
||||
if (result is null)
|
||||
{
|
||||
Logger.LogWarning("2FA verification failed for {Email}", _email);
|
||||
Logger.LogWarning("2FA verification failed");
|
||||
_errorMessage = Text["LoginPage_InvalidTwoFactorCode"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("2FA verification successful for {Email}", _email);
|
||||
Logger.LogInformation("2FA verification succeeded");
|
||||
await CompleteAuthAsync(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "2FA verification error for {Email}", _email);
|
||||
Logger.LogError("2FA verification flow failed (error type {ErrorType})", ex.GetType().Name);
|
||||
_errorMessage = UiErrors.OperationFailed();
|
||||
}
|
||||
finally { _loading = false; }
|
||||
@@ -202,7 +202,7 @@
|
||||
|
||||
private async Task CompleteAuthAsync(AuthResponse result)
|
||||
{
|
||||
Logger.LogInformation("Completing authentication for {Email}", _email);
|
||||
Logger.LogInformation("Completing authentication");
|
||||
|
||||
// Update Blazor-level auth state
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
@@ -211,23 +211,24 @@
|
||||
var cookieOk = true;
|
||||
if (!string.IsNullOrEmpty(result.AccessToken))
|
||||
{
|
||||
Logger.LogDebug("Creating auth cookie for {Email}", _email);
|
||||
Logger.LogDebug("Creating auth cookie");
|
||||
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
|
||||
Logger,
|
||||
AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("No access token in auth response for {Email}", _email);
|
||||
Logger.LogWarning("No access token in auth response");
|
||||
}
|
||||
|
||||
if (!cookieOk)
|
||||
{
|
||||
Logger.LogError("Failed to create auth cookie for {Email}", _email);
|
||||
Logger.LogError("Failed to create auth cookie");
|
||||
_errorMessage = Text["LoginPage_AuthSessionFailed"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl);
|
||||
Logger.LogInformation("Authentication completed successfully, redirecting to {ReturnUrl}", _returnUrl);
|
||||
Snackbar.Add(Text["LoginPage_SignInSucceeded"], Severity.Success);
|
||||
Navigation.NavigateTo(_returnUrl);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
@page "/notifications"
|
||||
@using Heimdall.Application.DTOs
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject NotificationsHubClient Hub
|
||||
@inject UiText Text
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h1" Class="mb-4">@Text["NotificationsPage_Title"]</MudText>
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressLinear Indeterminate="true" />
|
||||
}
|
||||
else if (_failed)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">@Text["NotificationsPage_Failed"]</MudAlert>
|
||||
}
|
||||
else if (_items.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info">@Text["NotificationsPage_Empty"]</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="d-flex justify-end mb-3">
|
||||
<MudButton Variant="Variant.Outlined" Disabled="@(!_items.Any(x => !x.IsRead))" OnClick="MarkAllReadAsync">
|
||||
@Text["NotificationsPage_MarkAllRead"]
|
||||
</MudButton>
|
||||
</div>
|
||||
@foreach (var item in _items)
|
||||
{
|
||||
<MudPaper Class="pa-4 mb-2" Elevation="1">
|
||||
<div class="d-flex justify-space-between align-start">
|
||||
<div>
|
||||
<MudText Typo="Typo.h6">@item.Title</MudText>
|
||||
<MudText>@item.Message</MudText>
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">@item.CreatedAt.ToLocalTime().ToString("g")</MudText>
|
||||
</div>
|
||||
@if (!item.IsRead)
|
||||
{
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => MarkReadAsync(item.Id))">@Text["NotificationsPage_MarkRead"]</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudPaper>
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
private List<NotificationDto> _items = [];
|
||||
private bool _loading = true;
|
||||
private bool _failed;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadAsync();
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_failed = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetNotificationsAsync();
|
||||
_items = result?.Items.ToList() ?? [];
|
||||
_failed = result is null;
|
||||
}
|
||||
catch (HttpRequestException) { _failed = true; }
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private async Task MarkReadAsync(Guid id)
|
||||
{
|
||||
if (await Api.MarkNotificationAsReadAsync(id))
|
||||
{
|
||||
await LoadAsync();
|
||||
await Hub.RefreshUnreadCountAsync();
|
||||
}
|
||||
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
|
||||
}
|
||||
|
||||
private async Task MarkAllReadAsync()
|
||||
{
|
||||
if (await Api.MarkAllNotificationsAsReadAsync())
|
||||
{
|
||||
await LoadAsync();
|
||||
await Hub.RefreshUnreadCountAsync();
|
||||
}
|
||||
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
|
||||
}
|
||||
}
|
||||
@@ -309,12 +309,19 @@ else
|
||||
{
|
||||
_person = await Api.GetPersonAsync(Id);
|
||||
}
|
||||
catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
// La vue dédiée affiche l'état introuvable sans lancer les lectures associées.
|
||||
}
|
||||
catch { Snackbar.Add(Text["PersonDetailPage_OperationFailed"], Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
|
||||
await LoadFaces();
|
||||
await LoadVehicles();
|
||||
await LoadEvents();
|
||||
if (_person is not null)
|
||||
{
|
||||
await LoadFaces();
|
||||
await LoadVehicles();
|
||||
await LoadEvents();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadFaces()
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
@inject ISnackbar Snackbar
|
||||
@inject HeimdallAuthStateProvider AuthProvider
|
||||
@inject IJSRuntime JS
|
||||
@inject Microsoft.Extensions.Logging.ILogger<Profile> Logger
|
||||
|
||||
<MudText Typo="Typo.h1" Class="mb-6">
|
||||
<i class="fas fa-user-circle mr-2"></i>
|
||||
@@ -470,7 +471,7 @@ else if (_profile is not null)
|
||||
return;
|
||||
}
|
||||
await AuthProvider.NotifyLoginAsync(renewedSession);
|
||||
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
if (!await AuthHelper.SignInAsync(JS, Logger, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
@inject HeimdallAuthStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
@inject IJSRuntime JsRuntime
|
||||
@inject Microsoft.Extensions.Logging.ILogger<Setup> Logger
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
@@ -96,7 +97,7 @@
|
||||
}
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
var cookieOk = !string.IsNullOrEmpty(result.AccessToken) && await AuthHelper.SignInAsync(
|
||||
JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
JsRuntime, Logger, AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
if (!cookieOk)
|
||||
{
|
||||
_error = Text["SetupAdmin_AutoLoginFailed"];
|
||||
|
||||
@@ -253,7 +253,6 @@ else
|
||||
private bool _generating;
|
||||
private string? _generatedToken;
|
||||
private DateTime _tokenExpiresAt;
|
||||
private string _dockerComposeSnippet = "";
|
||||
|
||||
// ── Identifiants caméras ──────────────────────────────────────
|
||||
private List<SiteCredentialItem> _credentials = [];
|
||||
@@ -385,15 +384,12 @@ else
|
||||
}
|
||||
_generatedToken = result.Token;
|
||||
_tokenExpiresAt = result.ExpiresAt;
|
||||
_dockerComposeSnippet = GenerateDockerComposeSnippet(_generatedToken);
|
||||
Snackbar.Add(Text["SiteDetail_TokenGenerated"], Severity.Warning);
|
||||
}
|
||||
catch { Snackbar.Add(Text["SiteDetail_OperationFailed"], Severity.Error); }
|
||||
finally { _generating = false; }
|
||||
}
|
||||
|
||||
private string GenerateDockerComposeSnippet(string token) => "";
|
||||
|
||||
/// <summary>Origin exposed by the browser that operators use to reach Central.</summary>
|
||||
private string CentralUrl => Nav.BaseUri.TrimEnd('/');
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject ISnackbar Snackbar
|
||||
@inject UiText Text
|
||||
@inject UiLanguageService Language
|
||||
@@ -17,9 +18,12 @@
|
||||
</MudText>
|
||||
|
||||
<div class="d-flex justify-space-between align-center mb-4">
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> @Text["SitesPage_NewSite"]
|
||||
</MudButton>
|
||||
@if (CanCreateSite)
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="OpenCreate">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> @Text["SitesPage_NewSite"]
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
@@ -75,6 +79,8 @@ else
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@if (CanCreateSite)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">@Text["SitesPage_NewSite"]</MudText></TitleContent>
|
||||
@@ -112,6 +118,7 @@ else
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Confirm delete dialog ───────────────────────────────── *@
|
||||
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
|
||||
@@ -254,6 +261,13 @@ else
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
private bool CanCreateSite => Auth.HasPermission("Site.Write");
|
||||
|
||||
private void OpenCreate()
|
||||
{
|
||||
if (CanCreateSite)
|
||||
_showCreate = true;
|
||||
}
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
</MudText>
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-4 mb-4">
|
||||
<MudToolBar>
|
||||
<div class="snapshot-filters">
|
||||
<MudTextField @bind-Value="_search" Label="@Text["SnapshotsPage_SearchLabel"]" Variant="Variant.Outlined"
|
||||
Class="mr-2" style="min-width:300px;" Placeholder="@Text["SnapshotsPage_SearchPlaceholder"]" />
|
||||
<MudSelect T="string" @bind-Value="_type" Label="@Text["SnapshotsPage_Type"]" Variant="Variant.Outlined" Clearable="true" Class="mr-2" Style="min-width:180px;">
|
||||
Class="snapshot-filter-control" Style="width:100%;" Placeholder="@Text["SnapshotsPage_SearchPlaceholder"]" />
|
||||
<MudSelect T="string" @bind-Value="_type" Label="@Text["SnapshotsPage_Type"]" Variant="Variant.Outlined" Clearable="true" Class="snapshot-filter-control" Style="width:100%;">
|
||||
<MudSelectItem Value="@nameof(EventType.MotionDetected)">@Text["SnapshotsPage_Motion"]</MudSelectItem>
|
||||
<MudSelectItem Value="@nameof(EventType.PersonDetected)">@Text["SnapshotsPage_Person"]</MudSelectItem>
|
||||
<MudSelectItem Value="@nameof(EventType.VehicleDetected)">@Text["SnapshotsPage_Vehicle"]</MudSelectItem>
|
||||
@@ -31,9 +31,32 @@
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@ApplyFilters">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Search" Class="mr-1" Size="Size.Small" /> @Text["SnapshotsPage_Load"]
|
||||
</MudButton>
|
||||
</MudToolBar>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<style>
|
||||
.snapshot-filters {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.snapshot-filter-control {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@@media (max-width: 600px) {
|
||||
.snapshot-filters {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.snapshot-filters button {
|
||||
justify-self: start;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Class="mt-8" />
|
||||
|
||||
@@ -1,28 +1,36 @@
|
||||
@namespace Heimdall.Web.Components.Settings
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
@inject Heimdall.Web.Services.UiText Text
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
|
||||
<MudText Typo="Typo.h6" Class="mb-2"><i class="fas fa-arrows-rotate mr-2"></i>Mises à jour</MudText>
|
||||
<MudText Typo="Typo.h6" Class="mb-2"><i class="fas fa-arrows-rotate mr-2"></i>@Text["UpdatesSettings_Title"]</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
|
||||
Source globale des versions et des manifestes d’images Heimdall. L’URL doit être une adresse HTTPS absolue.
|
||||
@Text["UpdatesSettings_Description"]
|
||||
</MudText>
|
||||
<MudTextField T="string" Label="API de publication" Variant="Variant.Outlined"
|
||||
<MudTextField T="string" Label="@Text["UpdatesSettings_ForgeUrl"]" Variant="Variant.Outlined"
|
||||
Value="@_url" ValueChanged="SaveUrlAsync"
|
||||
Placeholder="https://forge.example/api/v1/repos/owner/repo/releases/latest" />
|
||||
Placeholder="@Text["UpdatesSettings_ForgeUrlPlaceholder"]" />
|
||||
<MudTextField T="string" Label="@Text["UpdatesSettings_ReleaseApi"]" Variant="Variant.Outlined"
|
||||
Class="mt-3" Value="@ReleaseApiUrl" ReadOnly="true" />
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">
|
||||
@Text["UpdatesSettings_ReleaseApiReadOnly"]
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
private const string SettingKey = "updates.releaseapiurl";
|
||||
private List<AppSettingItem> _settings = [];
|
||||
private string _url = string.Empty;
|
||||
private string ReleaseApiUrl => Heimdall.Web.Services.ForgeReleaseApiAddress.BuildReleaseApiUrl(_url)
|
||||
?? Text["UpdatesSettings_ReleaseApiInvalid"];
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_settings = await Api.GetSettingsAsync();
|
||||
_url = _settings.FirstOrDefault(s => s.Key.Equals(SettingKey, StringComparison.OrdinalIgnoreCase))?.Value ?? string.Empty;
|
||||
_url = _settings.FirstOrDefault(s => s.Key.Equals(
|
||||
Heimdall.Web.Services.ForgeReleaseApiAddress.SettingKey, StringComparison.OrdinalIgnoreCase))?.Value ?? string.Empty;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -33,26 +41,32 @@
|
||||
private async Task SaveUrlAsync(string value)
|
||||
{
|
||||
value = value?.Trim() ?? string.Empty;
|
||||
if (value.Length > 0 && (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps))
|
||||
if (!Heimdall.Web.Services.ForgeReleaseApiAddress.IsValidForgePublicUrl(value))
|
||||
{
|
||||
Snackbar.Add("L’URL doit être une adresse HTTPS absolue.", Severity.Warning);
|
||||
Snackbar.Add(Text["UpdatesSettings_InvalidForgeUrl"], Severity.Warning);
|
||||
return;
|
||||
}
|
||||
value = new Uri(value.TrimEnd('/')).AbsoluteUri.TrimEnd('/');
|
||||
|
||||
var existing = _settings.FirstOrDefault(s => s.Key.Equals(SettingKey, StringComparison.OrdinalIgnoreCase));
|
||||
var existing = _settings.FirstOrDefault(s => s.Key.Equals(
|
||||
Heimdall.Web.Services.ForgeReleaseApiAddress.SettingKey, StringComparison.OrdinalIgnoreCase));
|
||||
try
|
||||
{
|
||||
if (existing is null)
|
||||
await Api.CreateSettingAsync(new CreateAppSettingRequest(SettingKey, value, "updates", "API de publication Heimdall", "string", null, false));
|
||||
(await Api.CreateSettingAsync(new CreateAppSettingRequest(
|
||||
Heimdall.Web.Services.ForgeReleaseApiAddress.SettingKey, value, "updates",
|
||||
"URL publique de Forgejo utilisée pour les releases Heimdall", "string", null, false)))
|
||||
.EnsureSuccessStatusCode();
|
||||
else
|
||||
await Api.UpdateSettingAsync(existing.Key, new UpdateAppSettingRequest(value, existing.Description, "updates", "string", null, false));
|
||||
(await Api.UpdateSettingAsync(existing.Key, new UpdateAppSettingRequest(
|
||||
value, existing.Description, "updates", "string", null, false))).EnsureSuccessStatusCode();
|
||||
_url = value;
|
||||
_settings = await Api.GetSettingsAsync();
|
||||
Snackbar.Add("Source des mises à jour enregistrée.", Severity.Success);
|
||||
Snackbar.Add(Text["UpdatesSettings_Saved"], Severity.Success);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Impossible d’enregistrer la source des mises à jour : {ex.Message}", Severity.Error);
|
||||
Snackbar.Add(string.Format(Text["UpdatesSettings_SaveFailed"], ex.Message), Severity.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
Visible="@(Hub.UnreadCount > 0)">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
|
||||
aria-label="@Text["SharedNotificationBadge_Title"]"
|
||||
OnClick="@(() => Navigation.NavigateTo("/events"))" />
|
||||
OnClick="@(() => Navigation.NavigateTo("/notifications"))" />
|
||||
</MudBadge>
|
||||
</MudTooltip>
|
||||
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
@using MudBlazor
|
||||
@inject Heimdall.Web.Services.UiText Text
|
||||
|
||||
<style>
|
||||
.installer-option { min-height: 3.25rem; justify-content: center; gap: .6rem; text-transform: none; }
|
||||
.installer-option-selected { background: color-mix(in srgb, var(--mud-palette-primary) 10%, transparent); }
|
||||
.installer-copy-box { position: relative; border: 1px solid var(--mud-palette-lines-default); border-radius: 6px; background: var(--mud-palette-surface); overflow: hidden; }
|
||||
.installer-copy-box pre { margin: 0; padding: 1rem 3.5rem 1rem 1rem; overflow-x: auto; white-space: pre; font-size: .875rem; }
|
||||
.installer-copy-button { position: absolute; top: .25rem; right: .25rem; background: var(--mud-palette-surface); }
|
||||
</style>
|
||||
|
||||
<MudText Typo="Typo.h6" Class="mb-1">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Download" Size="Size.Small" Class="mr-1" />
|
||||
@Text["SiteInstallPanel_Title"]
|
||||
@@ -10,27 +18,51 @@
|
||||
@Text["SiteInstallPanel_Description"]
|
||||
</MudText>
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
|
||||
<MudGrid Class="mb-3">
|
||||
@if (_releaseLoading)
|
||||
{
|
||||
<MudProgressLinear Indeterminate="true" Color="Color.Primary" Class="mb-3" />
|
||||
}
|
||||
else if (_releaseReady)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-3">
|
||||
@string.Format(Text["SiteInstallPanel_ReleaseReady"], _releaseVersion)
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-3">
|
||||
@Text["SiteInstallPanel_ReleaseUnavailable"]
|
||||
</MudAlert>
|
||||
}
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-3">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
|
||||
<MudGrid Class="mb-4">
|
||||
@foreach (var os in OperatingSystems)
|
||||
{
|
||||
<MudItem xs="12" sm="4" @key="os.Id">
|
||||
<MudButton FullWidth="true" Variant="@(_operatingSystem == os.Id ? Variant.Filled : Variant.Outlined)"
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined"
|
||||
Color="@(_operatingSystem == os.Id ? Color.Primary : Color.Default)"
|
||||
OnClick="@(() => SelectOperatingSystem(os.Id))">@os.Icon @Text[os.Label]</MudButton>
|
||||
Class="@OptionClass(_operatingSystem == os.Id)"
|
||||
OnClick="@(() => SelectOperatingSystem(os.Id))">
|
||||
<MudIcon Icon="@os.Icon" Size="Size.Small" />
|
||||
<span>@Text[os.Label]</span>
|
||||
</MudButton>
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Method"]</MudText>
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-3">@Text["SiteInstallPanel_Method"]</MudText>
|
||||
<MudGrid Class="mb-4">
|
||||
@foreach (var method in AvailableMethods)
|
||||
{
|
||||
var selectedMethod = method.Id;
|
||||
<MudItem xs="12" sm="6" @key="method.Id">
|
||||
<MudButton FullWidth="true" Variant="@(_method == method.Id ? Variant.Filled : Variant.Outlined)"
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined"
|
||||
Color="@(_method == method.Id ? Color.Primary : Color.Default)"
|
||||
OnClick="@(() => _method = selectedMethod)">@Text[method.Label]</MudButton>
|
||||
Class="@OptionClass(_method == method.Id)"
|
||||
OnClick="@(() => _method = selectedMethod)">
|
||||
@Text[method.Label]
|
||||
</MudButton>
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
@@ -38,9 +70,11 @@
|
||||
@if ((_method == "docker-compose" || _method == "docker-run") && CanGenerateDocker &&
|
||||
!string.IsNullOrWhiteSpace(_agentGpuImageReference))
|
||||
{
|
||||
<MudSwitch @bind-Value="_useGpuImage" Color="Color.Primary" Class="mb-2">
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
|
||||
<MudCheckBox @bind-Value="_useGpuImage" Color="Color.Primary" Class="mb-1">
|
||||
@Text["SiteInstallPanel_NvidiaInference"]
|
||||
</MudSwitch>
|
||||
</MudCheckBox>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_NvidiaDescription"]</MudText>
|
||||
@if (_useGpuImage)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Class="mb-3">@Text["SiteInstallPanel_NvidiaRequirement"]</MudAlert>
|
||||
@@ -49,33 +83,48 @@
|
||||
|
||||
@if (_method == "docker-compose" && CanGenerateDocker)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
|
||||
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2">@Text["SiteInstallPanel_Install"]</MudText>
|
||||
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@ComposeYaml</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
|
||||
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCompose"]
|
||||
</MudButton>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudText>
|
||||
}
|
||||
else if (_method == "docker-compose" && !CanGenerateDocker)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
|
||||
}
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
|
||||
@foreach (var command in Commands)
|
||||
else if (_method == "docker-run" && CanGenerateDocker)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
|
||||
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
|
||||
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCommand"]
|
||||
</MudButton>
|
||||
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
|
||||
}
|
||||
else if (_method == "docker-run")
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
|
||||
}
|
||||
|
||||
@if (CanGenerateSelectedMethod)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-3 mt-5">@Text["SiteInstallPanel_Commands"]</MudText>
|
||||
@if (_method == "docker-compose")
|
||||
{
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text["SiteInstallPanel_Configuration"]</MudText>
|
||||
<MudPaper Class="installer-copy-box mb-3">
|
||||
<pre><code>@ComposeYaml</code></pre>
|
||||
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
|
||||
<MudIconButton Icon="@CopyIconFor(ComposeYaml)" Color="Color.Default" Size="Size.Small"
|
||||
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
|
||||
OnClick="@(() => CopyCode(ComposeYaml))" />
|
||||
</MudTooltip>
|
||||
</MudPaper>
|
||||
}
|
||||
@foreach (var command in Commands)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
|
||||
<MudPaper Class="installer-copy-box">
|
||||
<pre><code>@command.Value</code></pre>
|
||||
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
|
||||
<MudIconButton Icon="@CopyIconFor(command.Value)" Color="Color.Default" Size="Size.Small"
|
||||
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
|
||||
OnClick="@(() => CopyCode(command.Value))" />
|
||||
</MudTooltip>
|
||||
</MudPaper>
|
||||
}
|
||||
}
|
||||
|
||||
@if (_method == "windows-run")
|
||||
@@ -98,9 +147,9 @@ else if (_method == "windows-service")
|
||||
|
||||
private static readonly (string Id, string Label, string Icon)[] OperatingSystems =
|
||||
[
|
||||
("linux", "SiteInstallPanel_Linux", "🐧"),
|
||||
("windows", "SiteInstallPanel_Windows", "⊞"),
|
||||
("docker", "SiteInstallPanel_Docker", "🐳")
|
||||
("linux", "SiteInstallPanel_Linux", Icons.Material.Filled.Terminal),
|
||||
("windows", "SiteInstallPanel_Windows", Icons.Material.Filled.Window),
|
||||
("docker", "SiteInstallPanel_Docker", Icons.Material.Filled.ViewInAr)
|
||||
];
|
||||
|
||||
private string _operatingSystem = "linux";
|
||||
@@ -108,10 +157,21 @@ else if (_method == "windows-service")
|
||||
private string? _agentImageReference;
|
||||
private string? _agentGpuImageReference;
|
||||
private string? _updatePublicKeyPem;
|
||||
private string? _releaseVersion;
|
||||
private bool _releaseLoading = true;
|
||||
private bool _releaseReady;
|
||||
private bool _useGpuImage;
|
||||
private string? _copiedCode;
|
||||
private string CopyIconFor(string code) => _copiedCode == code ? Icons.Material.Filled.Check : Icons.Material.Filled.ContentCopy;
|
||||
private static string OptionClass(bool selected) => selected ? "installer-option installer-option-selected" : "installer-option";
|
||||
|
||||
private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) &&
|
||||
!string.IsNullOrWhiteSpace(_updatePublicKeyPem);
|
||||
!string.IsNullOrWhiteSpace(_updatePublicKeyPem) && _releaseReady;
|
||||
private bool CanGenerateSelectedMethod => _method switch
|
||||
{
|
||||
"docker-compose" or "docker-run" => CanGenerateDocker,
|
||||
_ => _releaseReady
|
||||
};
|
||||
|
||||
private IReadOnlyList<(string Id, string Label)> AvailableMethods => _operatingSystem switch
|
||||
{
|
||||
@@ -165,7 +225,10 @@ else if (_method == "windows-service")
|
||||
[
|
||||
("SiteInstallPanel_Install", DockerRunInstallCommand),
|
||||
("SiteInstallPanel_Run", DockerRunCommand),
|
||||
("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}")
|
||||
("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}"),
|
||||
("SiteInstallPanel_InstallPowerShell", DockerRunPowerShellInstallCommand),
|
||||
("SiteInstallPanel_RunPowerShell", DockerRunPowerShellCommand),
|
||||
("SiteInstallPanel_CheckPowerShell", DockerRunPowerShellCheckCommand)
|
||||
];
|
||||
return [];
|
||||
}
|
||||
@@ -176,6 +239,11 @@ else if (_method == "windows-service")
|
||||
try
|
||||
{
|
||||
var release = await Api.GetLatestUpdateAsync();
|
||||
_releaseVersion = release?.Version;
|
||||
_releaseReady = !string.IsNullOrWhiteSpace(release?.UpdatePublicKeyPem) &&
|
||||
!string.IsNullOrWhiteSpace(release?.SignedManifest) &&
|
||||
!string.IsNullOrWhiteSpace(release?.ManifestSignature) &&
|
||||
release?.Assets.Count > 0;
|
||||
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
|
||||
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
|
||||
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
|
||||
@@ -188,6 +256,10 @@ else if (_method == "windows-service")
|
||||
{
|
||||
// Native installers fetch signed release metadata directly; Docker needs a verified image reference and key.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_releaseLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private string ComposeYaml
|
||||
@@ -208,6 +280,8 @@ else if (_method == "windows-service")
|
||||
container_name: heimdall-agent-{{safeName}}
|
||||
restart: unless-stopped
|
||||
user: "1654:1654"
|
||||
group_add:
|
||||
- "${DOCKER_GID:-0}"
|
||||
network_mode: host
|
||||
environment:
|
||||
Agent__CentralUrl: {{YamlScalar(CentralUrl)}}
|
||||
@@ -219,6 +293,7 @@ else if (_method == "windows-service")
|
||||
Agent__UpdatePublicKeyPem: "{{pem}}"
|
||||
volumes:
|
||||
- agent_state_{{safeName}}:/var/lib/heimdall
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
depends_on:
|
||||
agent-state-init:
|
||||
condition: service_completed_successfully
|
||||
@@ -249,8 +324,9 @@ else if (_method == "windows-service")
|
||||
get
|
||||
{
|
||||
var volume = "heimdall-agent-state-" + Slugify(SiteName);
|
||||
return $"docker pull {_agentImageReference} && docker volume create {volume} && " +
|
||||
$"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {_agentImageReference} -R 1654:1654 /state";
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
return $"docker pull {image} && docker volume create {volume} && " +
|
||||
$"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {image} -R 1654:1654 /state";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +339,8 @@ else if (_method == "windows-service")
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
|
||||
(_useGpuImage ? "--gpus all " : "") +
|
||||
"--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " +
|
||||
"-v /var/run/docker.sock:/var/run/docker.sock " +
|
||||
$"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " +
|
||||
$"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " +
|
||||
$"-e Agent__InferenceExecutionProvider={(_useGpuImage ? "CUDA" : "CPU")} " +
|
||||
@@ -271,6 +349,55 @@ else if (_method == "windows-service")
|
||||
}
|
||||
}
|
||||
|
||||
private string DockerRunPowerShellInstallCommand
|
||||
{
|
||||
get
|
||||
{
|
||||
var volume = "heimdall-agent-state-" + Slugify(SiteName);
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
return "$ErrorActionPreference = 'Stop'; " +
|
||||
"docker pull " + PowerShellQuote(image ?? "") + "; if ($LASTEXITCODE -ne 0) { throw 'docker pull failed' }; " +
|
||||
"docker volume create " + PowerShellQuote(volume) + "; if ($LASTEXITCODE -ne 0) { throw 'docker volume create failed' }; " +
|
||||
"docker run --rm --user 0:0 --entrypoint chown -v " + PowerShellQuote(volume + ":/state") + " " +
|
||||
PowerShellQuote(image ?? "") + " -R 1654:1654 /state; if ($LASTEXITCODE -ne 0) { throw 'state volume initialization failed' }";
|
||||
}
|
||||
}
|
||||
|
||||
private string DockerRunPowerShellCommand
|
||||
{
|
||||
get
|
||||
{
|
||||
var name = "heimdall-agent-" + Slugify(SiteName);
|
||||
var volume = "heimdall-agent-state-" + Slugify(SiteName);
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
var args = new List<string> { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
|
||||
if (_useGpuImage) args.AddRange(["--gpus", "all"]);
|
||||
args.AddRange([
|
||||
"-e", "Agent__CentralUrl=" + CentralUrl,
|
||||
"-e", "Agent__SiteToken=" + SiteToken,
|
||||
"-e", "Agent__AgentName=" + SiteName,
|
||||
"-e", "Agent__StateDirectory=/var/lib/heimdall",
|
||||
"-e", "ASPNETCORE_URLS=http://+:8080",
|
||||
"-e", "Agent__InferenceExecutionProvider=" + (_useGpuImage ? "CUDA" : "CPU"),
|
||||
"-e", "Agent__UpdatePublicKeyPem=" + (_updatePublicKeyPem ?? ""),
|
||||
"-v", volume + ":/var/lib/heimdall",
|
||||
image ?? ""
|
||||
]);
|
||||
return "$dockerArgs = @(" + string.Join(",", args.Select(PowerShellQuote)) + "); & docker @dockerArgs; if ($LASTEXITCODE -ne 0) { throw 'docker run failed' }";
|
||||
}
|
||||
}
|
||||
|
||||
private string DockerRunPowerShellCheckCommand
|
||||
{
|
||||
get
|
||||
{
|
||||
var name = "heimdall-agent-" + Slugify(SiteName);
|
||||
return "$status = docker inspect --format '{{.State.Status}}' " + PowerShellQuote(name) + "; " +
|
||||
"if ($LASTEXITCODE -ne 0) { throw 'container inspect failed' }; $status; " +
|
||||
"docker logs --tail 50 " + PowerShellQuote(name) + "; if ($LASTEXITCODE -ne 0) { throw 'container logs failed' }";
|
||||
}
|
||||
}
|
||||
|
||||
private string LinuxInstallCommand(bool service)
|
||||
{
|
||||
var baseUrl = CentralUrl.TrimEnd('/');
|
||||
@@ -336,7 +463,13 @@ else if (_method == "windows-service")
|
||||
private async Task CopyCode(string code)
|
||||
{
|
||||
await JsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", code);
|
||||
_copiedCode = code;
|
||||
StateHasChanged();
|
||||
Snackbar.Add(Text["SiteInstallPanel_Copied"], Severity.Success);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2));
|
||||
if (_copiedCode == code)
|
||||
_copiedCode = null;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
private static string Slugify(string value)
|
||||
|
||||
@@ -161,6 +161,48 @@ public class SitesController : ControllerBase
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>List the camera credential pool for a site. Passwords are never returned.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<SiteCredentialResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetCredentials(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ListSiteCredentialsQuery(id), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Add a camera credential to a site. The password is write-only.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(SiteCredentialResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> AddCredential(Guid id, [FromBody] AddSiteCredentialRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(
|
||||
new AddSiteCredentialCommand(id, request.Label, request.Username, request.Password), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera credential from a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpDelete("{id:guid}/credentials/{credentialId:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteCredential(Guid id, Guid credentialId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new DeleteSiteCredentialCommand(id, credentialId), ct);
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
|
||||
@@ -7,6 +7,7 @@ using Heimdall.Infrastructure.Settings;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
@@ -33,6 +34,7 @@ public class UpdatesController : ControllerBase
|
||||
private static readonly object _cacheLock = new();
|
||||
private static LatestReleaseCache? _cache;
|
||||
private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1);
|
||||
private const int MaxReleaseResponseBytes = 1_048_576;
|
||||
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> logger,
|
||||
IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess, IServiceProvider services)
|
||||
{
|
||||
@@ -103,7 +105,12 @@ public class UpdatesController : ControllerBase
|
||||
{
|
||||
using var scope = _services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
||||
return await AppSettingReader.GetAsync(db, "updates.releaseapiurl", ct).ConfigureAwait(false);
|
||||
var forgePublicUrl = await AppSettingReader.GetAsync(db, ForgeReleaseApiAddress.SettingKey, ct)
|
||||
.ConfigureAwait(false);
|
||||
var releaseApiUrl = ForgeReleaseApiAddress.BuildReleaseApiUrl(forgePublicUrl);
|
||||
if (releaseApiUrl is null)
|
||||
_logger.LogError("The global Forgejo public URL setting must be an absolute HTTPS URL without credentials, query, or fragment");
|
||||
return releaseApiUrl;
|
||||
}
|
||||
|
||||
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(string? source, CancellationToken ct)
|
||||
@@ -122,7 +129,7 @@ public class UpdatesController : ControllerBase
|
||||
using var response = await GetReleaseResponseWithRetryAsync(client, sourceUri, ct);
|
||||
if (response is null || !response.IsSuccessStatusCode)
|
||||
return null;
|
||||
var release = await response.Content.ReadFromJsonAsync<ForgejoRelease>(Json, ct);
|
||||
var release = await ReadForgejoReleaseAsync(response.Content, ct);
|
||||
if (release is null) return null;
|
||||
var assets = new Dictionary<string, PlatformAsset>();
|
||||
foreach (var asset in release.Assets ?? [])
|
||||
@@ -168,6 +175,34 @@ public class UpdatesController : ControllerBase
|
||||
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
|
||||
}
|
||||
|
||||
private static async Task<ForgejoRelease?> ReadForgejoReleaseAsync(HttpContent content, CancellationToken ct)
|
||||
{
|
||||
if (content.Headers.ContentLength is long length && length > MaxReleaseResponseBytes)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
await using var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[8192];
|
||||
while (true)
|
||||
{
|
||||
var read = await stream.ReadAsync(chunk, ct).ConfigureAwait(false);
|
||||
if (read == 0) break;
|
||||
if (buffer.Length + read > MaxReleaseResponseBytes) return null;
|
||||
buffer.Write(chunk, 0, read);
|
||||
}
|
||||
|
||||
return JsonSerializer.Deserialize<ForgejoRelease>(buffer.ToArray(), Json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Release providers and intermediaries can return HTML or malformed JSON.
|
||||
// Treat that as an unavailable release, without logging untrusted response content.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async Task<HttpResponseMessage?> GetReleaseResponseWithRetryAsync(HttpClient client, Uri sourceUri,
|
||||
CancellationToken ct)
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Heimdall.Api.Tests" />
|
||||
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
|
||||
<InternalsVisibleTo Include="Heimdall.Web.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user