Merge remote-tracking branch 'origin/main' into fix/agent-durable-camera-status
Heimdall Gitea / Build and tests (pull_request) Failing after 7s
Heimdall Gitea / Publish versioned release (pull_request) Skipped

This commit is contained in:
Arnaud Dartois committed 2026-10-22 19:17:46 +02:00
commit 3c4b8c95f5
18 files changed
+455 -102

No files matched your search

+2
View File
@@ -119,5 +119,7 @@ jobs:
BUILD_SERVER_URL: ${{ gitea.server_url }}
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
AGENT_REGISTRY_USER: ${{ secrets.AGENT_REGISTRY_USER }}
AGENT_REGISTRY_TOKEN: ${{ secrets.AGENT_REGISTRY_TOKEN }}
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: bash scripts/ci/publish.sh
+4 -2
View File
@@ -13,9 +13,11 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-rest
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:d5633778c754e89a386882eddf8dbee6942447a8a4b8267c19cf1e1158d0b0ac
WORKDIR /app
RUN apt-get update -qq && apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata && rm -rf /var/lib/apt/lists/*
ENV ASPNETCORE_URLS=http://+:8080
RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
ENV ASPNETCORE_URLS=http://127.0.0.1:8080
COPY --from=build /out/ ./
COPY models/yolov8n.onnx ./models/yolov8n.onnx
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://localhost:8080/healthz || exit 1
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://127.0.0.1:8080/healthz || exit 1
USER 1654:1654
ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
+3
View File
@@ -0,0 +1,3 @@
{
"image": "sources.tordais.cc/arnaud.dartois/heimdall-agent"
}
+5 -3
View File
@@ -1,7 +1,6 @@
# ─── Heimdall — Override: use locally-built image with current fixes ───
# The Docker Hub image (eltruncho/heimdall:latest) is published by CI on
# main pushes; until the fixes are pushed, deploy the local image instead.
# Usage: docker compose --env-file docker/.env -f docker/docker-compose.prod.yml -f docker/docker-compose.local.yml up -d
# Use locally-built images rather than the production release images.
# Usage: AGENT_IMAGE_REFERENCE=heimdall-agent:local docker compose --env-file docker/.env -f docker/docker-compose.prod.yml -f docker/docker-compose.local.yml up -d
services:
heimdall:
image: heimdall:local
@@ -14,3 +13,6 @@ services:
build:
context: ..
dockerfile: docker/Dockerfile.agent
agent-state-init:
image: heimdall-agent:local
+20 -7
View File
@@ -15,7 +15,7 @@
#
# Images are published by the CI pipeline on main branch pushes:
# eltruncho/heimdall:latest
# eltruncho/heimdall-agent:latest
# image reference from the current Central agent-image.json manifest
#
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
# and Hangfire background jobs (heartbeat monitor, agent failover)
@@ -138,14 +138,14 @@ services:
- heimdall-net
heimdall-agent:
# Versioned tag via AGENT_IMAGE_TAG env var (ticket #97)
image: eltruncho/heimdall-agent:${AGENT_IMAGE_TAG:-latest}
# Pin the exact image reference supplied by the Central release manifest.
image: ${AGENT_IMAGE_REFERENCE:?Set AGENT_IMAGE_REFERENCE from the Central agent image manifest}
# Host network: the agent must see the real camera LAN to run discovery.
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
network_mode: host
environment:
# 8080 is taken by ntfy on the host → listen on 8081
ASPNETCORE_URLS: http://+:8081
# Diagnostics are loopback-only; 8081 avoids conflicts with ntfy.
ASPNETCORE_URLS: http://127.0.0.1:8081
# Host network: Docker DNS names don't resolve → point HEIMDALL_CENTRAL_URL
# to the Central's public URL (e.g. https://heimdall.tordais.cc)
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:?HEIMDALL_CENTRAL_URL is required (public URL of the Central, e.g. https://heimdall.tordais.cc)}
@@ -180,19 +180,32 @@ services:
count: 1
capabilities: [gpu]
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"]
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
volumes:
- agent_state:/var/lib/heimdall
user: "1654:1654"
depends_on:
- heimdall
heimdall:
condition: service_started
agent-state-init:
condition: service_completed_successfully
restart: unless-stopped
logging: *default-logging
# no networks: host networking
# Migrate existing root-owned state before starting the non-root agent.
agent-state-init:
image: ${AGENT_IMAGE_REFERENCE:?Set AGENT_IMAGE_REFERENCE from the Central agent image manifest}
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
# ── Backup service (opt-in via --profile backup) ───────────────
backup:
+20 -4
View File
@@ -114,6 +114,7 @@ services:
- heimdall-net
heimdall-agent:
image: heimdall-agent:latest
build:
context: ..
dockerfile: docker/Dockerfile.agent
@@ -124,11 +125,13 @@ services:
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
network_mode: host
environment:
# 8080 is taken by ntfy on the host → listen on 8081
ASPNETCORE_URLS: http://+:8081
# Diagnostics are loopback-only; 8081 avoids conflicts with ntfy.
ASPNETCORE_URLS: http://127.0.0.1:8081
# Host network: Docker DNS names don't resolve → reach the Central via
# a host-reachable URL (same machine: http://localhost:5010)
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5010}
# This development profile uses local plain HTTP; never enable this in production.
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01}
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
@@ -139,6 +142,7 @@ services:
ORT_CUDA_DEVICE_ID: ${AGENT_CUDA_DEVICE_ID:-0}
volumes:
- agent_state:/var/lib/heimdall
user: "1654:1654"
# GPU device exposure (NVIDIA CUDA, AMD ROCm, Intel VAAPI/iGPU)
# Override in docker-compose.local.yml for specific GPU hardware:
# deploy:
@@ -163,17 +167,29 @@ services:
count: 1
capabilities: [gpu]
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"]
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
depends_on:
- heimdall
heimdall:
condition: service_started
agent-state-init:
condition: service_completed_successfully
restart: unless-stopped
logging: *default-logging
# no networks: host networking
# Migrate existing root-owned state before starting the non-root agent.
agent-state-init:
image: heimdall-agent:latest
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
# ── Optional services (dev) ────────────────────────────────────
coturn:
+20 -6
View File
@@ -1,24 +1,37 @@
#!/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"
CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" ALLOW_INSECURE_HTTP=false
BINARY_NAME="heimdall-agent" INSTALL_DIR="/usr/local/bin" 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;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$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;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--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 required" >&2; exit 1; }
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
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
echo "Installing Heimdall Agent for $PLATFORM..."
RELEASE_JSON=$(curl -sf "$CENTRAL_URL/api/updates/latest") || { echo "Failed to fetch release" >&2; exit 1; }
if command -v jq &>/dev/null; then VERSION=$(echo "$RELEASE_JSON" | jq -r '.version'); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].url // empty"); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].sha256 // empty"); else VERSION=$(echo "$RELEASE_JSON" | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"url":"[^"]*"' | head -1 | cut -d'"' -f4); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"sha256":"[^"]*"' | head -1 | cut -d'"' -f4); fi
[[ -z "$DOWNLOAD_URL" ]] && { echo "No binary for $PLATFORM" >&2; exit 1; }
[[ ! "$EXPECTED_SHA256" =~ ^[[:xdigit:]]{64}$ ]] && { echo "Release manifest has no valid SHA-256 digest for $PLATFORM; refusing an unverified install" >&2; exit 1; }
echo "Latest version: $VERSION"
TMP_DIR=$(mktemp -d); trap 'rm -rf "$TMP_DIR"' EXIT
curl -sfL "$DOWNLOAD_URL" -o "$TMP_DIR/$BINARY_NAME" || { echo "Download failed" >&2; exit 1; }
if [[ -n "$EXPECTED_SHA256" ]]; then ACTUAL=$(sha256sum "$TMP_DIR/$BINARY_NAME" | cut -d' ' -f1); [[ "$ACTUAL" != "$EXPECTED_SHA256" ]] && { echo "SHA256 mismatch" >&2; exit 1; }; echo "SHA256 verified"; fi
ACTUAL=$(sha256sum "$TMP_DIR/$BINARY_NAME" | cut -d' ' -f1); [[ "${ACTUAL,,}" != "${EXPECTED_SHA256,,}" ]] && { echo "SHA256 mismatch" >&2; exit 1; }; echo "SHA256 verified"
chmod +x "$TMP_DIR/$BINARY_NAME"; [[ $EUID -eq 0 ]] && cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME" || sudo cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME"
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"
AGENT_NAME_ENV=""; [[ -n "$AGENT_NAME" ]] && AGENT_NAME_ENV="Environment=Agent__AgentName=$AGENT_NAME"
sudo install -d -o root -g root -m 700 /etc/heimdall/credentials
printf '%s' "$SITE_TOKEN" | sudo tee /etc/heimdall/credentials/site-token >/dev/null
sudo chmod 600 /etc/heimdall/credentials/site-token
AGENT_NAME_CREDENTIAL=""
if [[ -n "$AGENT_NAME" ]]; then
printf '%s' "$AGENT_NAME" | sudo tee /etc/heimdall/credentials/agent-name >/dev/null
sudo chmod 600 /etc/heimdall/credentials/agent-name
AGENT_NAME_CREDENTIAL="LoadCredential=agent-name:/etc/heimdall/credentials/agent-name"
fi
cat <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service >/dev/null
[Unit]
Description=Heimdall Agent
@@ -30,9 +43,10 @@ ExecStart=$INSTALL_DIR/$BINARY_NAME
Restart=on-failure
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=Agent__CentralUrl=$CENTRAL_URL
Environment=Agent__SiteToken=$SITE_TOKEN
Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP
Environment=Agent__StateDirectory=$STATE_DIR
$AGENT_NAME_ENV
LoadCredential=site-token:/etc/heimdall/credentials/site-token
$AGENT_NAME_CREDENTIAL
[Install]
WantedBy=multi-user.target
EOF
+5 -2
View File
@@ -100,12 +100,15 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
| Fichier | Usage | Description |
|---------|-------|-------------|
| `docker-compose.yml` | Développement | Build local des images et services de développement |
| `docker-compose.prod.yml` | Production | Images publiées depuis Docker Hub |
| `docker-compose.prod.yml` | Production | Images de production, agent épinglé sur la référence fournie par le Central |
| `docker-compose.local.yml` | Surcharges locales | Ajustements optionnels, par exemple l'exposition d'un GPU |
| `Dockerfile` | Build | Image Central (UI + API + jobs) |
| `Dockerfile.agent` | Build | Image agent avec FFmpeg |
| `docker/agent-image.json` | Publication | Dépôt d’image agent à publier ; sa référence et son digest sont joints au manifeste de release |
| `docker/secrets/` | Production | Clés secrètes (JWT, DB, Coturn, etc.) |
Pour une installation de production, définissez `AGENT_IMAGE_REFERENCE` sur la valeur `image@digest` du compose généré par le Central. Le dépôt et le digest proviennent du manifeste `agent-image.json` de la release ; le compose n’utilise pas de tag mutable.
### Services
| Service | Image | Port par défaut | Dépend de |
@@ -113,7 +116,7 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
| `postgresql` | `postgres:17-alpine` | 5432 | — |
| `rustfs` | `rustfs/rustfs:latest` | 9000 (S3), 9001 (console) | — |
| `heimdall` | `heimdall:latest` (dev) / `eltruncho/heimdall:latest` (prod) | 5000 | postgresql (healthy) |
| `heimdall-agent` | `heimdall-agent:latest` (dev) / `eltruncho/heimdall-agent:latest` (prod) | — | heimdall |
| `heimdall-agent` | `heimdall-agent:latest` (dev) / `AGENT_IMAGE_REFERENCE` (prod) | — | heimdall |
| `ntfy` | `binwiederhier/ntfy` | 8080 | — |
| `coturn` | `coturn/coturn:4.6` | 3478 | — |
| `ollama` | `ollama/ollama:latest` | 11434 | — |
+33 -1
View File
@@ -24,9 +24,24 @@ export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin
agent_image=$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])')
[[ "$agent_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${agent_image##*/}" != *:* ]] || { echo 'Invalid agent image repository in docker/agent-image.json' >&2; exit 1; }
agent_registry=${agent_image%%/*}
if [[ "$agent_registry" == "$agent_image" || ( "$agent_registry" != *.* && "$agent_registry" != *:* && "$agent_registry" != localhost* ) ]]; then
agent_registry=docker.io
fi
if [[ "$agent_registry" != sources.tordais.cc ]]; then
: "${AGENT_REGISTRY_USER:?Agent registry user is required for $agent_registry}"
: "${AGENT_REGISTRY_TOKEN:?Agent registry token is required for $agent_registry}"
printf '%s' "$AGENT_REGISTRY_TOKEN" | docker login "$agent_registry" -u "$AGENT_REGISTRY_USER" --password-stdin
fi
: > artifacts/image-digests.txt
for component in server agent; do
image="sources.tordais.cc/arnaud.dartois/heimdall-$component"
if [[ "$component" == agent ]]; then
image=$agent_image
else
image="sources.tordais.cc/arnaud.dartois/heimdall-server"
fi
for image_tag in "sha-$sha" "${tag#v}"; do
if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then
docker pull "$image:$image_tag"
@@ -41,4 +56,21 @@ for component in server agent; do
done
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
python3 - "$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])')" <<'PY'
import json,sys
repository=sys.argv[1]
matches=set()
for line in open('artifacts/image-digests.txt'):
ref=line.strip()
if '@' not in ref: continue
image,digest=ref.rsplit('@',1)
if image == repository and digest.startswith('sha256:') and len(digest) == 71:
matches.add(digest)
if len(matches) != 1:
raise SystemExit('Expected one immutable agent image digest for configured repository')
with open('artifacts/packages/agent-image.json','w') as f:
json.dump({'image':repository,'digest':matches.pop()},f,sort_keys=True,separators=(',',':'))
f.write('\n')
PY
(cd artifacts/packages && sha256sum agent-image.json >> SHA256SUMS)
python3 scripts/ci/release-gitea.py
+43 -4
View File
@@ -16,14 +16,33 @@ public sealed class AgentOptions
[Required, Url]
public string CentralUrl { get; init; } = string.Empty;
/// <summary>Site token for agent registration.</summary>
/// <summary>Allow an unencrypted HTTP Central URL for isolated development networks only.</summary>
public bool AllowInsecureHttp { get; init; }
/// <summary>Site token for initial agent registration.</summary>
[Required, MinLength(1)]
public string SiteToken { get; init; } = string.Empty;
public string SiteToken
{
get => string.IsNullOrWhiteSpace(_siteToken)
? ReadSystemdCredential("site-token") ?? string.Empty
: _siteToken;
init => _siteToken = value ?? string.Empty;
}
private string _siteToken = string.Empty;
/// <summary>
/// Display name for this agent instance. Falls back to hostname if empty.
/// </summary>
public string? AgentName { get; init; }
public string? AgentName
{
get => string.IsNullOrWhiteSpace(_agentName)
? ReadSystemdCredential("agent-name")
: _agentName;
init => _agentName = value;
}
private string? _agentName;
/// <summary>Interval between heartbeats in seconds (default: 30).</summary>
[Range(5, 300)]
@@ -83,6 +102,26 @@ public sealed class AgentOptions
public string? BrokerUrl { get; init; }
public string DockerSocketPath { get; init; } = "/var/run/docker.sock";
public string DockerImageName { get; init; } = "eltruncho/heimdall-agent";
public bool AutoUpdateEnabled { get; set; }
private static string? ReadSystemdCredential(string name)
{
var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
if (string.IsNullOrWhiteSpace(directory))
return null;
try
{
var path = Path.Combine(directory, name);
return File.Exists(path) ? File.ReadAllText(path).TrimEnd('\r', '\n') : null;
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
}
+4
View File
@@ -39,6 +39,10 @@ if (!string.IsNullOrEmpty(sentryDsn))
builder.Services.AddOptions<AgentOptions>()
.BindConfiguration(AgentOptions.SectionName)
.ValidateDataAnnotations()
.Validate(options => Uri.TryCreate(options.CentralUrl, UriKind.Absolute, out var centralUri) &&
(centralUri.Scheme == Uri.UriSchemeHttps ||
(options.AllowInsecureHttp && centralUri.Scheme == Uri.UriSchemeHttp)),
"Agent:CentralUrl must use HTTPS unless Agent:AllowInsecureHttp is explicitly enabled.")
.ValidateOnStart();
// HTTP clients
@@ -149,6 +149,10 @@ public class AgentRegistrationService : BackgroundService
private async Task RegisterAgentAsync(HttpClient client, string hostname, CancellationToken stoppingToken)
{
if (string.IsNullOrWhiteSpace(_options.SiteToken))
throw new InvalidOperationException(
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
var maxRetries = _options.RegistrationMaxRetries;
@@ -115,6 +115,9 @@ public sealed class AgentUpdateService : BackgroundService
private async Task DownloadAndVerifyAsync(string url, string? expectedSha256, string destPath, CancellationToken ct)
{
if (expectedSha256 is null || expectedSha256.Length != 64 || expectedSha256.Any(c => !Uri.IsHexDigit(c)))
throw new InvalidOperationException("The release manifest does not contain a valid SHA-256 digest; refusing an unverified update");
using var client = _httpClientFactory.CreateClient("Central");
client.Timeout = TimeSpan.FromMinutes(10);
var response = await client.GetAsync(url, ct);
@@ -124,14 +127,12 @@ public sealed class AgentUpdateService : BackgroundService
await rs.CopyToAsync(fs, ct);
await fs.FlushAsync(ct);
await fs.DisposeAsync();
if (!string.IsNullOrEmpty(expectedSha256))
{
var hashBytes = await SHA256.HashDataAsync(File.OpenRead(destPath), ct);
var hex = Convert.ToHexString(hashBytes).ToLowerInvariant();
if (!string.Equals(hex, expectedSha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"SHA256 mismatch: expected {expectedSha256}, got {hex}");
_logger.LogInformation("SHA256 verified: {Hash}", hex);
}
await using var downloaded = File.OpenRead(destPath);
var hashBytes = await SHA256.HashDataAsync(downloaded, ct);
var hex = Convert.ToHexString(hashBytes).ToLowerInvariant();
if (!string.Equals(hex, expectedSha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"SHA256 mismatch: expected {expectedSha256}, got {hex}");
_logger.LogInformation("SHA256 verified: {Hash}", hex);
}
private static bool IsNewerVersion(string remote, string current)
@@ -52,51 +52,71 @@ public sealed class DockerUpdateService : BackgroundService
if (!force && !_options.AutoUpdateEnabled) return;
if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return;
_logger.LogInformation("Checking for agent updates...");
var latest = await FetchLatestVersionAsync(ct).ConfigureAwait(false);
if (latest is null) { _logger.LogWarning("Could not fetch latest version from Central"); return; }
var release = await FetchLatestReleaseAsync(ct).ConfigureAwait(false);
if (release is null) { _logger.LogWarning("Could not fetch latest release from Central"); return; }
var latest = release.Version;
var current = _options.Version;
if (!IsNewerVersion(current, latest)) { _logger.LogInformation("Up to date ({V})", current); return; }
_logger.LogInformation("Update available: {C} -> {A}", current, latest);
if (!IsSha256Digest(release.ContainerImageDigest))
{
_logger.LogError("Update manifest has no valid immutable agent image digest; refusing tag-based update");
return;
}
var cid = info.ContainerId;
if (string.IsNullOrEmpty(cid)) return;
var tag = ExtractTag(latest);
var image = _options.DockerImageName;
var full = image + ":" + tag;
var image = release.ContainerImage;
if (image is null || !IsValidImageRepository(image))
{
_logger.LogError("Update manifest has no valid agent image repository; refusing update");
return;
}
var full = image + "@" + release.ContainerImageDigest;
_logger.LogInformation("Pulling {Image}...", full);
var (pe, po) = await RunDocker("pull " + full, ct);
var (pe, po) = await RunDocker(["pull", full], ct);
if (pe != 0) { _logger.LogError("docker pull failed: {O}", po); return; }
var cfg = await InspectAsync(cid, ct).ConfigureAwait(false);
if (cfg is null) { _logger.LogError("Cannot inspect container"); return; }
_logger.LogInformation("Stopping current container {Id}...", cid);
await RunDocker("stop --time=30 " + cid, ct);
var (stopExitCode, stopOutput) = await RunDocker(["stop", "--time=30", cid], ct);
if (stopExitCode != 0)
{
_logger.LogError("Could not stop current container; update aborted: {Error}", stopOutput);
return;
}
var runArgs = BuildArgs(cfg, full);
_logger.LogInformation("Starting new container: docker run {Args}", runArgs);
var (re, ro) = await RunDocker("run -d " + runArgs, ct);
_logger.LogInformation("Starting updated container with pinned image {Image}", full);
var (re, ro) = await RunDocker(["run", "-d", .. runArgs], ct);
if (re != 0 || string.IsNullOrWhiteSpace(ro)) { _logger.LogError("docker run failed, rolling back"); await Rollback(cfg, image, ct); return; }
var nid = ro.Trim();
_logger.LogInformation("New container started: {N}", nid);
if (!await WaitForHealthAsync(nid, ct))
if (!await WaitForHealthAsync(nid, cfg.Environment, ct))
{
_logger.LogError("Health check failed, rolling back");
await RunDocker("stop --time=10 " + nid, ct);
await RunDocker("rm " + nid, ct);
await RunDocker(["stop", "--time=10", nid], ct);
await RunDocker(["rm", nid], ct);
await Rollback(cfg, image, ct);
return;
}
await RunDocker("rm " + cid, ct);
await RunDocker(["rm", cid], ct);
if (!string.IsNullOrEmpty(cfg.Name))
{
var (renameExitCode, _) = await RunDocker(["rename", nid, cfg.Name.TrimStart('/')], ct);
if (renameExitCode != 0) _logger.LogWarning("Updated container is healthy but could not reclaim its previous name");
}
_logger.LogInformation("Update complete: {C} -> {A}", current, latest);
}
private async Task Rollback(ContainerConfig cfg, string image, CancellationToken ct)
{
var oldImg = cfg.Image ?? (image + ":latest");
var oldImg = cfg.ImageId ?? cfg.Image ?? (image + ":latest");
var args = BuildArgs(cfg, oldImg);
var (e, _) = await RunDocker("run -d " + args, ct);
var (e, _) = await RunDocker(["run", "-d", .. args], ct);
if (e != 0) _logger.LogCritical("Rollback FAILED - manual intervention required");
else _logger.LogInformation("Rollback successful");
}
private async Task<string?> FetchLatestVersionAsync(CancellationToken ct)
private async Task<LatestUpdateResponse?> FetchLatestReleaseAsync(CancellationToken ct)
{
try
{
@@ -104,12 +124,7 @@ public sealed class DockerUpdateService : BackgroundService
http.DefaultRequestHeaders.Remove("X-API-Key");
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var r = await http.GetAsync(_options.CentralUrl.TrimEnd('/') + "/api/updates/agent/latest", ct);
if (r.IsSuccessStatusCode) { var u = await r.Content.ReadFromJsonAsync<LatestUpdateResponse>(ct); return u?.Version; }
if (r.StatusCode == System.Net.HttpStatusCode.NotFound)
{
var v = await http.GetAsync(_options.CentralUrl.TrimEnd('/') + "/api/version", ct);
if (v.IsSuccessStatusCode) { var i = await v.Content.ReadFromJsonAsync<VersionResponse>(ct); return i?.Version; }
}
if (r.IsSuccessStatusCode) return await r.Content.ReadFromJsonAsync<LatestUpdateResponse>(ct);
}
catch (Exception ex) { _logger.LogWarning(ex, "Failed to fetch latest version"); }
return null;
@@ -117,34 +132,51 @@ public sealed class DockerUpdateService : BackgroundService
private static async Task<ContainerConfig?> InspectAsync(string id, CancellationToken ct)
{
var (e, o) = await RunDocker("inspect " + id, ct);
var (e, o) = await RunDocker(["inspect", id], ct);
if (e != 0 || string.IsNullOrWhiteSpace(o)) return null;
try { return JsonSerializer.Deserialize<List<DockerInspectResult>>(o)?.FirstOrDefault()?.ToConfig(); } catch { return null; }
}
private static string BuildArgs(ContainerConfig c, string image)
private static List<string> BuildArgs(ContainerConfig c, string image)
{
var a = new List<string>();
if (!string.IsNullOrEmpty(c.Name)) a.Add("--name " + c.Name.TrimStart('/') + "-updated");
if (!string.IsNullOrEmpty(c.NetworkMode)) a.Add("--network " + c.NetworkMode);
if (!string.IsNullOrEmpty(c.RestartPolicy)) a.Add("--restart " + c.RestartPolicy);
foreach (var e in c.Environment) a.Add("-e " + e);
foreach (var p in c.Ports) a.Add("-p " + p);
foreach (var v in c.Volumes) a.Add("-v " + v);
foreach (var kv in c.Labels) a.Add("-l " + kv.Key + "=" + kv.Value);
if (!string.IsNullOrEmpty(c.Name)) a.AddRange(["--name", c.Name.TrimStart('/') + "-updated"]);
if (!string.IsNullOrEmpty(c.User)) a.AddRange(["--user", c.User]);
if (!string.IsNullOrEmpty(c.NetworkMode)) a.AddRange(["--network", c.NetworkMode]);
if (!string.IsNullOrEmpty(c.RestartPolicy)) a.AddRange(["--restart", c.RestartPolicy]);
foreach (var e in c.Environment) a.AddRange(["-e", e]);
foreach (var p in c.Ports) a.AddRange(["-p", p]);
foreach (var v in c.Volumes) a.AddRange(["-v", v]);
foreach (var d in c.Devices) a.AddRange(["--device", d]);
foreach (var request in c.DeviceRequests)
{
if (request.Driver is null or "nvidia")
{
if (request.Count > 0) a.AddRange(["--gpus", request.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)]);
else if (request.DeviceIds.Count > 0) a.AddRange(["--gpus", "device=" + string.Join(',', request.DeviceIds)]);
}
}
foreach (var capability in c.CapAdd) a.AddRange(["--cap-add", capability]);
foreach (var capability in c.CapDrop) a.AddRange(["--cap-drop", capability]);
foreach (var option in c.SecurityOptions) a.AddRange(["--security-opt", option]);
if (c.Privileged) a.Add("--privileged");
if (!string.IsNullOrEmpty(c.IpcMode)) a.AddRange(["--ipc", c.IpcMode]);
if (!string.IsNullOrEmpty(c.PidMode)) a.AddRange(["--pid", c.PidMode]);
if (c.ShmSize > 0) a.AddRange(["--shm-size", c.ShmSize.ToString(System.Globalization.CultureInfo.InvariantCulture)]);
foreach (var kv in c.Labels) a.AddRange(["-l", kv.Key + "=" + kv.Value]);
a.Add(image);
return string.Join(' ', a);
return a;
}
private static async Task<bool> WaitForHealthAsync(string id, CancellationToken ct)
private static async Task<bool> WaitForHealthAsync(string id, IReadOnlyList<string> environment, CancellationToken ct)
{
var dl = DateTime.UtcNow + TimeSpan.FromSeconds(60);
while (DateTime.UtcNow < dl && !ct.IsCancellationRequested)
{
try
{
var (_, o) = await RunDocker($"inspect --format='{{{{range .NetworkSettings.Ports}}}}{{{{(index . 0).HostPort}}}}{{{{end}}}}'", ct);
var p = ParsePort(o);
var (_, o) = await RunDocker(["inspect", "--format={{range .NetworkSettings.Ports}}{{(index . 0).HostPort}}{{end}}", id], ct);
var p = ParsePort(o, environment);
using var h = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var r = await h.GetAsync("http://localhost:" + p + "/health/live", ct);
if (r.IsSuccessStatusCode) return true;
@@ -155,11 +187,15 @@ public sealed class DockerUpdateService : BackgroundService
return false;
}
private static string ParsePort(string? o)
private static string ParsePort(string? o, IReadOnlyList<string> environment)
{
if (string.IsNullOrWhiteSpace(o)) return "8081";
foreach (var p in o.Trim().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries))
if (int.TryParse(p, out _)) return p;
if (!string.IsNullOrWhiteSpace(o))
foreach (var p in o.Trim().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries))
if (int.TryParse(p, out _)) return p;
var urls = environment.FirstOrDefault(e => e.StartsWith("ASPNETCORE_URLS=", StringComparison.OrdinalIgnoreCase))?["ASPNETCORE_URLS=".Length..];
if (!string.IsNullOrWhiteSpace(urls))
foreach (var url in urls.Split(';', ','))
if (int.TryParse(url[(url.LastIndexOf(':') + 1)..].TrimEnd('/'), out var port)) return port.ToString(System.Globalization.CultureInfo.InvariantCulture);
return "8081";
}
@@ -177,17 +213,25 @@ public sealed class DockerUpdateService : BackgroundService
return v;
}
private static string ExtractTag(string v)
{
if (v.StartsWith("agent-", StringComparison.OrdinalIgnoreCase)) v = v[6..];
return v;
}
private static bool IsValidImageRepository(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.EndsWith('/')
&& !image.Contains("//", StringComparison.Ordinal)
&& !image.Split('/').Last().Contains(':');
private static async Task<(int, string)> RunDocker(string args, CancellationToken ct)
private static bool IsSha256Digest(string? value) => value is { Length: 71 }
&& value.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& value[7..].All(Uri.IsHexDigit);
private static async Task<(int, string)> RunDocker(IReadOnlyList<string> args, CancellationToken ct)
{
try
{
var psi = new ProcessStartInfo("docker", args) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true };
var psi = new ProcessStartInfo("docker") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true };
foreach (var arg in args) psi.ArgumentList.Add(arg);
using var proc = Process.Start(psi);
if (proc is null) return (-1, "no process");
var so = await proc.StandardOutput.ReadToEndAsync(ct);
@@ -198,29 +242,103 @@ public sealed class DockerUpdateService : BackgroundService
catch (Exception ex) { return (-1, ex.Message); }
}
private sealed class LatestUpdateResponse { [JsonPropertyName("version")] public string? Version { get; init; } }
private sealed class VersionResponse { [JsonPropertyName("version")] public string? Version { get; init; } }
private sealed class LatestUpdateResponse
{
[JsonPropertyName("version")] public string Version { get; init; } = string.Empty;
[JsonPropertyName("containerImage")] public string? ContainerImage { get; init; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; }
}
private sealed class DockerInspectResult
{
[JsonPropertyName("Name")] public string? Name { get; init; }
[JsonPropertyName("Image")] public string? ImageId { get; init; }
[JsonPropertyName("Config")] public DockerInspectConfig? Config { get; init; }
[JsonPropertyName("HostConfig")] public DockerInspectHostConfig? HostConfig { get; init; }
[JsonPropertyName("Mounts")] public List<DockerMount>? Mounts { get; init; }
public ContainerConfig ToConfig()
{
var c = new ContainerConfig { Name = Name, Image = Config?.Image };
var c = new ContainerConfig { Name = Name, Image = Config?.Image, ImageId = ImageId, User = Config?.User };
if (Config?.Env is not null) c.Environment.AddRange(Config.Env);
if (HostConfig?.PortBindings is not null) foreach (var cp in HostConfig.PortBindings) foreach (var b in cp.Value) c.Ports.Add((b.HostPort ?? "0") + ":" + cp.Key.TrimStart('/'));
if (HostConfig?.Binds is not null) c.Volumes.AddRange(HostConfig.Binds);
if (HostConfig?.PortBindings is not null) foreach (var cp in HostConfig.PortBindings) foreach (var b in cp.Value) c.Ports.Add((string.IsNullOrEmpty(b.HostIp) || b.HostIp == "0.0.0.0" ? "" : b.HostIp + ":") + (b.HostPort ?? "0") + ":" + cp.Key.TrimStart('/'));
if (Mounts is not null) foreach (var mount in Mounts) c.Volumes.Add(mount.ToVolumeSpec());
if (HostConfig?.NetworkMode is not null) c.NetworkMode = HostConfig.NetworkMode;
if (HostConfig?.RestartPolicy?.Name is not null) c.RestartPolicy = HostConfig.RestartPolicy.Name;
if (HostConfig is not null)
{
c.Devices.AddRange(HostConfig.Devices?.Select(d => d.ToDeviceSpec()) ?? []);
c.DeviceRequests.AddRange(HostConfig.DeviceRequests ?? []);
c.CapAdd.AddRange(HostConfig.CapAdd ?? []);
c.CapDrop.AddRange(HostConfig.CapDrop ?? []);
c.SecurityOptions.AddRange(HostConfig.SecurityOptions ?? []);
c.Privileged = HostConfig.Privileged;
c.IpcMode = HostConfig.IpcMode;
c.PidMode = HostConfig.PidMode;
c.ShmSize = HostConfig.ShmSize;
}
if (Config?.Labels is not null) foreach (var kv in Config.Labels) c.Labels[kv.Key] = kv.Value;
return c;
}
}
private sealed class DockerInspectConfig { [JsonPropertyName("Image")] public string? Image { get; init; } [JsonPropertyName("Env")] public List<string>? Env { get; init; } [JsonPropertyName("Labels")] public Dictionary<string, string>? Labels { get; init; } }
private sealed class DockerInspectHostConfig { [JsonPropertyName("Binds")] public List<string>? Binds { get; init; } [JsonPropertyName("PortBindings")] public Dictionary<string, List<DockerPortBinding>>? PortBindings { get; init; } [JsonPropertyName("NetworkMode")] public string? NetworkMode { get; init; } [JsonPropertyName("RestartPolicy")] public DockerRestartPolicy? RestartPolicy { get; init; } }
private sealed class DockerInspectConfig { [JsonPropertyName("Image")] public string? Image { get; init; } [JsonPropertyName("User")] public string? User { get; init; } [JsonPropertyName("Env")] public List<string>? Env { get; init; } [JsonPropertyName("Labels")] public Dictionary<string, string>? Labels { get; init; } }
private sealed class DockerInspectHostConfig
{
[JsonPropertyName("PortBindings")] public Dictionary<string, List<DockerPortBinding>>? PortBindings { get; init; }
[JsonPropertyName("NetworkMode")] public string? NetworkMode { get; init; }
[JsonPropertyName("RestartPolicy")] public DockerRestartPolicy? RestartPolicy { get; init; }
[JsonPropertyName("Devices")] public List<DockerDevice>? Devices { get; init; }
[JsonPropertyName("DeviceRequests")] public List<DockerDeviceRequest>? DeviceRequests { get; init; }
[JsonPropertyName("CapAdd")] public List<string>? CapAdd { get; init; }
[JsonPropertyName("CapDrop")] public List<string>? CapDrop { get; init; }
[JsonPropertyName("SecurityOpt")] public List<string>? SecurityOptions { get; init; }
[JsonPropertyName("Privileged")] public bool Privileged { get; init; }
[JsonPropertyName("IpcMode")] public string? IpcMode { get; init; }
[JsonPropertyName("PidMode")] public string? PidMode { get; init; }
[JsonPropertyName("ShmSize")] public long ShmSize { get; init; }
}
private sealed class DockerMount
{
[JsonPropertyName("Type")] public string Type { get; init; } = "";
[JsonPropertyName("Name")] public string? Name { get; init; }
[JsonPropertyName("Source")] public string? Source { get; init; }
[JsonPropertyName("Destination")] public string Destination { get; init; } = "";
[JsonPropertyName("RW")] public bool ReadWrite { get; init; }
public string ToVolumeSpec() => (Name ?? Source ?? throw new InvalidOperationException("Container mount has no source")) + ":" + Destination + (ReadWrite ? "" : ":ro");
}
private sealed class DockerDevice
{
[JsonPropertyName("PathOnHost")] public string HostPath { get; init; } = "";
[JsonPropertyName("PathInContainer")] public string ContainerPath { get; init; } = "";
[JsonPropertyName("CgroupPermissions")] public string Permissions { get; init; } = "rwm";
public string ToDeviceSpec() => HostPath + ":" + ContainerPath + ":" + Permissions;
}
internal sealed class DockerDeviceRequest
{
[JsonPropertyName("Driver")] public string? Driver { get; init; }
[JsonPropertyName("Count")] public int Count { get; init; }
[JsonPropertyName("DeviceIDs")] public List<string> DeviceIds { get; init; } = [];
}
private sealed class DockerPortBinding { [JsonPropertyName("HostIp")] public string? HostIp { get; init; } [JsonPropertyName("HostPort")] public string? HostPort { get; init; } }
private sealed class DockerRestartPolicy { [JsonPropertyName("Name")] public string? Name { get; init; } }
}
internal sealed class ContainerConfig { public string? Name { get; set; } public string? Image { get; set; } public List<string> Environment { get; set; } = []; public List<string> Ports { get; set; } = []; public List<string> Volumes { get; set; } = []; public string? NetworkMode { get; set; } public string? RestartPolicy { get; set; } public Dictionary<string, string> Labels { get; set; } = []; }
internal sealed class ContainerConfig
{
public string? Name { get; set; }
public string? Image { get; set; }
public string? User { get; set; }
public List<string> Environment { get; set; } = [];
public List<string> Ports { get; set; } = [];
public List<string> Volumes { get; set; } = [];
public List<string> Devices { get; set; } = [];
public List<DockerUpdateService.DockerDeviceRequest> DeviceRequests { get; set; } = [];
public List<string> CapAdd { get; set; } = [];
public List<string> CapDrop { get; set; } = [];
public List<string> SecurityOptions { get; set; } = [];
public bool Privileged { get; set; }
public string? IpcMode { get; set; }
public string? PidMode { get; set; }
public long ShmSize { get; set; }
public string? NetworkMode { get; set; }
public string? RestartPolicy { get; set; }
public Dictionary<string, string> Labels { get; set; } = [];
}
@@ -21,7 +21,11 @@ public class UserRepository : IUserRepository
public async Task<PagedResult<UserResponse>> GetPagedAsync(int page, int pageSize, CancellationToken ct)
{
var query = _db.Users.AsNoTracking().OrderBy(u => u.DisplayName);
// Keep newly created accounts visible on the first page immediately after
// creation, even when the installation has more users than one page.
var query = _db.Users.AsNoTracking()
.OrderByDescending(u => u.CreatedAt)
.ThenBy(u => u.Id);
var total = await query.CountAsync(ct).ConfigureAwait(false);
var users = await query
.Skip((page - 1) * pageSize)
@@ -17,13 +17,20 @@
Copiez ce fichier <code>docker-compose.yml</code> sur la machine cible puis lancez
<code>docker compose up -d</code>.
</MudText>
<MudPaper Class="pa-3" Style="border-radius: 8px; background: #0d1117; overflow-x: auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:0.85rem;"><code>@ComposeYaml</code></pre>
</MudPaper>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
Copier le docker-compose.yml
</MudButton>
@if (_agentImageReference is null)
{
<MudAlert Severity="Severity.Warning">Le manifeste d’image de l’agent fourni par le Central est indisponible. Réessayez avant de copier le compose.</MudAlert>
}
else
{
<MudPaper Class="pa-3" Style="border-radius: 8px; background: #0d1117; overflow-x: auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:0.85rem;"><code>@ComposeYaml</code></pre>
</MudPaper>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
Copier le docker-compose.yml
</MudButton>
}
</MudTabPanel>
<MudTabPanel Text="Script shell" Icon="@Icons.Material.Filled.Terminal">
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">
@@ -50,6 +57,23 @@
[Parameter, EditorRequired] public string CentralUrl { get; set; } = "";
[Inject] private ISnackbar Snackbar { get; set; } = default!;
[Inject] private HeimdallApiClient Api { get; set; } = default!;
private string? _agentImageReference;
protected override async Task OnInitializedAsync()
{
try
{
var release = await Api.GetLatestUpdateAsync();
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && !string.IsNullOrWhiteSpace(release.ContainerImageDigest))
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
}
catch
{
// The compose stays hidden until Central provides a verified image manifest.
}
}
private string ComposeYaml
{
@@ -59,9 +83,10 @@
return $$"""
services:
heimdall-agent:
image: eltruncho/heimdall-agent:latest
image: {{_agentImageReference}}
container_name: heimdall-agent-{{safeName}}
restart: unless-stopped
user: "1654:1654"
environment:
Agent__CentralUrl: {{CentralUrl}}
Agent__SiteToken: {{SiteToken}}
@@ -70,6 +95,9 @@
Agent__StateDirectory: /var/lib/heimdall
volumes:
- agent_state:/var/lib/heimdall
depends_on:
agent-state-init:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
interval: 30s
@@ -77,6 +105,14 @@
retries: 3
start_period: 15s
agent-state-init:
image: {{_agentImageReference}}
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
volumes:
agent_state:
""";
@@ -84,7 +120,7 @@
}
private string ShellCommand
=> $"curl -sSL {CentralUrl}/install-agent.sh -o install-agent.sh && bash install-agent.sh --site-token {SiteToken} --name \"{SiteName}\"";
=> $"curl -sSL {ShellQuote(CentralUrl.TrimEnd('/') + "/install-agent.sh")} -o install-agent.sh && bash install-agent.sh --central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}";
private async Task CopyCode(string code)
{
@@ -101,4 +137,7 @@
sb.Append(char.IsLetterOrDigit(ch) ? ch : '-');
return sb.ToString().Trim('-');
}
private static string ShellQuote(string value)
=> $"'{value.Replace("'", "'\\''", StringComparison.Ordinal)}'";
}
@@ -1,4 +1,5 @@
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
using Heimdall.Infrastructure.Security;
@@ -112,12 +113,66 @@ public class UpdatesController : ControllerBase
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 image = await FetchAgentImageManifestAsync(release.Assets, client, ct);
result.ContainerImage = image?.Image;
result.ContainerImageDigest = image?.Digest;
lock (_cacheLock) { _cache = new LatestReleaseCache(result, DateTime.UtcNow); }
return result;
}
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
}
private static async Task<AgentImageManifest?> FetchAgentImageManifestAsync(List<ForgejoAsset>? assets, HttpClient client, CancellationToken ct)
{
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, "agent-image.json", 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 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);
private sealed class AgentImageManifest
{
[JsonPropertyName("image")] public string Image { get; init; } = string.Empty;
[JsonPropertyName("digest")] public string Digest { get; init; } = string.Empty;
}
private async Task RefreshCacheAsync(CancellationToken ct) { try { await FetchLatestReleaseAsync(ct); } catch { } }
private static LatestReleaseCache? GetCached() { lock (_cacheLock) return _cache; }
private static bool IsStale(LatestReleaseCache c) => DateTime.UtcNow - c.Timestamp > CacheDuration;
@@ -148,6 +203,8 @@ public class UpdatesController : ControllerBase
[JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; }
[JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; }
[JsonPropertyName("assets")] public Dictionary<string, PlatformAsset> Assets { get; set; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; set; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; }
}
public class PlatformAsset
{
@@ -1292,7 +1292,7 @@ public record CreateApiKeyResult(
[property: JsonPropertyName("siteId")] Guid? SiteId,
[property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt);
public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary<string, PlatformAssetInfo> Assets { get; set; } = []; }
public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary<string, PlatformAssetInfo> Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } }
public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } }
public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount);