From 4f027c5072a10b3f06c43ea6da2fe93bbb532639 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 17 Nov 2026 06:44:52 +0100 Subject: [PATCH] chore: preserve acceptance procedures outside skills --- docs/README.md | 3 + docs/development-workflow.md | 74 +++++ scripts/acceptance/agent-heartbeat-timeout.sh | 188 ++++++++++++ .../acceptance/agent-startup-composition.sh | 127 ++++++++ .../acceptance/camera-toggle-acceptance.sh | 276 ++++++++++++++++++ .../acceptance/database-migration-startup.sh | 198 +++++++++++++ scripts/acceptance/heimdall-identity.sh | 182 ++++++++++++ .../acceptance/optional-server-services.sh | 266 +++++++++++++++++ scripts/acceptance/renovate-automation.sh | 95 ++++++ .../acceptance/webrtc-live-source-change.sh | 76 +++++ 10 files changed, 1485 insertions(+) create mode 100644 docs/development-workflow.md create mode 100755 scripts/acceptance/agent-heartbeat-timeout.sh create mode 100755 scripts/acceptance/agent-startup-composition.sh create mode 100755 scripts/acceptance/camera-toggle-acceptance.sh create mode 100755 scripts/acceptance/database-migration-startup.sh create mode 100755 scripts/acceptance/heimdall-identity.sh create mode 100755 scripts/acceptance/optional-server-services.sh create mode 100755 scripts/acceptance/renovate-automation.sh create mode 100755 scripts/acceptance/webrtc-live-source-change.sh diff --git a/docs/README.md b/docs/README.md index 02718c0..7ad6af9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -73,6 +73,7 @@ Heimdall/ | `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites | | `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées | | `gpu-runtime.md` | Capacités GPU Agent, configuration et limites de validation matérielle | +| `development-workflow.md` | Règles opérationnelles Heimdall, CI et recettes d'acceptance | L'audit est la source de vérité pour les constats actuels, leur statut et les travaux restants. Les documents de spécification décrivent parfois la cible initiale; leurs @@ -83,6 +84,8 @@ mentions de fonctionnalités ne prouvent pas leur livraison. Les règles et critères d’acceptation propres au produit sont maintenus dans ces guides et les autres documents de ce répertoire. Les pratiques génériques des agents sont définies dans le catalogue partagé `/home/nonobis/skills/skills/`. +Les recettes exécutables sont rangées sous `scripts/acceptance/` et les +contrôles automatisés sous `scripts/ci/`. ## Audit du 20 octobre 2026 diff --git a/docs/development-workflow.md b/docs/development-workflow.md new file mode 100644 index 0000000..db91103 --- /dev/null +++ b/docs/development-workflow.md @@ -0,0 +1,74 @@ +# Règles de développement et acceptance Heimdall + +Ce document conserve les exigences opérationnelles propres au dépôt. Les +pratiques générales des agents relèvent du catalogue partagé. Le backlog et le +suivi d'avancement du projet résident dans les issues Gitea; ne pas créer de +`todo.md` parallèle. Lier l'issue dans la PR et y maintenir les preuves +d'acceptance. + +## Architecture et implémentation + +- `Domain` reste indépendant de l'infrastructure. Placer les cas d'usage et + interfaces dans `Application`, les adaptateurs et la persistance EF Core + dans `Infrastructure`, la composition HTTP/UI dans `Web`, et le comportement + caméra/runtime dans `Agent`. +- Cibler le SDK épinglé dans `global.json` et .NET 10 ou plus récent. Garder les + références nullable activées, transmettre les tokens d'annulation aux E/S et + valider explicitement les options. Ne pas affaiblir les restores verrouillés + ni supprimer un nouvel avertissement sans justification. +- Utiliser EF Core pour les lectures et écritures de production. Les commandes + ADO.NET ou spécifiques au fournisseur sont interdites en production. Une + requête SQL EF propre au fournisseur n'est admise que si LINQ ne peut exprimer + la capacité requise, avec justification adjacente et test relationnel. Le + contrôle CI de persistance vérifie cette limite. Préserver PostgreSQL, + ajouter les migrations de schéma et tester traduction, concurrence et + suppression sur une base relationnelle. Ne jamais partager un `DbContext` + entre opérations concurrentes. +- Vérifier l'autorisation tenant/site et caméra aux frontières API et + application. Ne jamais journaliser identifiants, URL RTSP, embeddings ou + jetons bruts. + +## CI, déploiement et validations + +- Les jobs Gitea s'exécutent sur `[ubuntu-latest, build-agent]`. Ne pas placer + `runner-aaja` sur ce label. Ne jamais exposer d'identifiants de publication + dans un job de pull request. +- Une modification de comportement ou de déploiement qui nécessite une + acceptance d'intégration doit utiliser une recette Compose jetable, construite + depuis la source modifiée, avec données et identifiants synthétiques, ports, + volumes, réseau, nom de projet et tags locaux uniques. Installer le nettoyage + avant le premier build/démarrage. Après la recette, supprimer uniquement les + ressources et tags exacts créés, vérifier leur absence et conserver les + images amont. Ne jamais utiliser de prune global. Si Docker est indisponible, + le signaler au lieu de prétendre que la recette a réussi. +- Ne pas affirmer qu'un runner, registre, appareil, caméra ou stockage distant a + été validé sans résultat d'une exécution réelle. Une acceptance synthétique + locale ne prouve pas le comportement sur un hôte déployé, réseau externe ou + matériel physique. +- Toute PR touchant au déploiement ou à la publication documente les secrets + requis et apporte une preuve locale pertinente du script. Ne jamais inclure + de secret dans les changements, journaux ou artefacts. + +## Recettes conservées + +Les scripts Compose d'acceptance sont exécutables dans `scripts/acceptance/` : + +- `agent-heartbeat-timeout.sh` — heartbeat Agent et expiration; +- `agent-startup-composition.sh` — composition et démarrage Agent; +- `camera-toggle-acceptance.sh` — activation et désactivation caméra; +- `database-migration-startup.sh` — migration et reprise au démarrage; +- `heimdall-identity.sh` — création/connexion et flux de cookie 2FA; +- `optional-server-services.sh` — services optionnels et sauvegarde/restauration; +- `renovate-automation.sh` — acceptance de l'automatisation Renovate; +- `webrtc-live-source-change.sh` — changement de source du live view. + +Les contrôles de build et de politique restent dans `scripts/ci/`. Voir +[`gitea-builds.md`](gitea-builds.md) pour les workflows et contraintes de +runners, et [`docker-compose.md`](docker-compose.md) pour les recettes jetables. + +## Collaboration et conception + +Pour les changements d'interface issus de Penpot, ouvrir le document avec la +session authentifiée du navigateur Orca et synchroniser le design connecté avec +les changements UI livrés. Si le travail est découpé en lots indépendants, +coordonner les lots via Orca et intégrer puis valider le résultat combiné. diff --git a/scripts/acceptance/agent-heartbeat-timeout.sh b/scripts/acceptance/agent-heartbeat-timeout.sh new file mode 100755 index 0000000..446ed64 --- /dev/null +++ b/scripts/acceptance/agent-heartbeat-timeout.sh @@ -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:-}" "${volumes:-}" "${networks:-}" >&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" <"$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 diff --git a/scripts/acceptance/agent-startup-composition.sh b/scripts/acceptance/agent-startup-composition.sh new file mode 100755 index 0000000..820b702 --- /dev/null +++ b/scripts/acceptance/agent-startup-composition.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +repo_root=$(git rev-parse --show-toplevel) +project="heimdall-agent-startup-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 3)" +image_tag="heimdall-agent:${project}-agent" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +env_file="$temp_dir/acceptance.env" +compose_file="$temp_dir/compose.yaml" +local_image_tags=("$image_tag") + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \ + down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1 + + containers= + volumes= + networks= + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + [[ -z "${containers:-}" && -z "${volumes:-}" && -z "${networks:-}" ]] || cleanup_failed=1 + + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + if docker image inspect "$tag" >/dev/null 2>&1; then + cleanup_failed=1 + fi + done + + rm -f -- "$env_file" "$compose_file" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + + if (( cleanup_failed )); then + printf 'Disposable Agent startup cleanup failed for project %s\n' "$project" >&2 + status=1 + else + printf 'Cleanup verified: project=%s; containers/volumes/networks absent; image tag %s absent.\n' \ + "$project" "$image_tag" + fi + + exit "$status" +} +trap cleanup EXIT + +umask 077 +cat >"$env_file" <"$compose_file" <<'EOF' +services: + agent: + image: ${IMAGE_TAG} + build: + context: ${SOURCE_ROOT} + dockerfile: docker/Dockerfile.agent + network: host + restart: "no" + environment: + Agent__CentralUrl: http://127.0.0.1:1 + Agent__AllowInsecureHttp: "true" + Agent__SiteToken: ${SYNTHETIC_SITE_TOKEN} + Agent__AgentName: ${PROJECT} + Agent__RegistrationMaxRetries: "20" + Agent__HeartbeatIntervalSeconds: "5" + Agent__DiscoveryEnabled: "false" + Agent__UpdateCheckIntervalHours: "0" + Agent__StateDirectory: /var/lib/heimdall + Sentry__Dsn: "" + volumes: + - agent_state:/var/lib/heimdall + networks: + - isolated + +volumes: + agent_state: + +networks: + isolated: + internal: true +EOF + +docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \ + up --build --detach agent + +container_id=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps -q agent) +[[ -n "$container_id" ]] || { printf 'Agent container was not created.\n' >&2; exit 1; } + +deadline=$((SECONDS + 90)) +live_ready=0 +while (( SECONDS < deadline )); do + running=$(docker inspect --format '{{.State.Running}}' "$container_id" 2>/dev/null || true) + if [[ "$running" != true ]]; then + printf 'Agent container exited before its live endpoint became ready.\n' >&2 + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps >&2 || true + exit 1 + fi + + if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \ + exec -T agent wget -q --tries=1 --spider http://127.0.0.1:8080/health/live >/dev/null 2>&1; then + live_ready=1 + break + fi + sleep 1 +done + +(( live_ready == 1 )) || { printf 'Agent /health/live did not become ready.\n' >&2; exit 1; } + +restart_count=$(docker inspect --format '{{.RestartCount}}' "$container_id") +[[ "$restart_count" == 0 ]] || { printf 'Agent container restarted unexpectedly.\n' >&2; exit 1; } + +if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs agent 2>&1 | + rg -q "Unable to resolve service for type 'Heimdall\.Agent\.Services\.SnapshotPipelineServiceOptions'|Hosting failed to start"; then + printf 'Agent startup log contains a dependency-injection or host-start failure.\n' >&2 + exit 1 +fi + +printf 'Agent host started; /health/live returned success; container remained running without restart.\n' +printf 'Project: %s\nLocal image tag: %s\n' "$project" "$image_tag" diff --git a/scripts/acceptance/camera-toggle-acceptance.sh b/scripts/acceptance/camera-toggle-acceptance.sh new file mode 100755 index 0000000..994efb4 --- /dev/null +++ b/scripts/acceptance/camera-toggle-acceptance.sh @@ -0,0 +1,276 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +umask 077 + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +stamp="$(date +%s)-$RANDOM" +project="heimdall-157-${stamp}" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +env_file="$temp_dir/acceptance.env" +env_next="$temp_dir/acceptance.env.next" +compose_override="$temp_dir/compose.override.yml" +config_headers="$temp_dir/config.headers" +config_body="$temp_dir/config.json" +stage=setup +local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent") +compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override") +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + if (( status != 0 )); then + printf 'acceptance failed at stage=%s\n' "$stage" >&2 + docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null | + grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true + fi + docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1 + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + rm -f -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then + printf 'cleanup verification failed for %s\n' "$project" >&2 + status=1 + else + printf 'cleanup verified: project resources absent; exact local tags absent\n' + fi + exit "$status" +} + +port=$((20000 + RANDOM % 20000)) +pg_port=$((port + 1)) +db_password=$(openssl rand -hex 24) +jwt_key=$(openssl rand -hex 48) +jwt_refresh=$(openssl rand -hex 48) +cat >"$env_file" <"$compose_override" <<'EOF' +services: + heimdall: + image: heimdall:${ACCEPTANCE_PROJECT}-central + heimdall-agent: + image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent + build: + context: .. + dockerfile: docker/Dockerfile.agent + user: "1654:1654" + environment: + Agent__CentralUrl: http://heimdall:8080 + Agent__AllowInsecureHttp: "true" + Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required} + Agent__AgentName: camera-157-agent + Agent__HeartbeatIntervalSeconds: "5" + Agent__StateDirectory: /var/lib/heimdall + Agent__DiscoveryEnabled: "false" + volumes: + - agent_state:/var/lib/heimdall + depends_on: + heimdall: + condition: service_healthy + synthetic-camera-publisher: + condition: service_started + networks: + - heimdall-net + synthetic-camera: + image: bluenviron/mediamtx:1.21.3 + volumes: + - ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro + networks: + - heimdall-net + synthetic-camera-publisher: + image: jrottenberg/ffmpeg:7.1-alpine + entrypoint: ["/bin/sh", "-c"] + command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"] + depends_on: + - synthetic-camera + networks: + - heimdall-net +volumes: + agent_state: +EOF + +# The cleanup trap is installed before any image build or Compose start. +trap cleanup EXIT +chmod 600 "$env_file" +api="http://127.0.0.1:$port" +compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; } +contract_failures=0 +wait_http() { + for _ in $(seq 1 90); do + if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi + sleep 2 + done + return 1 +} +request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; } +ffmpeg_count() { + compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"' +} +wait_count() { + expected=$1; seconds=$2 + for _ in $(seq 1 "$((seconds * 20))"); do + count=$(ffmpeg_count) + observed_at_ns=$(date +%s%N) + (( count <= 1 )) || return 1 + if [[ "$count" == "$expected" ]]; then + count_observed_at_ns=$observed_at_ns + return 0 + fi + sleep 0.05 + done + return 1 +} +wait_ack() { + expected_enabled=$1 + for _ in $(seq 1 100); do + request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body" + wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers") + actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body") + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents") + if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then + acknowledged_version=$wanted + return 0 + fi + sleep 0.1 + done + return 1 +} +wait_agent_reconnected_and_ack() { + restarted_at_ns=$1 + expected_version=$2 + for _ in $(seq 1 60); do + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents") + status=$(jq -r '.status // empty' <<<"$agent") + heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent") + applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent") + applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent") + if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then + heartbeat_ns=$(date -u -d "$heartbeat" +%s%N) + applied_at_ns=$(date -u -d "$applied_at" +%s%N) + if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then + return 0 + fi + fi + sleep 1 + done + return 1 +} + +printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}" +stage=build +compose build heimdall heimdall-agent +stage=central-startup +compose up -d postgresql heimdall +wait_http +stage=bootstrap +admin_password="Tst!$(openssl rand -hex 20)A9" +bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin") +admin_token=$(jq -er '.accessToken' <<<"$bootstrap") +printf 'synthetic Admin bootstrap accepted\n' +site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites") +site_id=$(jq -er '.id' <<<"$site") +printf 'synthetic site created\n' +site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token') +grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next" +printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next" +mv "$env_next" "$env_file" +camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras") +camera_id=$(jq -er '.id' <<<"$camera") +[[ $(jq -r '.status' <<<"$camera") == Disabled ]] +printf 'synthetic camera created\n' +stage=agent-startup +compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent +agent_id= +for _ in $(seq 1 60); do + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents") + [[ -n "$agent_id" ]] && break + sleep 1 +done +[[ -n "$agent_id" ]] +printf 'Agent registered\n' +request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null +stage=initial-on +request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null +wait_count 1 10 +wait_ack true + +off_once() { + started=$(date +%s%N) + result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status") + response_ms=$((( $(date +%s%N) - started ) / 1000000)) + [[ $(jq -r '.status' <<<"$result") == Disabled ]] + within_contract=1 + if ! wait_count 0 2; then + within_contract=0 + wait_count 0 10 || return 1 + fi + elapsed_ms=$((( count_observed_at_ns - started ) / 1000000)) + printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract" + if (( ! within_contract || elapsed_ms >= 2000 )); then + contract_failures=$((contract_failures + 1)) + fi + wait_ack false +} +for iteration in 1 2 3; do + stage="cycle-${iteration}-off" + off_once + stage="cycle-${iteration}-on" + request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null + wait_count 1 10 + wait_ack true + count=$(ffmpeg_count) + [[ "$count" == 1 ]] +done +stage=agent-restart-on +compose restart heimdall-agent +wait_count 1 10 +agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") +old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +[[ "$old_agent_id" == "$agent_id" ]] +wait_ack true +stage=final-off +off_once +agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") +old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +compose restart heimdall-agent +post_off_restart_returned_ns=$(date +%s%N) +wait_count 0 10 +wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version" +stage=central-restart-off +compose restart heimdall +central_restart_returned_ns=$(date +%s%N) +wait_http +sleep 2 +[[ $(ffmpeg_count) == 0 ]] +camera=$(request "$api/api/cameras/$camera_id") +[[ $(jq -r '.status' <<<"$camera") == Disabled ]] +wait_ack false +wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version" +printf 'restart OFF persisted; camera config digest acknowledged\n' +if (( contract_failures > 0 )); then + printf 'contract failures=%s\n' "$contract_failures" >&2 + exit 1 +fi diff --git a/scripts/acceptance/database-migration-startup.sh b/scripts/acceptance/database-migration-startup.sh new file mode 100755 index 0000000..7d797fd --- /dev/null +++ b/scripts/acceptance/database-migration-startup.sh @@ -0,0 +1,198 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +project="heimdall-migration-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 4)" +temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")" +env_file="$temp_dir/acceptance.env" +compose_override="$temp_dir/compose.override.yml" +failure_override="$temp_dir/compose.failure.yml" +recovery_override="$temp_dir/compose.recovery.yml" +compose_file="$(git rev-parse --show-toplevel)/docker/docker-compose.yml" +local_image_tags=("heimdall:${project}-central") + +web_port="$(python3 - <<'PY' +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +PY +)" +db_name="${project//-/_}" +db_user="migration_owner_${project//-/_}" +db_password="$(openssl rand -hex 24)" +probe_password="$(openssl rand -hex 24)" +jwt_key="$(openssl rand -base64 48 | tr -d '\n')" +jwt_refresh_key="$(openssl rand -base64 48 | tr -d '\n')" + +cat > "$env_file" < "$compose_override" <<'EOF' +services: + postgresql: + ports: !override [] + heimdall: + image: heimdall:${ACCEPTANCE_PROJECT}-central + ports: !override + - "127.0.0.1:${WEB_PORT}:8080" +EOF + +cat > "$failure_override" <<'EOF' +services: + heimdall: + environment: + DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD} + restart: "no" +EOF + +cat > "$recovery_override" <<'EOF' +services: + heimdall: + environment: + DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD} + restart: "no" +EOF + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" down --volumes --remove-orphans || cleanup_failed=1 + + containers="$(docker ps -aq --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1 + volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1 + networks="$(docker network ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1 + [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1 + + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + + python3 - "$env_file" "$compose_override" "$failure_override" "$recovery_override" <<'PY' || cleanup_failed=1 +import pathlib +import sys +for name in sys.argv[1:]: + pathlib.Path(name).unlink(missing_ok=True) +PY + rmdir -- "$temp_dir" || cleanup_failed=1 + + if (( cleanup_failed )); then + printf 'Disposable migration recipe cleanup failed for project %s\n' "$project" >&2 + status=1 + else + printf 'Cleanup verified: project containers/volumes/network and exact tag absent (%s).\n' "${local_image_tags[*]}" + fi + exit "$status" +} +trap cleanup EXIT + +for tag in "${local_image_tags[@]}"; do + if docker image inspect "$tag" >/dev/null 2>&1; then + printf 'Unique acceptance image tag already exists: %s\n' "$tag" >&2 + exit 1 + fi +done + +compose() { + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" "$@" +} + +compose config --quiet +compose up -d --build +base_url="http://127.0.0.1:$web_port" + +wait_healthy() { + for attempt in $(seq 1 120); do + if curl --fail --silent "$base_url/healthz" -o /dev/null; then return 0; fi + sleep 2 + done + return 1 +} + +wait_healthy || { echo 'Central did not become healthy after first migration.' >&2; exit 1; } +echo 'First boot: PostgreSQL fresh schema migrated; Central healthz returned HTTP 200.' + +compose restart heimdall +wait_healthy || { echo 'Central did not recover against the migrated database.' >&2; exit 1; } +echo 'Restart: Central healthz returned HTTP 200 on the migrated schema.' + +postgres_container="$(compose ps -q postgresql)" +[[ -n "$postgres_container" ]] || { echo 'PostgreSQL container was not found.' >&2; exit 1; } +docker exec -i "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \ + -v probe_password="$probe_password" <<'SQL' +CREATE ROLE migration_probe LOGIN PASSWORD :'probe_password'; +SELECT format('GRANT CONNECT ON DATABASE %I TO migration_probe', current_database()) \gexec +GRANT USAGE ON SCHEMA public TO migration_probe; +GRANT CREATE ON SCHEMA public TO migration_probe; +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO migration_probe; +GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO migration_probe; +GRANT USAGE, CREATE ON SCHEMA hangfire TO migration_probe; +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA hangfire TO migration_probe; +GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA hangfire TO migration_probe; +REVOKE SELECT ON TABLE public."__EFMigrationsHistory" FROM migration_probe; +SQL + +compose -f "$failure_override" up -d --force-recreate heimdall +web_container="$(compose -f "$failure_override" ps -q heimdall)" +[[ -n "$web_container" ]] || { echo 'Central failure-test container was not found.' >&2; exit 1; } + +failure_state="" +for attempt in $(seq 1 90); do + failure_state="$(docker inspect -f '{{.State.Status}}' "$web_container" 2>/dev/null || true)" + [[ "$failure_state" == exited ]] && break + sleep 1 +done +[[ "$failure_state" == exited ]] || { echo 'Central did not exit on a permanent migration permission failure.' >&2; exit 1; } +failure_exit_code="$(docker inspect -f '{{.State.ExitCode}}' "$web_container")" +[[ "$failure_exit_code" != 0 ]] || { echo 'Central exited successfully despite the permanent migration failure.' >&2; exit 1; } + +failure_logs="$(docker logs "$web_container" 2>&1)" +application_logs="$(grep -E 'Applying database migrations \(attempt|Database migration attempt .* failed|Failed to apply database migrations after 5 attempts|Database migrations applied successfully|permission denied' <<<"$failure_logs" | grep -v 'HttpTransport: Envelope')" +attempt_count="$(grep -c 'Applying database migrations (attempt' <<<"$application_logs" || true)" +retry_count="$(grep -c 'Database migration attempt .* failed' <<<"$application_logs" || true)" +terminal_count="$(grep -c 'Failed to apply database migrations after 5 attempts' <<<"$application_logs" || true)" +success_count="$(grep -c 'Database migrations applied successfully' <<<"$application_logs" || true)" +[[ "$attempt_count" -eq 5 && "$retry_count" -eq 4 && "$terminal_count" -eq 1 && "$success_count" -eq 0 ]] || { + printf 'Retry log counts: attempts=%s retries=%s terminal=%s successes=%s\n' \ + "$attempt_count" "$retry_count" "$terminal_count" "$success_count" >&2 + grep -E 'Applying database migrations \(attempt|Database migration attempt|Failed to apply database migrations|Database migrations applied successfully' \ + <<<"$application_logs" | cut -c1-240 >&2 || true + echo 'Permanent failure did not show five attempts, four retries, one terminal failure, and zero success logs.' >&2 + exit 1 +} +grep -qi 'permission denied' <<<"$application_logs" || { + echo 'The synthetic failure did not report the expected history-table permission denial.' >&2 + exit 1 +} +echo 'Permanent failure: permission denied on migration history; five attempts, four retries, final Critical error, nonzero exit, no migration-success log.' + +docker exec "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \ + -c 'GRANT SELECT ON TABLE public."__EFMigrationsHistory" TO migration_probe;' >/dev/null +compose -f "$recovery_override" up -d --force-recreate heimdall +wait_healthy || { + echo 'Central did not recover after granting migration-history access.' >&2 + docker logs "$(compose -f "$recovery_override" ps -q heimdall)" 2>&1 \ + | grep -Ei 'failed|error|permission denied|database migration|migration.*success' \ + | grep -v 'HttpTransport: Envelope' | cut -c1-240 | tail -n 20 >&2 || true + exit 1 +} +echo 'Recovery: granting history-table SELECT allowed startup; Central healthz returned HTTP 200.' diff --git a/scripts/acceptance/heimdall-identity.sh b/scripts/acceptance/heimdall-identity.sh new file mode 100755 index 0000000..653cc7f --- /dev/null +++ b/scripts/acceptance/heimdall-identity.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')" +flow="${HEIMDALL_ACCEPTANCE_FLOW:-create-login}" +if [[ "$flow" != "create-login" && "$flow" != "2fa-cookie" ]]; then + echo 'HEIMDALL_ACCEPTANCE_FLOW must be create-login or 2fa-cookie' >&2 + exit 2 +fi +project="heimdall-auth-${flow}-${suffix}" +central_image="heimdall:${project}-central" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +env_file="$temp_dir/acceptance.env" +override_file="$temp_dir/compose.override.yml" +compose_file="$repo_root/docker/docker-compose.yml" +local_image_tags=("$central_image") +compose_port=$(python3 - <<'PY' +import socket +with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + print(sock.getsockname()[1]) +PY +) +web_port=$(python3 - <<'PY' +import socket +with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + print(sock.getsockname()[1]) +PY +) + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" \ + down --volumes --remove-orphans || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then + printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \ + "${containers:-}" "${volumes:-}" "${networks:-}" >&2 + cleanup_failed=1 + else + printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project" + fi + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + if docker image inspect "$tag" >/dev/null 2>&1; then + printf 'Recipe image remains: %s\n' "$tag" >&2 + cleanup_failed=1 + else + printf 'Verified recipe image absent: %s\n' "$tag" + fi + done + rm -f -- "$env_file" "$override_file" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then status=1; fi + exit "$status" +} +trap cleanup EXIT + +pg_password=$(python3 - <<'PY' +import secrets, string +alphabet=string.ascii_letters+string.digits +print(''.join(secrets.choice(alphabet) for _ in range(40))) +PY +) +jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n') +refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n') +admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n') +admin_password="${admin_password}Aa1!" +cat >"$env_file" <"$override_file" </dev/null 2>&1; do + if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi + sleep 2 +done +printf 'Central /healthz: HTTP 200\n' + +BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY' +import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request +base=os.environ['BASE_URL'] +flow=os.environ['ACCEPTANCE_FLOW'] +def request(method, path, body=None, token=None, cookie=None): + headers={'Content-Type':'application/json'} + if token: headers['Authorization']='Bearer '+token + if cookie: headers['Cookie']=cookie + data=json.dumps(body).encode() if body is not None else None + req=urllib.request.Request(base+path, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=20) as response: + return response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + return error.code, error.read(), error.headers +def post(path, body, token=None): + status, payload, _=request('POST', path, body, token) + return status, payload +def totp(key): + secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8)) + counter=int(time.time())//30 + digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest() + offset=digest[-1]&15 + value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff + return f'{value%1000000:06d}' +status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'}) +if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}') +if flow == 'create-login': + status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']}) + if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}') + admin=json.loads(payload)['accessToken'] + for role in ('Viewer','Supervisor'): + email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test' + password='CreateLogin!'+secrets.token_urlsafe(18)+'A1' + status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin) + if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}') + user_id=json.loads(payload)['id'] + status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin) + if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}') + status,payload=post('/api/auth/login', {'email':email,'password':password}) + if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}') + if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token') + print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)') +else: + admin=json.loads(bootstrap_payload)['accessToken'] + email='acceptance-admin@heimdall.test' + password=os.environ['ACCEPTANCE_ADMIN_PASSWORD'] + status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin) + if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}') + shared_key=json.loads(payload)['sharedKey'] + # ResetAuthenticatorKey rotates the security stamp; renew the setup session + # before the authenticated confirmation call. + status,payload=post('/api/auth/login', {'email':email,'password':password}) + if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}') + admin=json.loads(payload)['accessToken'] + status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin) + if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}') + status,payload=post('/api/auth/login', {'email':email,'password':password}) + if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}') + challenge=json.loads(payload) + if not challenge.get('requires2fa') or not challenge.get('challengeId'): + raise SystemExit('2FA login did not return an authenticator challenge') + status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)}) + if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}') + access_token=json.loads(payload)['accessToken'] + status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token}) + if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}') + set_cookie=headers.get('Set-Cookie','').split(';',1)[0] + if not set_cookie.startswith('.Heimdall.Auth='): + raise SystemExit('2FA cookie sign-in returned no auth cookie') + status,_,_=request('GET','/api/users/me',cookie=set_cookie) + if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}') + print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)') +PY diff --git a/scripts/acceptance/optional-server-services.sh b/scripts/acceptance/optional-server-services.sh new file mode 100755 index 0000000..60fafd3 --- /dev/null +++ b/scripts/acceptance/optional-server-services.sh @@ -0,0 +1,266 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')" +project="heimdall-optional-services-${suffix}" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +install_root="$temp_dir/install-root" +secret_dir="$install_root/optional/secrets" +backup_scripts_dir="$install_root/optional/scripts" +env_file="$temp_dir/acceptance.env" +override_file="$temp_dir/compose.override.yml" +turn_log="$temp_dir/turn-client.log" +rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml" +coturn_compose="$repo_root/docker/docker-compose.coturn.yml" +backup_compose="$repo_root/docker/docker-compose.backup.yml" +backup_scripts=(backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh) +local_image_tags=() +mkdir -p "$secret_dir" "$backup_scripts_dir" + +compose() { + docker compose --project-directory "$install_root" --env-file "$env_file" \ + -f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \ + -p "$project" "$@" +} + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + compose down --volumes --remove-orphans || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" ]]; then + # `compose run --rm` may leave a one-off test container behind if the + # client exits during shutdown; remove only containers carrying this + # recipe's unique Compose project label. + while IFS= read -r container; do + [[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1 + done <<< "$containers" + fi + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then + printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \ + "${containers:-}" "${volumes:-}" "${networks:-}" >&2 + cleanup_failed=1 + else + printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project" + fi + if ((${#local_image_tags[@]} == 0)); then + printf 'No local images built; upstream service images retained.\n' + fi + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + if docker image inspect "$tag" >/dev/null 2>&1; then + printf 'Recipe image remains: %s\n' "$tag" >&2 + cleanup_failed=1 + else + printf 'Verified recipe image absent: %s\n' "$tag" + fi + done + rm -f -- "$env_file" "$override_file" "$turn_log" \ + "$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \ + "$secret_dir/coturn_secret" "$secret_dir/db_password" || cleanup_failed=1 + for name in "${backup_scripts[@]}"; do + rm -f -- "$backup_scripts_dir/$name" || cleanup_failed=1 + done + rmdir -- "$backup_scripts_dir" "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if ((cleanup_failed)); then + printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2 + status=1 + fi + exit "$status" +} +trap cleanup EXIT + +read -r rustfs_api_port rustfs_console_port coturn_port relay_min relay_max < <(python3 - <<'PY' +import random, socket +used=set() +def free_port(protocols): + for port in random.sample(range(20000, 60000), 2000): + if port in used: continue + sockets=[] + try: + for kind in protocols: + sock=socket.socket(socket.AF_INET,kind) + sock.bind(('127.0.0.1',port)) + sockets.append(sock) + used.add(port) + return port + except OSError: + pass + finally: + for sock in sockets: sock.close() + raise SystemExit('No free loopback ports found') +def free_udp_range(width): + for start in random.sample(range(25000, 55000-width), 2000): + if any(port in used for port in range(start,start+width)): continue + sockets=[] + try: + for port in range(start,start+width): + sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + sock.bind(('127.0.0.1',port)) + sockets.append(sock) + used.update(range(start,start+width)) + return start,start+width-1 + except OSError: + pass + finally: + for sock in sockets: sock.close() + raise SystemExit('No free contiguous UDP relay ports found') +print(free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,)), + free_port((socket.SOCK_STREAM,socket.SOCK_DGRAM)), *free_udp_range(20)) +PY +) +rustfs_access_key="acceptance$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" +rustfs_secret_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n') +coturn_secret=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n') +coturn_username=acceptance +printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key" +printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key" +printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret" +printf 'acceptance-db-password-%s' "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" > "$secret_dir/db_password" +for name in "${backup_scripts[@]}"; do + cp "$repo_root/docker/scripts/$name" "$backup_scripts_dir/$name" +done +chmod 600 "$secret_dir"/* +cat > "$env_file" < "$override_file" <<'EOF' +services: + turn-test: + image: coturn/coturn:4.6 + pull_policy: always + profiles: [acceptance] + entrypoint: ["/bin/sh", "-c"] + command: + - >- + exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478 + -W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn + environment: + COTURN_SECRET: ${COTURN_SECRET} + COTURN_USERNAME: ${COTURN_USERNAME} + depends_on: + - coturn +networks: + heimdall-net: + name: ${ACCEPTANCE_NETWORK} + external: false +EOF + +printf 'Disposable project: %s\nLocal images built: none\n' "$project" +compose config --quiet +compose config --format json | INSTALL_ROOT="$install_root" python3 -c ' +import json, os, sys +config = json.load(sys.stdin) +root = os.environ["INSTALL_ROOT"] +expected = { + "rustfs_access_key": os.path.join(root, "optional/secrets/rustfs_access_key"), + "rustfs_secret_key": os.path.join(root, "optional/secrets/rustfs_secret_key"), + "coturn_secret": os.path.join(root, "optional/secrets/coturn_secret"), +} +actual = {name: config["secrets"][name]["file"] for name in expected} +if actual != expected: + raise SystemExit("Compose secret bind mounts do not resolve under the installer root") +print("Verified RustFS and coturn secret bind mounts resolve under the installer root.") +' +docker compose --project-directory "$install_root/optional" --env-file "$env_file" \ + -f "$backup_compose" --project-name "${project}-backup" config --format json | + BACKUP_PROJECT_DIRECTORY="$install_root/optional" python3 -c ' +import json, os, sys +config = json.load(sys.stdin) +project_directory = os.environ["BACKUP_PROJECT_DIRECTORY"] +expected_secret = os.path.join(project_directory, "secrets/db_password") +expected_scripts = os.path.join(project_directory, "scripts") +actual_secret = config["secrets"]["db_password"]["file"] +scripts_mount = next((mount for mount in config["services"]["backup"]["volumes"] + if mount.get("target") == "/scripts"), None) +if actual_secret != expected_secret or scripts_mount is None or scripts_mount.get("source") != expected_scripts: + raise SystemExit("Backup secret or script bind mounts do not resolve under optional/") +print("Verified backup secret and scripts resolve under the installer optional directory.") +' +compose up -d rustfs coturn + +base_url="http://127.0.0.1:$rustfs_api_port" +deadline=$((SECONDS + 180)) +until curl -fsS "$base_url/health" >/dev/null 2>&1; do + if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi + sleep 2 +done +printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \ + "$rustfs_api_port" "$rustfs_console_port" + +RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \ +RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY' +import datetime, hashlib, hmac, os, urllib.error, urllib.request + +access = os.environ['RUSTFS_ACCESS_KEY'] +secret = os.environ['RUSTFS_SECRET_KEY'] +host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT'] +path = '/acceptance' +payload_hash = hashlib.sha256(b'').hexdigest() +now = datetime.datetime.now(datetime.timezone.utc) +amz_date = now.strftime('%Y%m%dT%H%M%SZ') +date = now.strftime('%Y%m%d') +canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n' +signed_headers = 'host;x-amz-content-sha256;x-amz-date' +canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}' +scope = f'{date}/us-east-1/s3/aws4_request' +to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest() +def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest() +key = sign(('AWS4' + secret).encode(), date) +key = sign(key, 'us-east-1') +key = sign(key, 's3') +key = sign(key, 'aws4_request') +signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest() +authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}' +request = urllib.request.Request( + f'http://{host}{path}', data=b'', method='PUT', + headers={'Host': host, 'x-amz-content-sha256': payload_hash, + 'x-amz-date': amz_date, 'Authorization': authorization}) +try: + with urllib.request.urlopen(request, timeout=15) as response: + if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status') +except urllib.error.HTTPError as error: + from xml.etree import ElementTree + body = error.read() + try: code = ElementTree.fromstring(body).findtext('{*}Code') + except ElementTree.ParseError: code = None + raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})') +PY +printf 'RustFS S3 authenticated bucket creation: passed.\n' + +if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then + echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2 + sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=/Ig' "$turn_log" | tail -30 >&2 || true + echo 'sanitized coturn server diagnostics:' >&2 + compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \ + sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=/Ig' | tail -40 >&2 || true + exit 1 +fi +printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \ + "$coturn_port" "$relay_min" "$relay_max" + +for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do + if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then + echo 'A generated service secret appeared in container logs.' >&2 + exit 1 + fi +done +printf 'Verified generated service secrets are absent from container logs.\n' diff --git a/scripts/acceptance/renovate-automation.sh b/scripts/acceptance/renovate-automation.sh new file mode 100755 index 0000000..28c8a4e --- /dev/null +++ b/scripts/acceptance/renovate-automation.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +project="heimdall-renovate-acceptance-$(date -u +%Y%m%d%H%M%S)-$RANDOM" +repo_root=$(git rev-parse --show-toplevel) +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +compose_file="$temp_dir/compose.yml" +runner_file="$temp_dir/acceptance.mjs" +cert_file="$temp_dir/mock.crt" +key_file="$temp_dir/mock.key" +local_image_tags=() +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then cleanup_failed=1; fi + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + rm -f -- "$compose_file" "$runner_file" "$cert_file" "$key_file" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then + echo "Disposable Compose cleanup failed for $project" >&2 + status=1 + else + echo "Verified no project containers, volumes, or networks; no local images built ($project)" + fi + exit "$status" +} +trap cleanup EXIT + +openssl req -x509 -newkey rsa:2048 -nodes -keyout "$key_file" -out "$cert_file" \ + -subj "/CN=localhost" -addext "subjectAltName=IP:127.0.0.1" -days 1 >/dev/null 2>&1 +cat > "$runner_file" <<'NODE' +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createServer } from 'node:https'; +import { checkGiteaAccess } from '/workspace/scripts/ci/renovate-preflight.mjs'; + +const requests = []; +const server = createServer({ + key: readFileSync('/acceptance/mock.key'), + cert: readFileSync('/acceptance/mock.crt'), +}, (request, response) => { + requests.push({ path: request.url, authorization: request.headers.authorization }); + if (request.headers.authorization !== 'token synthetic-valid') { + response.writeHead(401, { 'content-type': 'application/json' }); + response.end('{"message":"credential rejected"}'); + return; + } + response.writeHead(200, { 'content-type': 'application/json' }); + response.end('{}'); +}); + +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +try { + const endpoint = `https://127.0.0.1:${server.address().port}/api/v1`; + await checkGiteaAccess(endpoint, 'synthetic-valid'); + await assert.rejects( + checkGiteaAccess(endpoint, 'synthetic-invalid'), + error => error.message.includes('HTTP 401') && + error.message.includes('RENOVATE_TOKEN') && + !error.message.includes('synthetic-invalid') && + !error.message.includes('credential rejected'), + ); + assert.deepEqual(requests.map(({ path }) => path), [ + '/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall', + '/api/v1/user', + ]); + assert.ok(requests.every(({ authorization }) => + ['token synthetic-valid', 'token synthetic-invalid'].includes(authorization))); + console.log('HTTPS mock preflight accepted valid and rejected invalid synthetic credentials without exposing response details.'); +} finally { + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); +} +NODE +cat > "$compose_file" </dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then + printf 'Docker Compose is required for live source-change acceptance.\n' >&2 + rmdir -- "$temp_dir" + exit 2 +fi + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + if [[ -f "$compose_file" ]]; then + docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1 + fi + containers="$(docker ps -aq --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1 + volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1 + networks="$(docker network ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1 + [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1 + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + rm -f -- "$compose_file" "$source_archive" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then + printf 'Disposable acceptance cleanup failed for project %s\n' "$project" >&2 + status=1 + fi + exit "$status" +} +trap cleanup EXIT + +python3 - "$compose_file" "$source_archive" <<'PY' +import json +import sys + +compose_path, archive_path = sys.argv[1:] +test_command = """set -euo pipefail +mkdir -p /tmp/heimdall-source +tar -xf /source.tar -C /tmp/heimdall-source +cd /tmp/heimdall-source +dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode +dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --configuration Release -m:1 --filter FullyQualifiedName~LiveCameraRelayServiceTests +""" +document = { + "services": { + "source-change-tests": { + "image": "mcr.microsoft.com/dotnet/sdk:10.0", + "entrypoint": ["bash", "-euc"], + "command": [test_command], + "volumes": [f"{archive_path}:/source.tar:ro"], + } + } +} +with open(compose_path, "w", encoding="utf-8") as compose_file: + json.dump(document, compose_file) +PY + +# Archive only tracked and non-ignored working files; exclude multi-gigabyte +# ignored build/model outputs from the disposable SDK container. +git -C "$repo_root" ls-files -z --cached --others --exclude-standard | + tar -C "$repo_root" --null -T - -cf "$source_archive" + +printf 'Project: %s\n' "$project" +printf 'Local images built: none (upstream .NET SDK image only)\n' +docker compose -p "$project" -f "$compose_file" up --abort-on-container-exit --exit-code-from source-change-tests