Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
511fbfce7b | ||
|
|
78ff15799e | ||
|
|
aef04552a8 | ||
|
|
7c0c8ecf46 | ||
|
|
dc8a313deb | ||
|
|
9fd9c75f94 | ||
|
|
fcc719d627 | ||
|
|
bc7ddccfe3 | ||
|
|
6e7f593cb3 | ||
|
|
622abb4454 |
No files matched your search
@@ -75,7 +75,7 @@ jobs:
|
||||
needs: [changes]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine@sha256:b0f9560a2de083e2cc7382e75f808c7381a32852a7ec49117deedb300e552b24
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -208,7 +208,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -253,7 +253,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -298,7 +298,7 @@ jobs:
|
||||
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
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
# Server/PWA: restore the complete project graph from locked dependencies.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
@@ -8,7 +8,7 @@ COPY install/ ./install/
|
||||
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
WORKDIR /app
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CPU agent: use glibc for ONNX native dependencies. GPU variants need a
|
||||
# separately validated .NET/native-library runtime and are not published here.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
ARG TARGET_RUNTIME=cpu
|
||||
@@ -10,7 +10,7 @@ COPY src/ ./src/
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
WORKDIR /app
|
||||
ARG DOCKER_CLI_VERSION=29.9.3
|
||||
ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Optional NVIDIA Agent image. ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9.
|
||||
# NVIDIA amd64 runtime image digest is pinned; it includes CUDA 12.8.1/cuDNN 9.8.0.87.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
@@ -9,7 +9,7 @@ RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRunti
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out \
|
||||
-p:HeimdallOnnxRuntime=GPU -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee AS dotnet-runtime
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e AS dotnet-runtime
|
||||
|
||||
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
@@ -3,16 +3,41 @@ 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
|
||||
# Local Compose secrets are read-only bind mounts and preserve the
|
||||
# installer's 0600 owner-only permissions. Read the mounted file as a
|
||||
# short-lived root initializer, write a private config into tmpfs, then
|
||||
# run turnserver as nobody. The upstream binary does not exec with a
|
||||
# reduced capability set; no-new-privileges still prevents elevation.
|
||||
user: "0:0"
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
ports:
|
||||
- "${COTURN_PORT:-3478}:3478/tcp"
|
||||
- "${COTURN_PORT:-3478}:3478/udp"
|
||||
- "${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}:${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}/udp"
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n'
|
||||
"$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}"
|
||||
"${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}"
|
||||
> /run/coturn/turnserver.conf;
|
||||
printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf;
|
||||
if [ -n "$$COTURN_EXTERNAL_IP" ]; then
|
||||
printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf;
|
||||
fi;
|
||||
chown 65534:65534 /run/coturn /run/coturn/turnserver.conf;
|
||||
exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody
|
||||
environment:
|
||||
COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-}
|
||||
secrets:
|
||||
- coturn_secret
|
||||
restart: unless-stopped
|
||||
|
||||
secrets:
|
||||
coturn_secret:
|
||||
file: ./secrets/coturn_secret
|
||||
file: ./optional/secrets/coturn_secret
|
||||
@@ -5,6 +5,34 @@ services:
|
||||
image: rustfs/rustfs:latest
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
# Compose file secrets are read-only bind mounts locally. The installer
|
||||
# deliberately creates them mode 0600, owned by root; RustFS runs as UID
|
||||
# 10001 and cannot read that source directly. A small root init copies the
|
||||
# files into tmpfs, then drops privileges before starting the server.
|
||||
user: "0:0"
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
- DAC_OVERRIDE
|
||||
- SETGID
|
||||
- SETUID
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
- /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key;
|
||||
cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key;
|
||||
chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key;
|
||||
exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs
|
||||
ports:
|
||||
- "${RUSTFS_API_PORT:-9000}:9000"
|
||||
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
|
||||
@@ -13,8 +41,8 @@ services:
|
||||
RUSTFS_ADDRESS: 0.0.0.0:9000
|
||||
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
|
||||
RUSTFS_CONSOLE_ENABLE: "true"
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
|
||||
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key
|
||||
RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key
|
||||
secrets:
|
||||
- rustfs_access_key
|
||||
- rustfs_secret_key
|
||||
@@ -30,9 +58,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:
|
||||
|
||||
@@ -201,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:
|
||||
|
||||
@@ -44,8 +44,27 @@ if ($script:PackageReleaseVersion -eq 'unversioned') {
|
||||
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.' }
|
||||
$digestProperty = $installerAsset.PSObject.Properties['digest']
|
||||
$assetDigest = if ($null -ne $digestProperty) { $digestProperty.Value } else { $null }
|
||||
if ($null -ne $assetDigest) {
|
||||
if ($assetDigest -isnot [string] -or $assetDigest -notmatch '^sha256:[A-Fa-f0-9]{64}$') {
|
||||
throw 'Le digest Gitea du bundle est invalide.'
|
||||
}
|
||||
$expectedHash = $assetDigest.Substring(7)
|
||||
} else {
|
||||
$checksumName = "$installerName.sha256"
|
||||
$checksumAsset = @($release.assets) | Where-Object { $_.name -eq $checksumName } | Select-Object -First 1
|
||||
if (-not $checksumAsset -or $checksumAsset.browser_download_url -notmatch '^https://') {
|
||||
throw 'La release ne fournit pas le checksum publié du bundle.'
|
||||
}
|
||||
$checksumPath = Join-Path $bootstrapRoot 'installers.zip.sha256'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $checksumAsset.browser_download_url -OutFile $checksumPath -TimeoutSec 30
|
||||
$checksumText = [IO.File]::ReadAllText($checksumPath)
|
||||
$escapedName = [Regex]::Escape($installerName)
|
||||
$checksumMatches = [Regex]::Matches($checksumText, "(?m)^([A-Fa-f0-9]{64})\s+\*?$escapedName\s*$")
|
||||
if ($checksumMatches.Count -ne 1) { throw 'Le checksum publié du bundle est invalide.' }
|
||||
$expectedHash = $checksumMatches[0].Groups[1].Value
|
||||
}
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $installerAsset.browser_download_url -OutFile $bundlePath -TimeoutSec 120
|
||||
$actualHash = (Get-FileHash -LiteralPath $bundlePath -Algorithm SHA256).Hash
|
||||
if ($actualHash -ne $expectedHash) { throw 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' }
|
||||
|
||||
@@ -62,9 +62,25 @@ if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
|
||||
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;
|
||||
}
|
||||
asset_digest_type="$(jq -r 'if has("digest") then (.digest | type) else "missing" end' <<<"$asset_json")"
|
||||
asset_digest="$(jq -r '.digest // empty' <<<"$asset_json")"
|
||||
if [[ "$asset_digest_type" != null && "$asset_digest_type" != missing ]]; then
|
||||
[[ "$asset_digest_type" == string && "$asset_digest" =~ ^sha256:[A-Fa-f0-9]{64}$ ]] || {
|
||||
echo 'Le digest Gitea du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
expected_sha256="${asset_digest#sha256:}"
|
||||
else
|
||||
checksum_asset_json="$(jq -ce --arg name "$installer_asset.sha256" '.assets[]? | select(.name == $name)' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release ne fournit pas le checksum publié du bundle.' >&2; exit 1;
|
||||
}
|
||||
checksum_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$checksum_asset_json")" || {
|
||||
echo 'URL HTTPS du checksum du bundle invalide.' >&2; exit 1;
|
||||
}
|
||||
curl --fail --silent --show-error --location "$checksum_url" --output "$bootstrap_dir/installers.zip.sha256"
|
||||
expected_sha256="$(awk -v name="$installer_asset" '$2 == name && $1 ~ /^[A-Fa-f0-9]{64}$/ { print tolower($1); count++ } END { if (count != 1) exit 1 }' "$bootstrap_dir/installers.zip.sha256")" || {
|
||||
echo 'Le checksum publié du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
curl --fail --silent --show-error --location "$installer_url" --output "$bootstrap_dir/installers.zip"
|
||||
actual_sha256="$(sha256sum "$bootstrap_dir/installers.zip" | cut -d ' ' -f 1)"
|
||||
[[ "${actual_sha256,,}" == "${expected_sha256,,}" ]] || { echo 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' >&2; exit 1; }
|
||||
|
||||
@@ -131,13 +131,27 @@ output = args[args.index('--output') + 1]
|
||||
with open(os.environ['OFFLINE_CURL_LOG'], 'a') as log:
|
||||
log.write(url + '\n')
|
||||
if url.endswith('/releases/latest'):
|
||||
installer_path = os.environ['OFFLINE_INSTALLER_ZIP']
|
||||
if os.environ.get('OFFLINE_BAD_API_DIGEST') == '1':
|
||||
digest = 'invalid'
|
||||
elif os.environ.get('OFFLINE_NULL_ASSET_DIGEST') == '1':
|
||||
digest = None
|
||||
else:
|
||||
digest = 'sha256:' + hashlib.sha256(open(installer_path,'rb').read()).hexdigest()
|
||||
payload = json.dumps({'tag_name':'1.2.3','assets':[{
|
||||
'name':'heimdall-installers-1.2.3.zip',
|
||||
'digest':'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()
|
||||
'digest':digest,
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}, {
|
||||
'name':'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]}).encode()
|
||||
open(output, 'wb').write(payload)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip.sha256':
|
||||
if os.environ.get('OFFLINE_BAD_CHECKSUM') == '1':
|
||||
open(output, 'w').write('0' * 64 + ' heimdall-installers-1.2.3.zip\n')
|
||||
else:
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'] + '.sha256', output)
|
||||
else:
|
||||
sys.exit(22)
|
||||
'''
|
||||
@@ -200,7 +214,9 @@ else:
|
||||
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'}]})
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}, {
|
||||
'name': 'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]})
|
||||
elif path.endswith('/releases/tags/1.2.3'):
|
||||
self._json(404, {'message': 'not found'})
|
||||
elif path.endswith('/releases/7301/assets'):
|
||||
@@ -252,7 +268,7 @@ else:
|
||||
if path.endswith('/releases/7301'):
|
||||
assert set(release_state['assets']) >= {
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'heimdall-installers-1.2.3.zip'}
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256'}
|
||||
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
release_state['release']['draft'] = body['draft']
|
||||
@@ -318,6 +334,65 @@ else:
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
checksum_log = curl_log
|
||||
checksum_env = launcher_env.copy()
|
||||
checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(checksum_log),
|
||||
'OFFLINE_NULL_ASSET_DIGEST': '1',
|
||||
'HEIMDALL_INSTALLER_VERSION': '',
|
||||
})
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=checksum_env, capture_output=True, text=True)
|
||||
checksum_output = checksum_launcher.stdout + checksum_launcher.stderr
|
||||
assert checksum_launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
|
||||
f'checksum fallback exit={checksum_launcher.returncode}; '
|
||||
f'URLs={checksum_log.read_text() if checksum_log.exists() else "<none>"}; '
|
||||
+ checksum_output[-2000:])
|
||||
assert checksum_log.read_text().splitlines() == [
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
], (f'checksum fallback did not request expected assets; '
|
||||
f'HEIMDALL_INSTALLER_VERSION={checksum_env.get("HEIMDALL_INSTALLER_VERSION")!r}; '
|
||||
f'log={checksum_log.read_text() if checksum_log.exists() else "<missing>"}; '
|
||||
f'returncode={checksum_launcher.returncode}; output={checksum_output[-2000:]}')
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
bad_checksum_log = temp / 'installer-bootstrap-bad-checksum-urls.txt'
|
||||
bad_checksum_env = checksum_env.copy()
|
||||
bad_checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(bad_checksum_log),
|
||||
'OFFLINE_BAD_CHECKSUM': '1',
|
||||
})
|
||||
bad_checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=bad_checksum_env, capture_output=True, text=True)
|
||||
bad_checksum_output = bad_checksum_launcher.stdout + bad_checksum_launcher.stderr
|
||||
assert bad_checksum_launcher.returncode != 0 and 'ne correspond pas à la release' in bad_checksum_output, (
|
||||
f'bad checksum was not rejected; returncode={bad_checksum_launcher.returncode}; '
|
||||
f'output={bad_checksum_output[-2000:]}')
|
||||
assert bad_checksum_log.read_text().splitlines() == [
|
||||
bad_checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
invalid_digest_log = temp / 'installer-bootstrap-invalid-digest-urls.txt'
|
||||
invalid_digest_env = checksum_env.copy()
|
||||
invalid_digest_env.update({
|
||||
'OFFLINE_CURL_LOG': str(invalid_digest_log),
|
||||
'OFFLINE_BAD_API_DIGEST': '1',
|
||||
})
|
||||
invalid_digest_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=invalid_digest_env, capture_output=True, text=True)
|
||||
invalid_digest_output = invalid_digest_launcher.stdout + invalid_digest_launcher.stderr
|
||||
assert invalid_digest_launcher.returncode != 0 and 'digest Gitea du bundle est invalide' in invalid_digest_output, (
|
||||
f'malformed API digest was not rejected; returncode={invalid_digest_launcher.returncode}; '
|
||||
f'output={invalid_digest_output[-2000:]}')
|
||||
assert invalid_digest_log.read_text().splitlines() == [
|
||||
invalid_digest_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
]
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
env['GITEA_TOKEN'] = RELEASE_TOKEN
|
||||
env['BEFORE_SHA'] = commit + '^'
|
||||
@@ -379,8 +454,12 @@ else:
|
||||
assert "PackageReleaseVersion = '1.2.3'" in windows_script
|
||||
assert 'install/install-agent.sh' in bundle.namelist()
|
||||
assert 'install/install-agent.ps1' in bundle.namelist()
|
||||
checksum_asset = packages / 'heimdall-installers-1.2.3.zip.sha256'
|
||||
checksum, filename = checksum_asset.read_text().split()
|
||||
assert filename == 'heimdall-installers-1.2.3.zip'
|
||||
assert checksum == hashlib.sha256((packages / filename).read_bytes()).hexdigest()
|
||||
expected_release_assets = {
|
||||
'heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'agent-image.json', 'agent-image-gpu.json',
|
||||
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
|
||||
|
||||
@@ -64,4 +64,6 @@ Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
|
||||
installer_bundle="artifacts/packages/heimdall-installers-$version.zip"
|
||||
(cd artifacts/packages && sha256sum "$(basename "$installer_bundle")" > "$(basename "$installer_bundle").sha256")
|
||||
printf '%s' "$version" > artifacts/version
|
||||
@@ -30,15 +30,16 @@ def request(path, method='GET', body=None, content_type='application/json', miss
|
||||
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
|
||||
package_root = Path('artifacts/packages')
|
||||
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
|
||||
installer_checksum = package_root / f'{installer_bundle.name}.sha256'
|
||||
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
|
||||
required_assets = [installer_bundle, package_root / 'agent-release-public.pem',
|
||||
required_assets = [installer_bundle, installer_checksum, package_root / 'agent-release-public.pem',
|
||||
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
|
||||
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
|
||||
if any(not path.is_file() for path in required_assets) or not agent_archives:
|
||||
raise SystemExit('Installer bundle or signed Agent update assets are missing')
|
||||
# CI provenance, image digests, and 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.
|
||||
# CI provenance, image digests, and general checksum bookkeeping stay in the
|
||||
# build artifacts. Publish the installer bundle's checksum as a sidecar so
|
||||
# bootstraps can verify it when the Gitea asset API omits its digest field.
|
||||
package_files = sorted([*required_assets, *agent_archives])
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
|
||||
@@ -279,7 +279,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
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':
|
||||
names = ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
names = ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
|
||||
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
|
||||
@@ -289,7 +289,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
directory = Path(temp)/'artifacts/packages'
|
||||
directory.mkdir(parents=True)
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'1.2.3'}))
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
|
||||
(directory/name).write_bytes(b'archive')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -9,14 +9,18 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
|
||||
|
||||
## Implementation path
|
||||
|
||||
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central.
|
||||
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled.
|
||||
- Agent status reports require the API key to resolve to the same Agent ID in the route and the camera to be assigned to that Agent. Authenticate and authorize both resources with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`.
|
||||
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
|
||||
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
|
||||
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
|
||||
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
|
||||
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
|
||||
|
||||
## Local verification
|
||||
|
||||
The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract.
|
||||
|
||||
Run the focused Agent lifecycle suites:
|
||||
|
||||
```bash
|
||||
@@ -51,3 +55,9 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
|
||||
## Sixth source-built run
|
||||
|
||||
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
|
||||
|
||||
## Camera status contract acceptance
|
||||
|
||||
For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, reject its report before camera assignment, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled.
|
||||
|
||||
A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence.
|
||||
@@ -5,6 +5,8 @@ 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.
|
||||
|
||||
@@ -5,6 +5,8 @@ description: Build and acceptance-test Heimdall changes in a disposable Docker C
|
||||
|
||||
# Disposable Compose acceptance
|
||||
|
||||
Follow [Infisical secrets](../infisical-secrets/SKILL.md) when the surrounding task also needs real credentials. Acceptance projects must always use generated synthetic values and must never retrieve deployment secrets from Infisical.
|
||||
|
||||
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
|
||||
|
||||
When implementation or acceptance preparation has independent branches, use [parallel development with Orca](../parallel-development/SKILL.md) to assign bounded work. Keep the final Compose run, cleanup verification, and acceptance evidence under one coordinator so the combined change is validated as a whole.
|
||||
|
||||
@@ -11,4 +11,6 @@ Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime lay
|
||||
|
||||
For acceptance, build Central, CPU Agent, and NVIDIA Agent from the changed checkout under unique Compose image tags with synthetic credentials, loopback ports, project-scoped volumes/network, and an EXIT cleanup trap. Verify Central health and the native Agent installer and supervisor URLs; build the NVIDIA image without claiming GPU runtime validation. Scan all three built images with the same pinned Trivy version, vulnerability DB repositories, and HIGH/CRITICAL exit policy used by `scripts/ci/security.sh`. A passing acceptance requires zero HIGH/CRITICAL findings, successful teardown, no project containers/volumes/networks, and removal plus absence checks for every exact local tag. Retain upstream base and scanner images.
|
||||
|
||||
When Trivy reports fixed .NET runtime advisories, update the pinned SDK and ASP.NET runtime manifest-list digests together across all three Dockerfiles and every SDK container in `.gitea/workflows/build.yml`. CI must use the SDK matching the updated lockfile, or locked restore fails against stale SDK reference assets. Confirm the new tags and digests against Microsoft's .NET release notes and `docker buildx imagetools inspect`; keep the SDK major/minor aligned with `global.json`. For the November 2026 ASP.NET Core 10.0.15 security update, the `10.0-noble` tags must resolve to images containing runtime 10.0.15, which fixes CVE-2026-114146, CVE-2026-114147, and CVE-2026-114149. Do not suppress these findings or change the CI severity threshold.
|
||||
|
||||
The CI image scan is a merge gate. Do not publish or merge around a failed scan; inspect the report and correct the affected package, then rerun the complete workflow. Keep Gitea issue evidence split between disposable local acceptance and the actual CI publication run.
|
||||
@@ -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,6 +5,10 @@ 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.
|
||||
|
||||
@@ -16,6 +16,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
|
||||
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
|
||||
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
|
||||
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
|
||||
- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`.
|
||||
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
|
||||
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
|
||||
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
|
||||
@@ -28,6 +29,8 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
|
||||
- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
|
||||
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
|
||||
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
|
||||
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
|
||||
- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
|
||||
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
|
||||
|
||||
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
|
||||
Executable
+182
@@ -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:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then status=1; fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
pg_password=$(python3 - <<'PY'
|
||||
import secrets, string
|
||||
alphabet=string.ascii_letters+string.digits
|
||||
print(''.join(secrets.choice(alphabet) for _ in range(40)))
|
||||
PY
|
||||
)
|
||||
jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password="${admin_password}Aa1!"
|
||||
cat >"$env_file" <<EOF
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
POSTGRES_DB=heimdall_acceptance
|
||||
POSTGRES_USER=heimdall_acceptance
|
||||
POSTGRES_PASSWORD=$pg_password
|
||||
POSTGRES_PORT=$compose_port
|
||||
WEB_PORT=$web_port
|
||||
DATABASE_URL="Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=heimdall_acceptance;Password=$pg_password;Timeout=60;Command Timeout=300"
|
||||
JWT__KEY=$jwt_key
|
||||
JWT__REFRESHKEY=$refresh_key
|
||||
JWT__ISSUER=heimdall-acceptance
|
||||
JWT__AUDIENCE=heimdall-acceptance
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
HEIMDALL_NETWORK_NAME=${project}-net
|
||||
EOF
|
||||
cat >"$override_file" <<EOF
|
||||
services:
|
||||
heimdall:
|
||||
image: $central_image
|
||||
environment:
|
||||
Database__MigrateOnStartup: "true"
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nCentral image: %s\n' "$project" "$central_image"
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" up -d --build
|
||||
|
||||
base_url="http://127.0.0.1:$web_port"
|
||||
deadline=$((SECONDS + 300))
|
||||
until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do
|
||||
if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
printf 'Central /healthz: HTTP 200\n'
|
||||
|
||||
BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY'
|
||||
import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request
|
||||
base=os.environ['BASE_URL']
|
||||
flow=os.environ['ACCEPTANCE_FLOW']
|
||||
def request(method, path, body=None, token=None, cookie=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['Authorization']='Bearer '+token
|
||||
if cookie: headers['Cookie']=cookie
|
||||
data=json.dumps(body).encode() if body is not None else None
|
||||
req=urllib.request.Request(base+path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as response:
|
||||
return response.status, response.read(), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read(), error.headers
|
||||
def post(path, body, token=None):
|
||||
status, payload, _=request('POST', path, body, token)
|
||||
return status, payload
|
||||
def totp(key):
|
||||
secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8))
|
||||
counter=int(time.time())//30
|
||||
digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest()
|
||||
offset=digest[-1]&15
|
||||
value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff
|
||||
return f'{value%1000000:06d}'
|
||||
status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'})
|
||||
if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}')
|
||||
if flow == 'create-login':
|
||||
status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']})
|
||||
if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}')
|
||||
admin=json.loads(payload)['accessToken']
|
||||
for role in ('Viewer','Supervisor'):
|
||||
email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test'
|
||||
password='CreateLogin!'+secrets.token_urlsafe(18)+'A1'
|
||||
status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin)
|
||||
if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}')
|
||||
user_id=json.loads(payload)['id']
|
||||
status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin)
|
||||
if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}')
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}')
|
||||
if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token')
|
||||
print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)')
|
||||
else:
|
||||
admin=json.loads(bootstrap_payload)['accessToken']
|
||||
email='acceptance-admin@heimdall.test'
|
||||
password=os.environ['ACCEPTANCE_ADMIN_PASSWORD']
|
||||
status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin)
|
||||
if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}')
|
||||
shared_key=json.loads(payload)['sharedKey']
|
||||
# ResetAuthenticatorKey rotates the security stamp; renew the setup session
|
||||
# before the authenticated confirmation call.
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}')
|
||||
admin=json.loads(payload)['accessToken']
|
||||
status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin)
|
||||
if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}')
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}')
|
||||
challenge=json.loads(payload)
|
||||
if not challenge.get('requires2fa') or not challenge.get('challengeId'):
|
||||
raise SystemExit('2FA login did not return an authenticator challenge')
|
||||
status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)})
|
||||
if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}')
|
||||
access_token=json.loads(payload)['accessToken']
|
||||
status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token})
|
||||
if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}')
|
||||
set_cookie=headers.get('Set-Cookie','').split(';',1)[0]
|
||||
if not set_cookie.startswith('.Heimdall.Auth='):
|
||||
raise SystemExit('2FA cookie sign-in returned no auth cookie')
|
||||
status,_,_=request('GET','/api/users/me',cookie=set_cookie)
|
||||
if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}')
|
||||
print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)')
|
||||
PY
|
||||
@@ -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.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: installer-checksum-acceptance
|
||||
description: Build and verify the versioned Central installer checksum asset and both server bootstrap verification paths.
|
||||
---
|
||||
|
||||
# Central installer checksum acceptance
|
||||
|
||||
Use this workflow when changing `install/install-server.sh`, `install/install-server.ps1`, `scripts/ci/package.sh`, or the release asset set in `scripts/ci/release-gitea.py`.
|
||||
|
||||
## Release contract
|
||||
|
||||
- `package.sh` creates `heimdall-installers-<version>.zip.sha256` beside the ZIP. Its single standard `sha256sum` line names the ZIP asset exactly, with no workspace-relative path.
|
||||
- `release-gitea.py` requires and publishes both files before making a release visible. The sidecar is part of the exact expected asset set for already-published releases.
|
||||
- The raw Linux and Windows bootstraps prefer a valid `sha256:<64 hex>` digest from the matching release API asset. If the digest is absent or null, they find the correspondingly named checksum asset, require an HTTPS download URL and exactly one checksum line naming the ZIP, download the ZIP, and compare its SHA-256 before extraction or execution.
|
||||
- A malformed, non-null API digest fails closed. Do not fall back from an invalid digest or calculate the expected checksum from the ZIP that is being verified.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Run `python3 scripts/ci/accept-release-offline.py` in a clean dedicated checkout. Its TLS loopback Gitea double and fake Docker CLI must prove release asset publication, the API digest-present path, the Forgejo-compatible `digest: null` sidecar path, rejection of a mismatched sidecar, and fail-closed behavior for a malformed non-null API digest. Assert the expected installer asset names and the sidecar content against the produced ZIP.
|
||||
2. Run `python3 -m unittest scripts.ci.test_ci` (or the repository's equivalent CI policy test command) and verify release asset fixtures include the sidecar.
|
||||
3. Run `bash -n install/install-server.sh`; if `pwsh` is available, parse `install/install-server.ps1` without invoking Windows-only installation actions.
|
||||
4. For any disposable Compose validation required by the behavior change, follow `skills/compose-disposable-recipe/SKILL.md`: use source-built unique tags and isolated credentials/ports/volumes, install cleanup before build/start, and verify project resources and exact image tags are absent afterward.
|
||||
5. Record local and CI evidence in the Gitea issue and PR. Do not claim a production Gitea release, `/releases/latest`, Docker Hub, runner, or deployed installer was validated by the offline API double.
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
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.
|
||||
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
|
||||
- Verify 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 short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
|
||||
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
|
||||
- Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings.
|
||||
- Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults.
|
||||
- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address.
|
||||
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
#!/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"
|
||||
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"
|
||||
local_image_tags=()
|
||||
mkdir -p "$secret_dir"
|
||||
|
||||
compose() {
|
||||
docker compose --project-directory "$install_root" --env-file "$env_file" \
|
||||
-f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \
|
||||
-p "$project" "$@"
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
compose down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" ]]; then
|
||||
# `compose run --rm` may leave a one-off test container behind if the
|
||||
# client exits during shutdown; remove only containers carrying this
|
||||
# recipe's unique Compose project label.
|
||||
while IFS= read -r container; do
|
||||
[[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1
|
||||
done <<< "$containers"
|
||||
fi
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
if ((${#local_image_tags[@]} == 0)); then
|
||||
printf 'No local images built; upstream service images retained.\n'
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" "$turn_log" \
|
||||
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
|
||||
"$secret_dir/coturn_secret" || cleanup_failed=1
|
||||
rmdir -- "$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"
|
||||
chmod 600 "$secret_dir"/*
|
||||
cat > "$env_file" <<EOF
|
||||
RUSTFS_API_PORT=$rustfs_api_port
|
||||
RUSTFS_CONSOLE_PORT=$rustfs_console_port
|
||||
COTURN_PORT=$coturn_port
|
||||
COTURN_RELAY_PORT_MIN=$relay_min
|
||||
COTURN_RELAY_PORT_MAX=$relay_max
|
||||
COTURN_REALM=heimdall.acceptance.test
|
||||
COTURN_SECRET=$coturn_secret
|
||||
COTURN_USERNAME=$coturn_username
|
||||
RUSTFS_ACCESS_KEY=$rustfs_access_key
|
||||
RUSTFS_SECRET_KEY=$rustfs_secret_key
|
||||
ACCEPTANCE_NETWORK=${project}-heimdall-net
|
||||
EOF
|
||||
chmod 600 "$env_file"
|
||||
cat > "$override_file" <<'EOF'
|
||||
services:
|
||||
turn-test:
|
||||
image: coturn/coturn:4.6
|
||||
pull_policy: always
|
||||
profiles: [acceptance]
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478
|
||||
-W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn
|
||||
environment:
|
||||
COTURN_SECRET: ${COTURN_SECRET}
|
||||
COTURN_USERNAME: ${COTURN_USERNAME}
|
||||
depends_on:
|
||||
- coturn
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: ${ACCEPTANCE_NETWORK}
|
||||
external: false
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
|
||||
compose config --quiet
|
||||
compose up -d rustfs coturn
|
||||
|
||||
base_url="http://127.0.0.1:$rustfs_api_port"
|
||||
deadline=$((SECONDS + 180))
|
||||
until curl -fsS "$base_url/health" >/dev/null 2>&1; do
|
||||
if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \
|
||||
"$rustfs_api_port" "$rustfs_console_port"
|
||||
|
||||
RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \
|
||||
RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY'
|
||||
import datetime, hashlib, hmac, os, urllib.error, urllib.request
|
||||
|
||||
access = os.environ['RUSTFS_ACCESS_KEY']
|
||||
secret = os.environ['RUSTFS_SECRET_KEY']
|
||||
host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT']
|
||||
path = '/acceptance'
|
||||
payload_hash = hashlib.sha256(b'').hexdigest()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
amz_date = now.strftime('%Y%m%dT%H%M%SZ')
|
||||
date = now.strftime('%Y%m%d')
|
||||
canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n'
|
||||
signed_headers = 'host;x-amz-content-sha256;x-amz-date'
|
||||
canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}'
|
||||
scope = f'{date}/us-east-1/s3/aws4_request'
|
||||
to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest()
|
||||
def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest()
|
||||
key = sign(('AWS4' + secret).encode(), date)
|
||||
key = sign(key, 'us-east-1')
|
||||
key = sign(key, 's3')
|
||||
key = sign(key, 'aws4_request')
|
||||
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}'
|
||||
request = urllib.request.Request(
|
||||
f'http://{host}{path}', data=b'', method='PUT',
|
||||
headers={'Host': host, 'x-amz-content-sha256': payload_hash,
|
||||
'x-amz-date': amz_date, 'Authorization': authorization})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status')
|
||||
except urllib.error.HTTPError as error:
|
||||
from xml.etree import ElementTree
|
||||
body = error.read()
|
||||
try: code = ElementTree.fromstring(body).findtext('{*}Code')
|
||||
except ElementTree.ParseError: code = None
|
||||
raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})')
|
||||
PY
|
||||
printf 'RustFS S3 authenticated bucket creation: passed.\n'
|
||||
|
||||
if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then
|
||||
echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2
|
||||
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' "$turn_log" | tail -30 >&2 || true
|
||||
echo 'sanitized coturn server diagnostics:' >&2
|
||||
compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \
|
||||
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' | tail -40 >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \
|
||||
"$coturn_port" "$relay_min" "$relay_max"
|
||||
|
||||
for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do
|
||||
if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then
|
||||
echo 'A generated service secret appeared in container logs.' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
printf 'Verified generated service secrets are absent from container logs.\n'
|
||||
@@ -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.
|
||||
@@ -5,6 +5,10 @@ description: Build and validate changed Heimdall images on pushes, then publish
|
||||
|
||||
# Heimdall build and release workflow
|
||||
|
||||
For every PR, follow [pull request release assessment](../pr-release-versioning/SKILL.md). Determine and record whether a release is needed and the proposed SemVer from the change impact; do not ask the user to decide. Documentation and skills-only changes do not create a release or change the version. Only tag a release after the merged commit is on `main` and required checks pass.
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -14,9 +18,10 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
|
||||
- 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.
|
||||
- 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.
|
||||
- After merge of a release-worthy PR, use the current stable tag and all unreleased changes to calculate the SemVer increment according to `pr-release-versioning`. Fetch `main`, verify the merged commit is reachable from it, verify the selected tag is unused, create an annotated tag at the merged commit, and push it to trigger this workflow. Never ask the user to choose a version or release, infer a version from the PR title alone, or force-update an existing tag. Documentation and skills-only changes do not get a tag.
|
||||
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, its `heimdall-installers-<version>.zip.sha256` sidecar, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and unrelated checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
|
||||
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
|
||||
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. 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.
|
||||
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. The package job writes a checksum sidecar with the archive's exact asset filename. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), uses a valid Gitea SHA-256 asset digest when present and otherwise downloads and parses the published sidecar, then verifies the ZIP before running its version-pinned script. A malformed non-null Gitea digest is a hard failure; it must not be silently replaced by the sidecar. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
|
||||
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
|
||||
- Central stores only the public Forgejo origin in `updates.forgepublicurl` and constructs the canonical Heimdall `releases/latest` API route in code. Preserve the legacy setting migration and never make the derived API route editable in Settings.
|
||||
- The Site Install panel displays the configured signed release version and only exposes native install commands when the signed manifest, key, and platform assets are available. Docker commands also require a verified image digest.
|
||||
@@ -29,7 +34,7 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
|
||||
|
||||
## Offline end-to-end acceptance
|
||||
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP and its published checksum sidecar, installer bootstrap with both a valid API digest and `digest: null`, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.r
|
||||
- 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.
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
|
||||
var oldStatus = camera.Status;
|
||||
|
||||
var newStatus = camera.Status == CameraStatus.Disabled
|
||||
? CameraStatus.Online
|
||||
? CameraStatus.Offline
|
||||
: CameraStatus.Disabled;
|
||||
|
||||
camera.SetStatus(newStatus);
|
||||
|
||||
@@ -633,7 +633,7 @@ else
|
||||
if (result.Succeeded && result.Data is not null)
|
||||
{
|
||||
_camera.Status = result.Data.Status;
|
||||
Snackbar.Add(result.Data.Status == "Online" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
|
||||
Snackbar.Add(result.Data.Status != "Disabled" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
|
||||
}
|
||||
else _editError = result.ErrorMessage ?? Text["CameraDetail_StatusError"];
|
||||
}
|
||||
|
||||
@@ -638,7 +638,7 @@
|
||||
{
|
||||
camera.Status = result.Data.Status;
|
||||
Snackbar.Add(
|
||||
result.Data.Status == "Online" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
|
||||
result.Data.Status != "Disabled" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
|
||||
Severity.Success);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -10,6 +10,7 @@ using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory;
|
||||
using Heimdall.Application.Cameras.Commands.ReportCameraStatus;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using MediatR;
|
||||
@@ -24,6 +25,8 @@ namespace Heimdall.Api.Controllers;
|
||||
[EnableRateLimiting("Api")]
|
||||
public class AgentsController : ControllerBase
|
||||
{
|
||||
private readonly ResourceAccess _resourceAccess;
|
||||
|
||||
/// <summary>Query parameters for agent log retrieval.</summary>
|
||||
public record AgentLogsQuery(
|
||||
[FromQuery] int Page = 1,
|
||||
@@ -35,7 +38,11 @@ public class AgentsController : ControllerBase
|
||||
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public AgentsController(IMediator mediator) => _mediator = mediator;
|
||||
public AgentsController(IMediator mediator, ResourceAccess resourceAccess)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_resourceAccess = resourceAccess;
|
||||
}
|
||||
|
||||
/// <summary>Register an agent using a site registration token.</summary>
|
||||
[AllowAnonymous]
|
||||
@@ -149,6 +156,12 @@ public class AgentsController : ControllerBase
|
||||
public async Task<IActionResult> ReportCameraStatus(
|
||||
Guid id, Guid cameraId, [FromBody] ReportCameraStatusRequest request, CancellationToken ct)
|
||||
{
|
||||
var requester = await _resourceAccess.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
||||
!await _resourceAccess.AgentAsync(requester, id, ct) ||
|
||||
!await _resourceAccess.CameraAsync(requester, cameraId, ct))
|
||||
return Forbid();
|
||||
|
||||
if (!Enum.TryParse<CameraStatus>(request.Status, true, out var status))
|
||||
return BadRequest(new { error = $"Invalid status: {request.Status}" });
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ public class CamerasController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Toggle a camera between Online and Disabled.</summary>
|
||||
/// <summary>Toggle a camera between enabled (initially Offline) and Disabled.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{id:guid}/toggle-status")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
|
||||
@@ -44,9 +44,9 @@
|
||||
},
|
||||
"Microsoft.AspNetCore.App.Internal.Assets": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "T1IOYbID1msKjQEh684HebnN+Xnq/pocMXDukOMZtzzPTf9c4/30+/JndM/1txrqwuSYqWvLiAQWzu4U93cshw=="
|
||||
"requested": "[10.0.15, )",
|
||||
"resolved": "10.0.15",
|
||||
"contentHash": "cineG7aU2cpo+CC5rDORY4bFRya0mlaULDpzQ+ncfG0tMyZlWATyVAo2P29i0hH40EElK5O204pjT4XEYALb6g=="
|
||||
},
|
||||
"Microsoft.AspNetCore.OpenApi": {
|
||||
"type": "Direct",
|
||||
|
||||
@@ -20,7 +20,7 @@ public class ToggleCameraStatusCommandTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Toggle_disabled_camera_should_set_online()
|
||||
public async Task Toggle_disabled_camera_should_set_offline_until_agent_confirms_connectivity()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>([_disabledCamera]));
|
||||
@@ -30,7 +30,7 @@ public class ToggleCameraStatusCommandTests
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Status.ShouldBe(CameraStatus.Online);
|
||||
result.Data.Status.ShouldBe(CameraStatus.Offline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -76,6 +76,6 @@ public class ToggleCameraStatusCommandTests
|
||||
context.AuditLogs.Received(1).Add(Arg.Is<AuditLog>(log => log != null
|
||||
&& log.UserId == actorId && log.Action == "Camera.StatusChanged"
|
||||
&& log.OldValue!.Contains("\"status\":\"Disabled\"")
|
||||
&& log.NewValue!.Contains("\"status\":\"Online\"")));
|
||||
&& log.NewValue!.Contains("\"status\":\"Offline\"")));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@@ -83,6 +85,73 @@ public class AuthFlowTests : E2ETestBase
|
||||
navCount.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Authenticator_2fa_login_creates_a_usable_browser_cookie()
|
||||
{
|
||||
const string password = "BrowserTwoFactorPass123!";
|
||||
var email = $"e2e-2fa-{Guid.NewGuid():N}@heimdall.test";
|
||||
IdentityAppUser? user = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (var scope = App.Services.CreateScope())
|
||||
{
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
|
||||
user = new IdentityAppUser
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Email = email,
|
||||
UserName = email,
|
||||
EmailConfirmed = true
|
||||
};
|
||||
(await users.CreateAsync(user, password)).Succeeded.ShouldBeTrue();
|
||||
(await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue();
|
||||
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
|
||||
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
|
||||
}
|
||||
|
||||
await GotoWithCircuitAsync("/login");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='current-password']", password);
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
var codeInput = Page.Locator("input[autocomplete='one-time-code']");
|
||||
await codeInput.WaitForAsync(new() { Timeout = 15000 });
|
||||
|
||||
string authenticatorKey;
|
||||
using (var scope = App.Services.CreateScope())
|
||||
{
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
|
||||
var storedUser = await users.FindByIdAsync(user!.Id.ToString());
|
||||
authenticatorKey = (await users.GetAuthenticatorKeyAsync(storedUser!))!;
|
||||
}
|
||||
|
||||
await codeInput.FillAsync(GenerateTotp(authenticatorKey));
|
||||
await Page.ClickAsync("button:has-text('Vérifier')");
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
|
||||
|
||||
var cookies = await Page.Context.CookiesAsync([BaseUrl]);
|
||||
var authCookie = cookies.SingleOrDefault(cookie => cookie.Name == ".Heimdall.Auth");
|
||||
authCookie.ShouldNotBeNull();
|
||||
|
||||
using var authenticated = new HttpClient();
|
||||
authenticated.DefaultRequestHeaders.Add("Cookie", $".Heimdall.Auth={authCookie!.Value}");
|
||||
var response = await authenticated.GetAsync($"{BaseUrl}/api/users/me");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (user is not null)
|
||||
{
|
||||
using var scope = App.Services.CreateScope();
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
|
||||
var storedUser = await users.FindByIdAsync(user.Id.ToString());
|
||||
if (storedUser is not null)
|
||||
(await users.DeleteAsync(storedUser)).Succeeded.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_with_wrong_password_shows_error()
|
||||
{
|
||||
@@ -153,4 +222,30 @@ public class AuthFlowTests : E2ETestBase
|
||||
}
|
||||
|
||||
private sealed record BootstrapStatus(bool SetupRequired);
|
||||
|
||||
#pragma warning disable CA5350
|
||||
private static string GenerateTotp(string base32Key)
|
||||
{
|
||||
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
var key = new List<byte>();
|
||||
var buffer = 0;
|
||||
var bits = 0;
|
||||
foreach (var character in base32Key.TrimEnd('='))
|
||||
{
|
||||
buffer = (buffer << 5) | alphabet.IndexOf(character);
|
||||
bits += 5;
|
||||
if (bits < 8) continue;
|
||||
bits -= 8;
|
||||
key.Add((byte)(buffer >> bits));
|
||||
}
|
||||
|
||||
Span<byte> message = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
|
||||
var hash = HMACSHA1.HashData(key.ToArray(), message);
|
||||
var offset = hash[^1] & 0x0f;
|
||||
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
|
||||
| (hash[offset + 2] << 8) | hash[offset + 3];
|
||||
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
#pragma warning restore CA5350
|
||||
}
|
||||
@@ -56,6 +56,64 @@ public class UserManagementTests : E2ETestBase
|
||||
body.ShouldContain("E2E Viewer");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Supervisor", true)]
|
||||
[InlineData("Supervisor", false)]
|
||||
[InlineData("Viewer", true)]
|
||||
[InlineData("Viewer", false)]
|
||||
public async Task User_created_from_dialog_can_log_in_with_submitted_password_after_email_confirmation(
|
||||
string role, bool selectRoleBeforePassword)
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
|
||||
await Page.ClickAsync("text=Nouvel utilisateur");
|
||||
|
||||
var dialog = Page.Locator(".mud-dialog");
|
||||
await dialog.WaitForAsync(new() { Timeout = 10000 });
|
||||
var email = $"e2e-{role.ToLowerInvariant()}-{Guid.NewGuid():N}@heimdall.test";
|
||||
var password = "FirstLoginPass123!";
|
||||
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
|
||||
await dialog.Locator("input[autocomplete='name']").FillAsync($"E2E {role}");
|
||||
|
||||
if (selectRoleBeforePassword)
|
||||
await SelectCreateRoleAsync(dialog, role);
|
||||
|
||||
await dialog.Locator("input[autocomplete='new-password']").FillAsync(password);
|
||||
|
||||
if (!selectRoleBeforePassword)
|
||||
await SelectCreateRoleAsync(dialog, role);
|
||||
|
||||
await dialog.Locator("button:has-text('Créer')").ClickAsync();
|
||||
await dialog.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
|
||||
|
||||
var token = await LoginViaApiAsync();
|
||||
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var row = Page.Locator($"tr:has-text('{email}')");
|
||||
await row.WaitForAsync(new() { Timeout = 15000 });
|
||||
await row.GetByRole(AriaRole.Button, new() { Name = "Confirmer l’email", Exact = true }).ClickAsync();
|
||||
|
||||
using var login = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var response = await login.PostAsJsonAsync("/api/auth/login", new { email, password });
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.OK,
|
||||
$"A {role} account created with role selected {(selectRoleBeforePassword ? "before" : "after")} its password should authenticate after admin email confirmation.");
|
||||
var body = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>();
|
||||
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrWhiteSpace();
|
||||
|
||||
using var cleanup = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
cleanup.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var deleteResponse = await cleanup.DeleteAsync($"/api/users/{body.GetProperty("user").GetProperty("id").GetString()}");
|
||||
deleteResponse.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
private static async Task SelectCreateRoleAsync(ILocator dialog, string role)
|
||||
{
|
||||
await dialog.Locator(".mud-input-control.mud-select").ClickAsync();
|
||||
await dialog.Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = role }).ClickAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task New_user_can_log_in_with_viewer_role()
|
||||
{
|
||||
|
||||
@@ -67,11 +67,58 @@ public class CamerasControllerTests : PostgresTestBase
|
||||
var cameraId = cameraContent.GetProperty("id").GetGuid();
|
||||
cameraContent.GetProperty("status").GetString().ShouldBe("Disabled");
|
||||
|
||||
// Toggle → Online
|
||||
// Activation is enabled but has no connectivity evidence yet.
|
||||
var toggleResponse = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
|
||||
toggleResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
var toggled = await toggleResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
toggled.GetProperty("status").GetString().ShouldBe("Online");
|
||||
toggled.GetProperty("status").GetString().ShouldBe("Offline");
|
||||
|
||||
var cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
|
||||
var camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
camera.GetProperty("status").GetString().ShouldBe("Offline");
|
||||
|
||||
var tokenResponse = await client.PostAsync($"api/sites/{siteId}/tokens", null);
|
||||
var siteToken = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>())
|
||||
.GetProperty("token").GetString()!;
|
||||
var registerResponse = await client.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token = siteToken,
|
||||
hostname = "camera-connectivity-agent",
|
||||
version = "1.0.0-test"
|
||||
});
|
||||
var registration = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var agentId = registration.GetProperty("agentId").GetGuid();
|
||||
var apiKey = registration.GetProperty("apiKey").GetString()!;
|
||||
var agentClient = Factory.CreateClient();
|
||||
agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
|
||||
|
||||
var heartbeatResponse = await agentClient.PostAsJsonAsync(
|
||||
$"api/agents/{agentId}/heartbeat", new { publicIp = "127.0.0.1" });
|
||||
heartbeatResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var unassignedReport = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
|
||||
unassignedReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
var assignmentResponse = await client.PostAsJsonAsync("api/assignments", new
|
||||
{
|
||||
cameraId,
|
||||
agentId,
|
||||
reason = "integration test"
|
||||
});
|
||||
assignmentResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var reportResponse = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
|
||||
reportResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var wrongAgentReport = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{Guid.NewGuid()}/cameras/{cameraId}/status", new { status = "Offline" });
|
||||
wrongAgentReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
|
||||
camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
camera.GetProperty("status").GetString().ShouldBe("Online");
|
||||
|
||||
// Toggle back → Disabled
|
||||
var toggleBack = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
|
||||
|
||||
Reference in new issue
Block a user