fix: secure and verify native agent deployment
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Failing after 14m15s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s

This commit is contained in:
arnaud.dartois committed 2026-11-13 17:32:25 +01:00
1 parent 04b3279d1f
commit 923f9e7a55
18 files changed
+390 -113

No files matched your search

+4 -2
View File
@@ -242,7 +242,7 @@ Dashboard shows agent offline state
│ │ Commandes │ │
│ │ Installer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
│ │ │ demander URL/token puis installer [⧉]│ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ Lancer │ │
│ │ ┌──────────────────────────────────────────┐ │ │
@@ -273,7 +273,7 @@ Configuration (Docker uniquement si l'image GPU est publiée)
Commandes
Installer
┌──────────────────────────────────────────────┐
│ commande/script [⧉]│
│ demande URL et token masqué, puis installe [⧉]│
└──────────────────────────────────────────────┘
Lancer
┌──────────────────────────────────────────────┐
@@ -283,6 +283,8 @@ Lancer
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
La commande Linux ne contient ni l'URL Central ni le token du site. À son exécution, elle demande l'URL HTTPS puis le token sans afficher sa saisie, place les valeurs dans des fichiers temporaires protégés et télécharge les scripts par HTTPS avant leur exécution. L'installateur exige les fichiers d'enrôlement protégés et conserve le token comme credential systemd.
### États — Détail Site
| État | Comportement |
+26 -8
View File
@@ -1,15 +1,25 @@
#!/usr/bin/env bash
# install-agent.sh — Heimdall Agent installer for Linux
set -euo pipefail
CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
CENTRAL_URL="" SITE_TOKEN="" CENTRAL_URL_FILE="" SITE_TOKEN_FILE="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall"
while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token are required" >&2; exit 1; }
while [[ $# -gt 0 ]]; do case "$1" in --central-url-file) CENTRAL_URL_FILE="$2"; shift 2;; --site-token-file) SITE_TOKEN_FILE="$2"; shift 2;; --central-url|--site-token) echo "Error: pass enrollment settings through protected files, not command-line values" >&2; exit 1;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url-file PATH --site-token-file PATH [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
read_protected_value() {
local path="$1" label="$2" mode
[[ -n "$path" && -f "$path" && ! -L "$path" ]] || { echo "Error: $label must reference a regular protected file" >&2; exit 1; }
mode=$(stat -c '%a' "$path")
(( (8#$mode & 077) == 0 )) || { echo "Error: $label file must not be accessible by group or others" >&2; exit 1; }
cat -- "$path"
}
[[ -n "$CENTRAL_URL_FILE" && -n "$SITE_TOKEN_FILE" ]] || { echo "Error: --central-url-file and --site-token-file are required" >&2; exit 1; }
CENTRAL_URL="$(read_protected_value "$CENTRAL_URL_FILE" 'Central URL')"
SITE_TOKEN="$(read_protected_value "$SITE_TOKEN_FILE" 'site token')"
[[ -n "$CENTRAL_URL" && -n "$SITE_TOKEN" ]] || { echo "Error: protected Central URL and site token files must be non-empty" >&2; exit 1; }
[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; }
if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi
CENTRAL_URL="${CENTRAL_URL%/}"
if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then
echo "Error: --central-url must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
echo "Error: Central URL must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
exit 1
fi
ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac
@@ -45,9 +55,11 @@ RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
for attempt in 1 2 3; do
CURL_PROTOCOL=https
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
printf '%s' "$RELEASE_METADATA_URL" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/release-metadata.curl"
chmod 600 "$TMP_DIR/release-metadata.curl"
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
--connect-timeout 10 --max-time 30 \
-w '%{http_code}' "$RELEASE_METADATA_URL" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
-w '%{http_code}' --config "$TMP_DIR/release-metadata.curl" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
break
fi
@@ -109,6 +121,11 @@ with tarfile.open(sys.argv[1], 'r:gz') as archive:
shutil.copyfileobj(source,output)
PY
[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; }
printf '%s' "$CENTRAL_URL" | python3 -c 'import json,pathlib,sys; p=pathlib.Path(sys.argv[1]); raw=p.read_text() if p.exists() else "{}";
try: d=json.loads(raw)
except json.JSONDecodeError: d={}
d.setdefault("Agent",{})["CentralUrl"]=sys.stdin.read(); p.write_text(json.dumps(d,indent=2)+"\n")' "$TMP_DIR/agent/appsettings.json"
chmod 640 "$TMP_DIR/agent/appsettings.json"
id "$SERVICE_USER" &>/dev/null || sudo useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" 2>/dev/null || true
sudo mkdir -p "$STATE_DIR" && sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR" && sudo chmod 700 "$STATE_DIR"
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$INSTALL_ROOT" "$INSTALL_ROOT/releases"
@@ -122,7 +139,9 @@ sudo install -d -o root -g root -m 755 /usr/local/libexec
SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py"
if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then
SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py"
curl -fsS "$CENTRAL_URL/install/agent-supervisor.py" -o "$SUPERVISOR_SOURCE" || {
printf '%s' "$CENTRAL_URL/install/agent-supervisor.py" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/supervisor.curl"
chmod 600 "$TMP_DIR/supervisor.curl"
curl -fsS --config "$TMP_DIR/supervisor.curl" -o "$SUPERVISOR_SOURCE" || {
echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1;
}
fi
@@ -150,7 +169,6 @@ if [[ "$RUN_MODE" == true ]]; then
ASPNETCORE_URLS=http://127.0.0.1:8081 \
HEIMDALL_DOTNET="$DOTNET_BIN" \
ASPNETCORE_ENVIRONMENT=Production \
Agent__CentralUrl="$CENTRAL_URL" \
Agent__AgentName="$AGENT_NAME" \
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
Agent__StateDirectory="$STATE_DIR" \
@@ -173,7 +191,6 @@ RestartSec=5
Environment=ASPNETCORE_URLS=http://127.0.0.1:8081
Environment=HEIMDALL_DOTNET=$DOTNET_BIN
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=Agent__CentralUrl=$CENTRAL_URL
Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP
Environment=Agent__StateDirectory=$STATE_DIR
Environment=Agent__UpdateInstallRoot=$INSTALL_ROOT
@@ -183,6 +200,7 @@ $AGENT_NAME_CREDENTIAL
[Install]
WantedBy=multi-user.target
EOF
sudo chmod 600 "/etc/systemd/system/$SERVICE_NAME.service"
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME"
if [[ "$INSTALL_ONLY" == true ]]; then
echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME"
+9 -7
View File
@@ -110,6 +110,8 @@ copy_source_asset() {
say "Installation de Heimdall Central (serveur + PostgreSQL)."
destination="$(ask 'Dossier d’installation' "$HOME/heimdall")"
compose_project="$(ask 'Nom isolé du projet Docker Compose' 'heimdall')"
[[ "$compose_project" =~ ^[a-z0-9][a-z0-9_-]{0,62}$ ]] || { echo 'Nom de projet Compose invalide.' >&2; exit 1; }
compose_path="$destination/docker-compose.yml"
env_path="$destination/.env"
is_existing=no
@@ -125,7 +127,10 @@ if [[ -e "$compose_path" || -e "$env_path" ]]; then
is_existing=yes
else
web_port="$(ask 'Port HTTP du serveur' '5000')"
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')"
public_origin="${HEIMDALL_URL:-}"
cors_default=''
if [[ "$public_origin" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?$ ]]; then cors_default="$public_origin"; fi
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' "${cors_default:-https://heimdall.invalid}")"
[[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; }
[[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; }
fi
@@ -186,8 +191,6 @@ fi
compose_tmp="$(mktemp "$destination/.docker-compose.yml.XXXXXX")"
trap 'rm -f "${compose_tmp:-}"' EXIT
cat > "$compose_tmp" <<'COMPOSE'
name: heimdall
services:
postgresql:
image: postgres:17-alpine
@@ -257,11 +260,10 @@ secrets:
networks:
heimdall-net:
name: heimdall-net
driver: bridge
COMPOSE
chmod 600 "$compose_tmp"
docker compose --env-file "$env_path" -f "$compose_tmp" config --quiet
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_tmp" config --quiet
if [[ "$is_existing" == yes ]]; then
backup_path="$compose_path.bak.$(date -u +%Y%m%dT%H%M%SZ)"
cp -p "$compose_path" "$backup_path"
@@ -291,7 +293,7 @@ say "Variables protégées dans $destination/.env (mode 600), secret PostgreSQL
say "Validation du Compose avant démarrage…"
start_core=no
if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
docker compose --env-file "$env_path" -f "$compose_path" up -d
docker compose --project-name "$compose_project" --env-file "$env_path" -f "$compose_path" up -d
start_core=yes
fi
@@ -322,7 +324,7 @@ for service in "${selected[@]}"; do
;;
esac
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
docker compose --project-directory "$compose_project_directory" --project-name "heimdall-${service}" \
docker compose --project-directory "$compose_project_directory" --project-name "${compose_project}-${service}" \
--env-file "$destination/.env" \
-f "$destination/optional/docker-compose.${service}.yml" up -d
else
+33
View File
@@ -33,6 +33,28 @@ For Linux systemd installs, preserve the site display name through the existing
foreground installer may pass `Agent__AgentName` directly; do not put arbitrary
site names in an unescaped systemd `Environment=` assignment.
Linux enrollment values must be passed to `install/install-agent.sh` using
`--central-url-file` and `--site-token-file`, each pointing to a regular file
with no group/other permissions. Reject legacy `--central-url` and
`--site-token` values because they are visible in process listings. The site
token is persisted only in root-owned and Agent-owned mode-0600 credential
files and loaded by systemd `LoadCredential`; generated command text must not
contain either enrollment value. Keep the temporary prompt files mode 0600 in
a mode-0700 directory and remove them on every exit path. Verify generated
Linux command text has no Central URL or site token, both legacy value flags
fail before installation, and unsafe/symlink/empty files are rejected.
Keep the Central URL out of process arguments and unit contents. The Linux
installer stores it in the Agent release's `appsettings.json` with mode 0640
inside the mode-0750 Agent release tree; a new Agent may alternatively load it
from a systemd `central-url` credential through `CREDENTIALS_DIRECTORY`.
Agent logs must not include the Central URL.
The server installer Compose project/network must use Compose's project-scoped
resource names rather than fixed global `name:` values. The interactive
installer should default CORS to the configured public HTTPS origin when one
is supplied and otherwise use a restrictive placeholder that the operator
must replace; do not default a new installation to wildcard CORS.
Before accepting a native or Docker install flow, verify that Central's global
`updates.forgepublicurl` contains only the HTTPS public Forgejo origin and that
Central constructs `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` from
@@ -41,6 +63,17 @@ contain the signed manifest, asset checksums, and required image digest. A
`main` Docker image build alone cannot supply the signed Agent release metadata
used by installers and the IHM.
Forgejo releases may omit the optional `asset.digest` API field. In that case,
Central may fetch the public key, manifest, and signature only from HTTPS URLs
on the configured Forgejo origin, then must verify the ECDSA P-256 signature,
release tag, manifest schema, archive SHA-256 values, and image digests before
returning metadata. Use the hashes from the verified signed manifest for
downloadable archives. Reject cross-origin asset URLs, redirects to another
origin, bad signatures, malformed digests, and tag mismatches. Do not replace
missing API digests with unchecked archive metadata or disable verification.
Validate both an actual release whose API omits `asset.digest` and synthetic
tampered metadata in a source-built Compose acceptance.
## Linux rollback simulation
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
+4
View File
@@ -43,6 +43,10 @@ For installer, Compose, image, and documentation work that can proceed independe
- When a newer Compose needs an absent env key, append a generated secret or documented default only if that key is missing. Never print secret values. Refuse to continue if the existing database URL or password file needed by PostgreSQL is missing.
- If the user declines the Compose refresh, exit without changing the install. If only part of an install is present, stop and explain what is missing instead of creating a second set of credentials.
## Live Linux deployment evidence
For an explicitly authorized host validation, inspect existing services and data before mutation, use only that environment's protected credentials, and scope reset to the named Heimdall Compose projects. Install Central and Agent through the released `.sh` installers. Record image digest, Agent version/identity/site association, `/healthz`, local Agent version endpoint, heartbeat status, credential modes, listener bindings, and sanitized logs. Restart Central and Agent and verify health and persisted volumes/site identity. Do not infer Windows, GPU, camera, multicast, TURN, backup, or long-load acceptance from a single Linux host.
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the corresponding `:latest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
+1
View File
@@ -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 verified CPU/GPU image metadata and the update key, but install the corresponding published `:latest` image. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
- The Linux generated installer command must not embed Central URL or site token in its text or process arguments. Prompt for both at execution time, hide token input, use protected temporary files and the installer's file-based flags, and clean those files on all exits.
- 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.
+9 -1
View File
@@ -14,7 +14,15 @@ public sealed class AgentOptions
/// <summary>URL of the Heimdall Central server, supplied by the installation or deployment configuration.</summary>
[Required, Url]
public string CentralUrl { get; init; } = string.Empty;
public string CentralUrl
{
get => string.IsNullOrWhiteSpace(_centralUrl)
? ReadSystemdCredential("central-url") ?? string.Empty
: _centralUrl;
init => _centralUrl = value ?? string.Empty;
}
private string _centralUrl = string.Empty;
/// <summary>Allow an unencrypted HTTP Central URL for isolated development networks only.</summary>
public bool AllowInsecureHttp { get; init; }
@@ -171,7 +171,7 @@ public class AgentRegistrationService : BackgroundService
throw new InvalidOperationException(
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
_logger.LogInformation("Registering agent with Central.");
var maxRetries = _options.RegistrationMaxRetries;
RegisterResponse? registration = null;
@@ -113,6 +113,10 @@ else if (_method == "docker-run")
</MudTooltip>
</MudPaper>
}
@if (_method is "linux-run" or "linux-systemd")
{
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_LinuxSecretPrompt"]</MudAlert>
}
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
@@ -410,15 +414,16 @@ else if (_method == "windows-service")
private string LinuxInstallCommand(bool service)
{
var baseUrl = CentralUrl.TrimEnd('/');
var scriptUrl = ShellQuote(baseUrl + "/install/install-agent.sh");
var supervisorUrl = ShellQuote(baseUrl + "/install/agent-supervisor.py");
var args = $"--central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}";
var args = $"--central-url-file \"$tmp/central-url\" --site-token-file \"$tmp/site-token\" --agent-name {ShellQuote(SiteName)}";
args += service ? " --install-only" : " --run";
return "tmp=$(mktemp -d) && " +
$"curl -fsSL {scriptUrl} -o \"$tmp/install-agent.sh\" && " +
$"curl -fsSL {supervisorUrl} -o \"$tmp/agent-supervisor.py\" && " +
$"sudo bash \"$tmp/install-agent.sh\" {args}; rc=$?; rm -rf \"$tmp\"; exit $rc";
return "set -eu\n" +
"tmp=$(mktemp -d)\nchmod 700 \"$tmp\"\n" +
"cleanup() { rc=$?; trap - EXIT; rm -f \"$tmp/install-agent.sh\" \"$tmp/agent-supervisor.py\" \"$tmp/central-url\" \"$tmp/site-token\"; rmdir \"$tmp\"; exit $rc; }\ntrap cleanup EXIT HUP INT TERM\n" +
"printf 'Central HTTPS URL: '; IFS= read -r central_url\n" +
"printf 'Site enrollment token (input hidden): '; IFS= read -r -s site_token; printf '\\n'\n" +
"umask 077\nprintf '%s' \"$central_url\" > \"$tmp/central-url\"\nprintf '%s' \"$site_token\" > \"$tmp/site-token\"\nunset central_url site_token\n" +
"python3 - \"$tmp\" <<'PY'\nimport pathlib, sys, urllib.request\nroot=pathlib.Path(sys.argv[1])\nbase=(root/'central-url').read_text().rstrip('/')\nif not base.startswith('https://'): raise SystemExit('Central URL must use HTTPS')\nfor name in ('install-agent.sh','agent-supervisor.py'):\n request=urllib.request.Request(base+'/install/'+name, headers={'User-Agent':'Heimdall-Agent-Installer'})\n with urllib.request.urlopen(request, timeout=30) as response:\n if response.status != 200: raise SystemExit('Central installer asset request failed')\n (root/name).write_bytes(response.read())\nPY\n" +
$"sudo bash \"$tmp/install-agent.sh\" {args}";
}
private string WindowsServiceName => "HeimdallAgent-" + Slugify(SiteName)[..Math.Min(60, Slugify(SiteName).Length)];
@@ -131,44 +131,41 @@ public class UpdatesController : ControllerBase
return null;
var release = await ReadForgejoReleaseAsync(response.Content, ct);
if (release is null) return null;
var assets = new Dictionary<string, PlatformAsset>();
foreach (var asset in release.Assets ?? [])
{
var platform = DetectPlatform(asset.Name);
if (platform is null) continue;
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = ExtractSha256(asset.Digest), Size = asset.Size };
}
var result = new LatestReleaseResponse { Version = release.TagName, ReleaseNotes = release.Body, PublishedAt = release.PublishedAt, Assets = assets };
var publicKeyBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-release-public.pem", client, 4096, ct);
if (publicKeyBytes is not null)
{
try
{
var publicKeyPem = System.Text.Encoding.UTF8.GetString(publicKeyBytes);
using var verifier = ECDsa.Create();
verifier.ImportFromPem(publicKeyPem);
if (verifier.KeySize == 256)
result.UpdatePublicKeyPem = publicKeyPem;
}
catch (CryptographicException) { }
catch (ArgumentException) { }
}
var image = await FetchAgentImageManifestAsync(release.Assets, "agent-image.json", client, ct);
result.ContainerImage = image?.Image;
result.ContainerImageDigest = image?.Digest;
var gpuImage = await FetchAgentImageManifestAsync(release.Assets, "agent-image-gpu.json", client, ct);
result.ContainerImageGpu = gpuImage?.Image;
result.ContainerImageGpuDigest = gpuImage?.Digest;
"agent-release-public.pem", client, 4096, sourceUri, ct);
var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-update-manifest.json", client, 1_048_576, ct);
"agent-update-manifest.json", client, 1_048_576, sourceUri, ct);
var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
"agent-update-manifest.sig", client, 512, ct);
if (manifestBytes is not null && signatureBytes is not null)
"agent-update-manifest.sig", client, 512, sourceUri, ct);
var publicKeyPem = publicKeyBytes is null ? null : System.Text.Encoding.UTF8.GetString(publicKeyBytes);
if (publicKeyPem is null || manifestBytes is null || signatureBytes is null ||
!AgentReleaseManifestVerifier.TryVerify(publicKeyPem, manifestBytes, signatureBytes,
release.TagName, out var signedManifest) || signedManifest is null)
return null;
var assets = new Dictionary<string, PlatformAsset>();
foreach (var (platform, sha256) in signedManifest.Assets)
{
result.SignedManifest = Convert.ToBase64String(manifestBytes);
result.ManifestSignature = Convert.ToBase64String(signatureBytes);
var asset = release.Assets?.SingleOrDefault(a => DetectPlatform(a.Name) == platform);
if (asset is null || !IsSameHttpsOrigin(asset.BrowserDownloadUrl, sourceUri)) return null;
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = sha256, Size = asset.Size };
}
if (assets.Count == 0) return null;
var result = new LatestReleaseResponse
{
Version = signedManifest.Version,
ReleaseNotes = release.Body,
PublishedAt = release.PublishedAt,
Assets = assets,
ContainerImage = signedManifest.ContainerImage,
ContainerImageDigest = signedManifest.ContainerImageDigest,
ContainerImageGpu = signedManifest.ContainerImageGpu,
ContainerImageGpuDigest = signedManifest.ContainerImageGpuDigest,
UpdatePublicKeyPem = publicKeyPem,
SignedManifest = Convert.ToBase64String(manifestBytes),
ManifestSignature = Convert.ToBase64String(signatureBytes),
};
lock (_cacheLock) { _cache = new LatestReleaseCache(source!, result, DateTime.UtcNow); }
return result;
}
@@ -236,52 +233,19 @@ public class UpdatesController : ControllerBase
statusCode is System.Net.HttpStatusCode.RequestTimeout or System.Net.HttpStatusCode.TooManyRequests ||
(int)statusCode >= 500;
private static async Task<AgentImageManifest?> FetchAgentImageManifestAsync(List<ForgejoAsset>? assets,
string assetName, HttpClient client, CancellationToken ct)
{
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, assetName, StringComparison.OrdinalIgnoreCase));
var expectedSha256 = asset is null ? null : ExtractSha256(asset.Digest);
if (asset is null || !IsSha256Digest(expectedSha256)) return null;
try
{
using var response = await client.GetAsync(asset.BrowserDownloadUrl, HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is > 1_048_576)
return null;
await using var stream = await response.Content.ReadAsStreamAsync(ct);
using var buffer = new MemoryStream();
var chunk = new byte[8192];
while (true)
{
var read = await stream.ReadAsync(chunk, ct);
if (read == 0) break;
if (buffer.Length + read > 1_048_576) return null;
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
var actualSha256 = Convert.ToHexString(SHA256.HashData(bytes));
if (!string.Equals(actualSha256, expectedSha256, StringComparison.OrdinalIgnoreCase)) return null;
var manifest = JsonSerializer.Deserialize<AgentImageManifest>(bytes, Json);
return manifest is not null && IsValidContainerImageRepository(manifest.Image) && IsValidContainerImageDigest(manifest.Digest)
? manifest
: null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch { return null; }
}
private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
private static async Task<byte[]?> FetchBoundedReleaseAssetAsync(List<ForgejoAsset>? assets,
string name, HttpClient client, int maxBytes, CancellationToken ct)
string name, HttpClient client, int maxBytes, Uri sourceUri, CancellationToken ct)
{
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.Ordinal));
var expected = asset is null ? null : ExtractSha256(asset.Digest);
if (asset is null || !IsSha256Digest(expected)) return null;
if (asset is null || !IsSameHttpsOrigin(asset.BrowserDownloadUrl, sourceUri) ||
(asset.Digest is not null && !IsSha256Digest(expected))) return null;
try
{
using var response = await client.GetAsync(asset.BrowserDownloadUrl,
HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes)
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes ||
response.RequestMessage?.RequestUri is not { } finalUri || !IsSameHttpsOrigin(finalUri, sourceUri))
return null;
await using var stream = await response.Content.ReadAsStreamAsync(ct);
using var buffer = new MemoryStream();
@@ -294,29 +258,23 @@ public class UpdatesController : ControllerBase
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
return string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected,
return expected is null || string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected,
StringComparison.OrdinalIgnoreCase) ? bytes : null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch { return null; }
}
private static bool IsValidContainerImageRepository(string? image) => image is { Length: > 0 and <= 255 }
&& char.IsAsciiLetterOrDigit(image[0])
&& image.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or ':' or '/' or '-')
&& !image.Contains('@')
&& !image.Any(char.IsWhiteSpace)
&& !image.Split('/').Last().Contains(':');
private static bool IsSameHttpsOrigin(string candidate, Uri sourceUri) =>
Uri.TryCreate(candidate, UriKind.Absolute, out var candidateUri) && IsSameHttpsOrigin(candidateUri, sourceUri);
private static bool IsValidContainerImageDigest(string? digest) => digest is { Length: 71 }
&& digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& digest[7..].All(Uri.IsHexDigit);
private static bool IsSameHttpsOrigin(Uri candidateUri, Uri sourceUri) =>
candidateUri.Scheme == Uri.UriSchemeHttps &&
string.Equals(candidateUri.Host, sourceUri.Host, StringComparison.OrdinalIgnoreCase) &&
candidateUri.Port == sourceUri.Port && string.IsNullOrEmpty(candidateUri.UserInfo) &&
string.IsNullOrEmpty(candidateUri.Fragment);
private sealed class AgentImageManifest
{
[JsonPropertyName("image")] public string Image { get; init; } = string.Empty;
[JsonPropertyName("digest")] public string Digest { get; init; } = string.Empty;
}
private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
private async Task RefreshCacheAsync(string? source, CancellationToken ct)
{
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Install and run</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>At runtime, enter the Central HTTPS URL and then the site token (token input is hidden). These values are not included in the copied command.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Run</value>
</data>
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Installer et lancer</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>À l’exécution, saisissez l’URL HTTPS de Central puis le token du site (la saisie du token est masquée). Ces valeurs ne sont pas incluses dans la commande copiée.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Lancer</value>
</data>
@@ -4071,6 +4071,9 @@
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
<value>Install and run</value>
</data>
<data name="SiteInstallPanel_LinuxSecretPrompt" xml:space="preserve">
<value>At runtime, enter the Central HTTPS URL and then the site token (token input is hidden). These values are not included in the copied command.</value>
</data>
<data name="SiteInstallPanel_Run" xml:space="preserve">
<value>Run</value>
</data>
@@ -0,0 +1,66 @@
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Heimdall.Web.Services;
/// <summary>Verifies the signed Agent release metadata before Central exposes it to installers.</summary>
public static class AgentReleaseManifestVerifier
{
private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
public static bool TryVerify(string publicKeyPem, byte[] manifestBytes, byte[] signatureBytes,
string releaseTag, out AgentReleaseManifest? manifest)
{
manifest = null;
if (string.IsNullOrWhiteSpace(publicKeyPem) || manifestBytes.Length is 0 or > 1_048_576 ||
signatureBytes.Length is 0 or > 512 || string.IsNullOrWhiteSpace(releaseTag))
return false;
try
{
using var verifier = ECDsa.Create();
verifier.ImportFromPem(publicKeyPem);
if (verifier.KeySize != 256 || !verifier.VerifyData(manifestBytes, signatureBytes,
HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence))
return false;
var parsed = JsonSerializer.Deserialize<AgentReleaseManifest>(manifestBytes, Json);
if (parsed is null || parsed.Assets is null ||
!string.Equals(NormalizeVersion(parsed.Version), NormalizeVersion(releaseTag),
StringComparison.Ordinal) || parsed.Assets.Count == 0 ||
parsed.Assets.Any(asset => string.IsNullOrWhiteSpace(asset.Key) || asset.Value is null || !IsSha256(asset.Value)) ||
!IsValidContainerImageRepository(parsed.ContainerImage) ||
!IsValidContainerImageDigest(parsed.ContainerImageDigest) ||
!IsValidContainerImageRepository(parsed.ContainerImageGpu) ||
!IsValidContainerImageDigest(parsed.ContainerImageGpuDigest))
return false;
manifest = parsed;
return true;
}
catch (CryptographicException) { return false; }
catch (ArgumentException) { return false; }
catch (JsonException) { return false; }
}
private static string NormalizeVersion(string value) => value.Trim().TrimStart('v', 'V');
private static bool IsSha256(string value) => value.Length == 64 && value.All(Uri.IsHexDigit);
private static bool IsValidContainerImageRepository(string? image) => image is { Length: > 0 and <= 255 }
&& char.IsAsciiLetterOrDigit(image[0])
&& image.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or ':' or '/' or '-')
&& !image.Contains('@') && !image.Any(char.IsWhiteSpace) && !image.Split('/').Last().Contains(':');
private static bool IsValidContainerImageDigest(string? digest) => digest is { Length: 71 }
&& digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& digest[7..].All(Uri.IsHexDigit);
}
public sealed class AgentReleaseManifest
{
[JsonPropertyName("version")] public string Version { get; init; } = string.Empty;
[JsonPropertyName("assets")] public Dictionary<string, string> Assets { get; init; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; init; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; }
[JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; }
[JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; }
}
@@ -0,0 +1,31 @@
namespace Heimdall.Agent.Tests;
[CollectionDefinition("AgentOptions environment", DisableParallelization = true)]
public sealed class AgentOptionsEnvironmentScope
{
public const string Name = "AgentOptions environment";
}
[Collection(AgentOptionsEnvironmentScope.Name)]
public sealed class AgentOptionsTests
{
[Fact]
public void CentralUrl_LoadsFromSystemdCredentialWhenNoEnvironmentSettingExists()
{
var previous = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-agent-options-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "central-url"), "https://central.example.test\n");
try
{
Environment.SetEnvironmentVariable("CREDENTIALS_DIRECTORY", directory);
new AgentOptions { }.CentralUrl.ShouldBe("https://central.example.test");
}
finally
{
Environment.SetEnvironmentVariable("CREDENTIALS_DIRECTORY", previous);
Directory.Delete(directory, recursive: true);
}
}
}
@@ -140,6 +140,29 @@ public class SiteDetailTests : PageTestBase
cut.Markup.ShouldNotContain("install-agent.ps1");
}
[Fact]
public void SiteDetail_CommandeLinuxNeContientNiUrlCentralNiToken()
{
Handler.OnGet("api/updates/latest", AgentRelease());
Handler.OnGet("api/sites/", new SiteItem(
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow));
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-linux-private-42", DateTime.UtcNow.AddHours(24)));
LoginAs();
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Générer un token"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-linux-private-42"));
var command = cut.Find("pre code").TextContent;
command.ShouldContain("--central-url-file");
command.ShouldContain("--site-token-file");
command.ShouldContain("read -r -s site_token");
command.ShouldNotContain("tok-linux-private-42");
command.ShouldNotContain("http://localhost");
cut.Markup.ShouldContain("saisie du token est masquée");
}
[Fact]
public void SiteDetail_ChoisirImageNvidia_GenereComposeAvecGpuEtProviderCuda()
{
@@ -9,6 +9,26 @@ namespace Heimdall.Web.Tests.Controllers;
public sealed class UpdatesControllerRetryTests
{
[Fact]
public async Task FetchBoundedReleaseAssetAsync_allowsMissingForgejoDigestForSignedMetadata()
{
using var client = new HttpClient(new StaticResponseHandler("verified-by-release-signature"));
var result = await FetchAssetAsync("https://forgejo.example/attachments/release-key", digest: null, client);
Assert.Equal("verified-by-release-signature", Encoding.UTF8.GetString(result!));
}
[Fact]
public async Task FetchBoundedReleaseAssetAsync_rejectsCrossOriginUrls()
{
var handler = new StaticResponseHandler("unexpected");
using var client = new HttpClient(handler);
var result = await FetchAssetAsync("https://other.example/asset", digest: null, client);
Assert.Null(result);
Assert.Equal(0, handler.RequestCount);
}
[Theory]
[InlineData("<html><title>Proxy error</title></html>")]
[InlineData("{not-json")]
@@ -63,6 +83,40 @@ public sealed class UpdatesControllerRetryTests
return task.GetType().GetProperty("Result")?.GetValue(task);
}
private static async Task<byte[]?> FetchAssetAsync(string url, string? digest, HttpClient client)
{
var assetType = typeof(UpdatesController).GetNestedType("ForgejoAsset", BindingFlags.NonPublic);
Assert.NotNull(assetType);
var asset = Activator.CreateInstance(assetType)!;
assetType.GetProperty("Name")!.SetValue(asset, "agent-release-public.pem");
assetType.GetProperty("BrowserDownloadUrl")!.SetValue(asset, url);
assetType.GetProperty("Digest")!.SetValue(asset, digest);
var listType = typeof(List<>).MakeGenericType(assetType);
var assets = (System.Collections.IList)Activator.CreateInstance(listType)!;
assets.Add(asset);
var method = typeof(UpdatesController).GetMethod("FetchBoundedReleaseAssetAsync",
BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(method);
var task = (Task<byte[]?>)method.Invoke(null,
[assets, "agent-release-public.pem", client, 4096, new Uri("https://forgejo.example/api/v1/releases/latest"), CancellationToken.None])!;
return await task;
}
private sealed class StaticResponseHandler(string body) : HttpMessageHandler
{
public int RequestCount { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
RequestCount++;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = request,
Content = new StringContent(body, Encoding.UTF8),
});
}
}
[Theory]
[InlineData(HttpStatusCode.RequestTimeout, true)]
[InlineData(HttpStatusCode.TooManyRequests, true)]
@@ -0,0 +1,63 @@
using System.Security.Cryptography;
using System.Text.Json;
using Heimdall.Web.Services;
using Xunit;
namespace Heimdall.Web.Tests.Services;
public sealed class AgentReleaseManifestVerifierTests
{
[Fact]
public void TryVerify_AcceptsSignedManifestWhenForgejoAssetDigestIsUnavailable()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
var valid = AgentReleaseManifestVerifier.TryVerify(
key.ExportSubjectPublicKeyInfoPem(), bytes, signature, "1.0.7", out var manifest);
Assert.True(valid);
Assert.NotNull(manifest);
Assert.Equal("1.0.7", manifest.Version);
Assert.True(manifest.Assets.ContainsKey("portable"));
}
[Fact]
public void TryVerify_RejectsModifiedManifest()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
bytes[^2] ^= 1;
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.7", out _));
}
[Fact]
public void TryVerify_RejectsTagMismatchAndMalformedArchiveDigest()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var bytes = ManifestBytes();
var signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.8", out _));
bytes = ManifestBytes(invalidArchiveHash: true);
signature = key.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
Assert.False(AgentReleaseManifestVerifier.TryVerify(key.ExportSubjectPublicKeyInfoPem(), bytes, signature,
"1.0.7", out _));
}
private static byte[] ManifestBytes(bool invalidArchiveHash = false) => JsonSerializer.SerializeToUtf8Bytes(new
{
version = "1.0.7",
assets = new { portable = invalidArchiveHash ? "not-a-sha256" : new string('c', 64) },
containerImage = "eltruncho/heimdall-agent",
containerImageDigest = "sha256:" + new string('a', 64),
containerImageGpu = "eltruncho/heimdall-agent-gpu",
containerImageGpuDigest = "sha256:" + new string('b', 64),
});
}