From a6f22a9a38d4490f57d52947a2632eaa6de0192c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:03:20 +0000 Subject: [PATCH 1/7] test(cloud-init): pin Cloudflare boot output recorded on main before L18 Co-Authored-By: Claude Opus 5.5 --- .../cloudflare-tunnel-configured.yaml | 731 ++++++++++++++++ .../cloudflare-tunnel-defaults.yaml | 731 ++++++++++++++++ .../cloudflare-output/direct-minimal.yaml | 788 ++++++++++++++++++ .../direct-origin-ca-deployment.yaml | 788 ++++++++++++++++++ .../direct-origin-ca-task.yaml | 788 ++++++++++++++++++ .../cloudflare-output/direct-origin-ca.yaml | 788 ++++++++++++++++++ .../tests/cloudflare-output-snapshot.test.ts | 94 +++ ...-selfhost-l18-reverse-tunnel-cloud-init.md | 64 ++ 8 files changed, 4772 insertions(+) create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-configured.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-defaults.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-minimal.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-deployment.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-task.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca.yaml create mode 100644 packages/cloud-init/tests/cloudflare-output-snapshot.test.ts create mode 100644 tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-configured.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-configured.yaml new file mode 100644 index 0000000000..8b9260cf49 --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-configured.yaml @@ -0,0 +1,731 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: tunnel-bootstrap"' + - | + case $(uname -m) in + x86_64) CF_ARCH=amd64 CF_SHA256=1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872 ;; + aarch64) CF_ARCH=arm64 CF_SHA256=3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775 ;; + *) CF_ARCH="" ;; + esac + CF_TMP=$(mktemp) + if [ -z "$CF_ARCH" ] || ! curl --max-time 60 -fsSLo "$CF_TMP" "https://github.com/cloudflare/cloudflared/releases/download/2026.10.7/cloudflared-linux-$CF_ARCH" || + [ "$(sha256sum "$CF_TMP" | cut -d' ' -f1)" != "$CF_SHA256" ]; then + rm -f "$CF_TMP" + /usr/local/sbin/sam-boot-failure cloudflared_install + exit 1 + fi + install -m 0755 "$CF_TMP" /usr/local/bin/cloudflared + rm -f "$CF_TMP" + id sam-cloudflared >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-cloudflared + (umask 077; printf '%s' 'eyJhIjoiZml4dHVyZS1hY2NvdW50IiwidCI6ImZpeHR1cmUtdHVubmVsIiwicyI6ImZpeHR1cmUtc2VjcmV0In0=' > /etc/sam/cloudflared/tunnel-token) + chown sam-cloudflared /etc/sam/cloudflared/tunnel-token + chmod 0400 /etc/sam/cloudflared/tunnel-token + if ! /etc/sam/firewall/setup-firewall.sh; then + /usr/local/sbin/sam-boot-failure tunnel_firewall + exit 1 + fi + logger -t sam-boot "cloudflared installed (sha256 verified); public agent/SSH ingress closed" + - 'logger -t sam-boot "PHASE END: tunnel-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + - 'logger -t sam-boot "PHASE START: tunnel-connector"' + - | + if ! systemctl enable --now sam-cloudflared.service; then + /usr/local/sbin/sam-boot-failure tunnel_connector + exit 1 + fi + - 'logger -t sam-boot "PHASE END: tunnel-connector"' + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8080 + Environment=VM_AGENT_TUNNEL_ENABLED=true + Environment=VM_AGENT_TUNNEL_PORT=8555 + Environment=TLS_CERT_PATH= + Environment=TLS_KEY_PATH= + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + ExecStartPre=/etc/sam/firewall/setup-firewall.sh + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + - path: /usr/local/sbin/sam-wait-tunnel-listener + permissions: '0755' + content: | + #!/bin/sh + # Expose nothing until the vm-agent's loopback tunnel listener answers, + # giving up after an elapsed-time deadline (not an attempt count). + deadline=$(($(date +%s) + 200)) + until curl -fsS --max-time 3 -o /dev/null "http://127.0.0.1:8555/health"; do + if [ "$(date +%s)" -ge "$deadline" ]; then + logger -t sam-tunnel "tunnel listener 127.0.0.1:8555 not ready" + exit 1 + fi + sleep 2 + done + + - path: /etc/systemd/system/sam-cloudflared.service + permissions: '0644' + content: | + [Unit] + Description=SAM Cloudflare Tunnel connector + After=network-online.target vm-agent.service + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + User=sam-cloudflared + ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener + ExecStart=/usr/local/bin/cloudflared tunnel --no-autoupdate run --token-file /etc/sam/cloudflared/tunnel-token + TimeoutStartSec=infinity + Restart=always + RestartSec=7 + Slice=sam-infra.slice + NoNewPrivileges=yes + ProtectSystem=strict + ProtectHome=yes + PrivateTmp=yes + PrivateDevices=yes + ProtectKernelTunables=yes + ProtectKernelModules=yes + ProtectControlGroups=yes + ProtectClock=yes + ProtectHostname=yes + RestrictSUIDSGID=yes + RestrictRealtime=yes + LockPersonality=yes + RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK + CapabilityBoundingSet= + + [Install] + WantedBy=multi-user.target + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM tunnel-node firewall: no public ingress to the VM agent, its loopback + # tunnel listener, or SSH, on IPv4 and IPv6. Docker bridges may reach the + # agent port (Git credential helper). Egress and INPUT policy are untouched. + # The rules live in one chain replaced by a single iptables-restore + # transaction, so a re-run (cron, provisioning, every vm-agent start) + # never opens a gap. + set -euo pipefail + VM_AGENT_PORT="8080" + TUNNEL_PORT="8555" + CHAIN=SAM-TUNNEL-INGRESS + # Whether the INPUT jump exists is decided BEFORE iptables-restore starts. The restore + # holds the xtables lock while it reads stdin, so an iptables call inside the producer + # below would wait on that lock forever under iptables-legacy. + # -w waits for the lock instead of misreading contention as "absent" (a duplicate jump). + jump_state() { if "$1" -C INPUT -j "$CHAIN" -w 2>/dev/null; then echo present; else echo absent; fi; } + rules() { + echo '*filter' + echo ":$CHAIN - [0:0]" + [ "$2" = present ] || echo "-I INPUT 1 -j $CHAIN" + echo "-A $CHAIN -i lo -j RETURN" + echo "-A $CHAIN -i docker0 -p tcp --dport $VM_AGENT_PORT -j RETURN" + echo "-A $CHAIN -i br-+ -p tcp --dport $VM_AGENT_PORT -j RETURN" + for port in "$VM_AGENT_PORT" "$TUNNEL_PORT"; do + echo "-A $CHAIN -p tcp --dport $port -j DROP" + echo "-A $CHAIN -p udp --dport $port -j DROP" + done + echo "-A $CHAIN -p tcp --dport 22 -j DROP" + echo COMMIT + } + jump_v4=$(jump_state iptables) + rules iptables "$jump_v4" | iptables-restore --noflush + # Usability of ip6tables, not modprobe, decides: the module may be built in. + modprobe ip6_tables 2>/dev/null || true + if ip6tables -L -n >/dev/null 2>&1; then + jump_v6=$(jump_state ip6tables) + rules ip6tables "$jump_v6" | ip6tables-restore --noflush + elif [ -n "$(ip -6 addr show scope global 2>/dev/null)" ]; then + # Go serves 0.0.0.0 dual-stack: global IPv6 without ip6tables is exposure. + logger -t sam-firewall "ERROR: ip6tables unavailable on a tunnel node with global IPv6; refusing" + exit 1 + fi + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + logger -t sam-firewall "Firewall configured: tunnel node, no public agent/SSH ingress" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-defaults.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-defaults.yaml new file mode 100644 index 0000000000..6118291571 --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-defaults.yaml @@ -0,0 +1,731 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: tunnel-bootstrap"' + - | + case $(uname -m) in + x86_64) CF_ARCH=amd64 CF_SHA256=1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872 ;; + aarch64) CF_ARCH=arm64 CF_SHA256=3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775 ;; + *) CF_ARCH="" ;; + esac + CF_TMP=$(mktemp) + if [ -z "$CF_ARCH" ] || ! curl --max-time 60 -fsSLo "$CF_TMP" "https://github.com/cloudflare/cloudflared/releases/download/2026.10.7/cloudflared-linux-$CF_ARCH" || + [ "$(sha256sum "$CF_TMP" | cut -d' ' -f1)" != "$CF_SHA256" ]; then + rm -f "$CF_TMP" + /usr/local/sbin/sam-boot-failure cloudflared_install + exit 1 + fi + install -m 0755 "$CF_TMP" /usr/local/bin/cloudflared + rm -f "$CF_TMP" + id sam-cloudflared >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-cloudflared + (umask 077; printf '%s' 'eyJhIjoiZml4dHVyZS1hY2NvdW50IiwidCI6ImZpeHR1cmUtdHVubmVsIiwicyI6ImZpeHR1cmUtc2VjcmV0In0=' > /etc/sam/cloudflared/tunnel-token) + chown sam-cloudflared /etc/sam/cloudflared/tunnel-token + chmod 0400 /etc/sam/cloudflared/tunnel-token + if ! /etc/sam/firewall/setup-firewall.sh; then + /usr/local/sbin/sam-boot-failure tunnel_firewall + exit 1 + fi + logger -t sam-boot "cloudflared installed (sha256 verified); public agent/SSH ingress closed" + - 'logger -t sam-boot "PHASE END: tunnel-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + - 'logger -t sam-boot "PHASE START: tunnel-connector"' + - | + if ! systemctl enable --now sam-cloudflared.service; then + /usr/local/sbin/sam-boot-failure tunnel_connector + exit 1 + fi + - 'logger -t sam-boot "PHASE END: tunnel-connector"' + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8080 + Environment=VM_AGENT_TUNNEL_ENABLED=true + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH= + Environment=TLS_KEY_PATH= + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + ExecStartPre=/etc/sam/firewall/setup-firewall.sh + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + - path: /usr/local/sbin/sam-wait-tunnel-listener + permissions: '0755' + content: | + #!/bin/sh + # Expose nothing until the vm-agent's loopback tunnel listener answers, + # giving up after an elapsed-time deadline (not an attempt count). + deadline=$(($(date +%s) + 120)) + until curl -fsS --max-time 2 -o /dev/null "http://127.0.0.1:8444/health"; do + if [ "$(date +%s)" -ge "$deadline" ]; then + logger -t sam-tunnel "tunnel listener 127.0.0.1:8444 not ready" + exit 1 + fi + sleep 1 + done + + - path: /etc/systemd/system/sam-cloudflared.service + permissions: '0644' + content: | + [Unit] + Description=SAM Cloudflare Tunnel connector + After=network-online.target vm-agent.service + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + User=sam-cloudflared + ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener + ExecStart=/usr/local/bin/cloudflared tunnel --no-autoupdate run --token-file /etc/sam/cloudflared/tunnel-token + TimeoutStartSec=infinity + Restart=always + RestartSec=5 + Slice=sam-infra.slice + NoNewPrivileges=yes + ProtectSystem=strict + ProtectHome=yes + PrivateTmp=yes + PrivateDevices=yes + ProtectKernelTunables=yes + ProtectKernelModules=yes + ProtectControlGroups=yes + ProtectClock=yes + ProtectHostname=yes + RestrictSUIDSGID=yes + RestrictRealtime=yes + LockPersonality=yes + RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK + CapabilityBoundingSet= + + [Install] + WantedBy=multi-user.target + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM tunnel-node firewall: no public ingress to the VM agent, its loopback + # tunnel listener, or SSH, on IPv4 and IPv6. Docker bridges may reach the + # agent port (Git credential helper). Egress and INPUT policy are untouched. + # The rules live in one chain replaced by a single iptables-restore + # transaction, so a re-run (cron, provisioning, every vm-agent start) + # never opens a gap. + set -euo pipefail + VM_AGENT_PORT="8080" + TUNNEL_PORT="8444" + CHAIN=SAM-TUNNEL-INGRESS + # Whether the INPUT jump exists is decided BEFORE iptables-restore starts. The restore + # holds the xtables lock while it reads stdin, so an iptables call inside the producer + # below would wait on that lock forever under iptables-legacy. + # -w waits for the lock instead of misreading contention as "absent" (a duplicate jump). + jump_state() { if "$1" -C INPUT -j "$CHAIN" -w 2>/dev/null; then echo present; else echo absent; fi; } + rules() { + echo '*filter' + echo ":$CHAIN - [0:0]" + [ "$2" = present ] || echo "-I INPUT 1 -j $CHAIN" + echo "-A $CHAIN -i lo -j RETURN" + echo "-A $CHAIN -i docker0 -p tcp --dport $VM_AGENT_PORT -j RETURN" + echo "-A $CHAIN -i br-+ -p tcp --dport $VM_AGENT_PORT -j RETURN" + for port in "$VM_AGENT_PORT" "$TUNNEL_PORT"; do + echo "-A $CHAIN -p tcp --dport $port -j DROP" + echo "-A $CHAIN -p udp --dport $port -j DROP" + done + echo "-A $CHAIN -p tcp --dport 22 -j DROP" + echo COMMIT + } + jump_v4=$(jump_state iptables) + rules iptables "$jump_v4" | iptables-restore --noflush + # Usability of ip6tables, not modprobe, decides: the module may be built in. + modprobe ip6_tables 2>/dev/null || true + if ip6tables -L -n >/dev/null 2>&1; then + jump_v6=$(jump_state ip6tables) + rules ip6tables "$jump_v6" | ip6tables-restore --noflush + elif [ -n "$(ip -6 addr show scope global 2>/dev/null)" ]; then + # Go serves 0.0.0.0 dual-stack: global IPv6 without ip6tables is exposure. + logger -t sam-firewall "ERROR: ip6tables unavailable on a tunnel node with global IPv6; refusing" + exit 1 + fi + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + logger -t sam-firewall "Firewall configured: tunnel node, no public agent/SSH ingress" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-minimal.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-minimal.yaml new file mode 100644 index 0000000000..683916f53f --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-minimal.yaml @@ -0,0 +1,788 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: origin-ca-bootstrap"' + - | + ORIGIN_CA_CERTIFICATE_URL="" + TLS_CERT_PATH="/etc/sam/tls/origin-ca.pem" + TLS_KEY_PATH="/etc/sam/tls/origin-ca-key.pem" + TLS_CSR_PATH="/etc/sam/tls/origin-ca.csr" + if [ -n "$ORIGIN_CA_CERTIFICATE_URL" ]; then + logger -t sam-boot "Generating node-local Origin CA private key and CSR" + ORIGIN_CA_OK=true + if [ ! -s "$TLS_KEY_PATH" ]; then + if openssl genrsa -out "$TLS_KEY_PATH" 2048 >/dev/null 2>&1; then + chmod 600 "$TLS_KEY_PATH" + logger -t sam-boot "RSA key generated" + else + logger -t sam-boot "ERROR: openssl genrsa failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + if openssl req -new -key "$TLS_KEY_PATH" -out "$TLS_CSR_PATH" -subj "/CN=01SNAPSHOTNODE0000000000000" >/dev/null 2>&1; then + logger -t sam-boot "CSR generated" + else + logger -t sam-boot "ERROR: openssl req (CSR generation) failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + ATTEMPT=1 + DELAY=2 + ORIGIN_CA_OK=false + while [ "$ATTEMPT" -le 3 ]; do + CURL_EXIT=0 + HTTP_CODE=$(curl -sS --max-time 45 -o "$TLS_CERT_PATH" -w '%{http_code}' -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: text/plain" \ + --data-binary "@$TLS_CSR_PATH" \ + "$ORIGIN_CA_CERTIFICATE_URL" 2>/dev/null) || CURL_EXIT=$? + logger -t sam-boot "Origin CA cert request: attempt=$ATTEMPT HTTP=$HTTP_CODE curl_exit=$CURL_EXIT" + if [ "$CURL_EXIT" -eq 0 ] && { [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; }; then + if openssl x509 -in "$TLS_CERT_PATH" -noout >/dev/null 2>&1; then + ORIGIN_CA_OK=true + break + fi + logger -t sam-boot "ERROR: Origin CA response was not a certificate" + break + fi + # Auth/input failures cannot heal through retries. Transport/429/5xx can. + if [ "$CURL_EXIT" -eq 0 ]; then + case "$HTTP_CODE" in 429|5??) ;; *) break ;; esac + fi + if [ "$ATTEMPT" -ge 3 ]; then break; fi + if [ "$DELAY" -gt 8 ]; then DELAY=8; fi + sleep "$DELAY" + DELAY=$((DELAY * 2)) + ATTEMPT=$((ATTEMPT + 1)) + done + fi + rm -f "$TLS_CSR_PATH" + if [ "$ORIGIN_CA_OK" = true ] && [ -s "$TLS_CERT_PATH" ]; then + chmod 0644 "$TLS_CERT_PATH" + logger -t sam-boot "Node-local Origin CA certificate installed" + else + logger -t sam-boot "ERROR: Origin CA bootstrap failed — refusing to start vm-agent without TLS" + rm -f "$TLS_CERT_PATH" "$TLS_KEY_PATH" "$TLS_CSR_PATH" + /usr/local/sbin/sam-boot-failure origin_ca_bootstrap + exit 1 + fi + else + logger -t sam-boot "Skipping Origin CA bootstrap; TLS disabled" + fi + - 'logger -t sam-boot "PHASE END: origin-ca-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8080 + Environment=VM_AGENT_TUNNEL_ENABLED=false + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH= + Environment=TLS_KEY_PATH= + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM Firewall — restricts VM agent port to Cloudflare IPs only. + # + # Policy: INPUT chain stays ACCEPT. A single targeted DROP rule is + # appended LAST for tcp dport VM_AGENT_PORT so only the explicit CF + # ACCEPT rules (and loopback / docker bridges) can reach the agent port. + # Outbound connections and their replies are unaffected — we do NOT rely + # on conntrack to let reply packets back in, because conntrack state is + # invalidated by Docker install + restart + veth churn and the resulting + # silent drops caused a sustained ~6-minute "Cloudflare API unreachable" + # window on every fresh boot. + set -euo pipefail + # NOTE: intentionally no EXIT trap that clamps policy to DROP. A failed + # script must not lock the box out — the previous trap caused total + # blackouts when any earlier step errored before ACCEPT rules were added. + + VM_AGENT_PORT="8080" + CF_IPV4_URL="https://www.cloudflare.com/ips-v4" + CF_IPV6_URL="https://www.cloudflare.com/ips-v6" + + FALLBACK_IPV4="173.245.48.0/20 + 103.21.244.0/22 + 103.22.200.0/22 + 103.31.4.0/22 + 141.101.64.0/18 + 108.162.192.0/18 + 190.93.240.0/20 + 188.114.96.0/20 + 197.234.240.0/22 + 198.41.128.0/17 + 162.158.0.0/15 + 104.16.0.0/13 + 104.24.0.0/14 + 172.64.0.0/13 + 131.0.72.0/22" + + FALLBACK_IPV6="2400:cb00::/32 + 2606:4700::/32 + 2803:f800::/32 + 2405:b500::/32 + 2405:8100::/32 + 2a06:98c0::/29 + 2c0f:f248::/32" + + CF_IPV4=$(curl -sf --max-time 10 "$CF_IPV4_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv4 ranges, using fallback" + CF_IPV4="$FALLBACK_IPV4" + } + CF_IPV6=$(curl -sf --max-time 10 "$CF_IPV6_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv6 ranges, using fallback" + CF_IPV6="$FALLBACK_IPV6" + } + + # IPv4: policy ACCEPT so outbound reply packets are never dropped when + # conntrack state is invalidated (the root cause of the 6-minute Cloudflare + # blackout after Docker install + restart). Restriction is via targeted + # DROP rules on specific ports. The Hetzner cloud firewall remains the + # primary ingress gate; iptables is defense in depth against misconfig. + # + # Rule installation order (critical): install DROPs FIRST (so the agent + # port is never unprotected during a re-apply), then INSERT ACCEPT rules + # at position 1 so they take precedence. INSERT order is reverse of + # final priority — last -I becomes rule #1. + iptables -P INPUT ACCEPT + iptables -F INPUT + + # Catch-all DROPs installed FIRST. TCP+UDP on the agent port blocks both + # service traffic and port-fingerprinting via ICMP unreachable replies. + # TCP :22 defense-in-depth against sshd exposure — Hetzner console works + # without iptables SSH access for operator emergencies. + iptables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p tcp --dport 22 -j DROP + + # INSERT CF ACCEPT rules for VM_AGENT_PORT at top of chain. + while IFS= read -r cidr; do + [ -n "$cidr" ] && iptables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV4" + + # INSERT trusted-interface ACCEPTs (lo last so it is rule #1 — loopback + # traffic, including localhost-to-sshd for operator tooling, is never + # filtered by the port-22 DROP above). + iptables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i lo -j ACCEPT + + # IPv6: same pattern. Load the kernel module first — some Hetzner + # images ship without ip6_tables loaded, causing all ip6tables + # commands to fail ("ip6tables: No chain/target/match by that name"). + if modprobe ip6_tables 2>/dev/null && ip6tables -L -n >/dev/null 2>&1; then + ip6tables -P INPUT ACCEPT + ip6tables -F INPUT + + ip6tables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p tcp --dport 22 -j DROP + + while IFS= read -r cidr; do + [ -n "$cidr" ] && ip6tables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV6" + + ip6tables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i lo -j ACCEPT + else + logger -t sam-firewall "WARNING: ip6tables unavailable (kernel module not loaded), skipping IPv6 firewall rules" + fi + + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + + logger -t sam-firewall "Firewall configured: port $VM_AGENT_PORT restricted to Cloudflare IPs; metadata API block deferred until Docker restart" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-deployment.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-deployment.yaml new file mode 100644 index 0000000000..39f4b5d1bd --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-deployment.yaml @@ -0,0 +1,788 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: origin-ca-bootstrap"' + - | + ORIGIN_CA_CERTIFICATE_URL="https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/origin-ca-certificate" + TLS_CERT_PATH="/etc/sam/tls/origin-ca.pem" + TLS_KEY_PATH="/etc/sam/tls/origin-ca-key.pem" + TLS_CSR_PATH="/etc/sam/tls/origin-ca.csr" + if [ -n "$ORIGIN_CA_CERTIFICATE_URL" ]; then + logger -t sam-boot "Generating node-local Origin CA private key and CSR" + ORIGIN_CA_OK=true + if [ ! -s "$TLS_KEY_PATH" ]; then + if openssl genrsa -out "$TLS_KEY_PATH" 2048 >/dev/null 2>&1; then + chmod 600 "$TLS_KEY_PATH" + logger -t sam-boot "RSA key generated" + else + logger -t sam-boot "ERROR: openssl genrsa failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + if openssl req -new -key "$TLS_KEY_PATH" -out "$TLS_CSR_PATH" -subj "/CN=01SNAPSHOTNODE0000000000000" >/dev/null 2>&1; then + logger -t sam-boot "CSR generated" + else + logger -t sam-boot "ERROR: openssl req (CSR generation) failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + ATTEMPT=1 + DELAY=2 + ORIGIN_CA_OK=false + while [ "$ATTEMPT" -le 3 ]; do + CURL_EXIT=0 + HTTP_CODE=$(curl -sS --max-time 45 -o "$TLS_CERT_PATH" -w '%{http_code}' -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: text/plain" \ + --data-binary "@$TLS_CSR_PATH" \ + "$ORIGIN_CA_CERTIFICATE_URL" 2>/dev/null) || CURL_EXIT=$? + logger -t sam-boot "Origin CA cert request: attempt=$ATTEMPT HTTP=$HTTP_CODE curl_exit=$CURL_EXIT" + if [ "$CURL_EXIT" -eq 0 ] && { [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; }; then + if openssl x509 -in "$TLS_CERT_PATH" -noout >/dev/null 2>&1; then + ORIGIN_CA_OK=true + break + fi + logger -t sam-boot "ERROR: Origin CA response was not a certificate" + break + fi + # Auth/input failures cannot heal through retries. Transport/429/5xx can. + if [ "$CURL_EXIT" -eq 0 ]; then + case "$HTTP_CODE" in 429|5??) ;; *) break ;; esac + fi + if [ "$ATTEMPT" -ge 3 ]; then break; fi + if [ "$DELAY" -gt 8 ]; then DELAY=8; fi + sleep "$DELAY" + DELAY=$((DELAY * 2)) + ATTEMPT=$((ATTEMPT + 1)) + done + fi + rm -f "$TLS_CSR_PATH" + if [ "$ORIGIN_CA_OK" = true ] && [ -s "$TLS_CERT_PATH" ]; then + chmod 0644 "$TLS_CERT_PATH" + logger -t sam-boot "Node-local Origin CA certificate installed" + else + logger -t sam-boot "ERROR: Origin CA bootstrap failed — refusing to start vm-agent without TLS" + rm -f "$TLS_CERT_PATH" "$TLS_KEY_PATH" "$TLS_CSR_PATH" + /usr/local/sbin/sam-boot-failure origin_ca_bootstrap + exit 1 + fi + else + logger -t sam-boot "Skipping Origin CA bootstrap; TLS disabled" + fi + - 'logger -t sam-boot "PHASE END: origin-ca-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="deployment" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8443 + Environment=VM_AGENT_TUNNEL_ENABLED=false + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH=/etc/sam/tls/origin-ca.pem + Environment=TLS_KEY_PATH=/etc/sam/tls/origin-ca-key.pem + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE=deployment + Environment=NODE_ROLE=deployment + Environment=ENVIRONMENT_ID=env-snapshot + Environment=DEPLOY_SIGNING_PUB_KEY=PUBKEY-SNAPSHOT + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM Firewall — restricts VM agent port to Cloudflare IPs only. + # + # Policy: INPUT chain stays ACCEPT. A single targeted DROP rule is + # appended LAST for tcp dport VM_AGENT_PORT so only the explicit CF + # ACCEPT rules (and loopback / docker bridges) can reach the agent port. + # Outbound connections and their replies are unaffected — we do NOT rely + # on conntrack to let reply packets back in, because conntrack state is + # invalidated by Docker install + restart + veth churn and the resulting + # silent drops caused a sustained ~6-minute "Cloudflare API unreachable" + # window on every fresh boot. + set -euo pipefail + # NOTE: intentionally no EXIT trap that clamps policy to DROP. A failed + # script must not lock the box out — the previous trap caused total + # blackouts when any earlier step errored before ACCEPT rules were added. + + VM_AGENT_PORT="8443" + CF_IPV4_URL="https://www.cloudflare.com/ips-v4" + CF_IPV6_URL="https://www.cloudflare.com/ips-v6" + + FALLBACK_IPV4="173.245.48.0/20 + 103.21.244.0/22 + 103.22.200.0/22 + 103.31.4.0/22 + 141.101.64.0/18 + 108.162.192.0/18 + 190.93.240.0/20 + 188.114.96.0/20 + 197.234.240.0/22 + 198.41.128.0/17 + 162.158.0.0/15 + 104.16.0.0/13 + 104.24.0.0/14 + 172.64.0.0/13 + 131.0.72.0/22" + + FALLBACK_IPV6="2400:cb00::/32 + 2606:4700::/32 + 2803:f800::/32 + 2405:b500::/32 + 2405:8100::/32 + 2a06:98c0::/29 + 2c0f:f248::/32" + + CF_IPV4=$(curl -sf --max-time 10 "$CF_IPV4_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv4 ranges, using fallback" + CF_IPV4="$FALLBACK_IPV4" + } + CF_IPV6=$(curl -sf --max-time 10 "$CF_IPV6_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv6 ranges, using fallback" + CF_IPV6="$FALLBACK_IPV6" + } + + # IPv4: policy ACCEPT so outbound reply packets are never dropped when + # conntrack state is invalidated (the root cause of the 6-minute Cloudflare + # blackout after Docker install + restart). Restriction is via targeted + # DROP rules on specific ports. The Hetzner cloud firewall remains the + # primary ingress gate; iptables is defense in depth against misconfig. + # + # Rule installation order (critical): install DROPs FIRST (so the agent + # port is never unprotected during a re-apply), then INSERT ACCEPT rules + # at position 1 so they take precedence. INSERT order is reverse of + # final priority — last -I becomes rule #1. + iptables -P INPUT ACCEPT + iptables -F INPUT + + # Catch-all DROPs installed FIRST. TCP+UDP on the agent port blocks both + # service traffic and port-fingerprinting via ICMP unreachable replies. + # TCP :22 defense-in-depth against sshd exposure — Hetzner console works + # without iptables SSH access for operator emergencies. + iptables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p tcp --dport 22 -j DROP + + # INSERT CF ACCEPT rules for VM_AGENT_PORT at top of chain. + while IFS= read -r cidr; do + [ -n "$cidr" ] && iptables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV4" + + # INSERT trusted-interface ACCEPTs (lo last so it is rule #1 — loopback + # traffic, including localhost-to-sshd for operator tooling, is never + # filtered by the port-22 DROP above). + iptables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i lo -j ACCEPT + + # IPv6: same pattern. Load the kernel module first — some Hetzner + # images ship without ip6_tables loaded, causing all ip6tables + # commands to fail ("ip6tables: No chain/target/match by that name"). + if modprobe ip6_tables 2>/dev/null && ip6tables -L -n >/dev/null 2>&1; then + ip6tables -P INPUT ACCEPT + ip6tables -F INPUT + + ip6tables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p tcp --dport 22 -j DROP + + while IFS= read -r cidr; do + [ -n "$cidr" ] && ip6tables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV6" + + ip6tables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i lo -j ACCEPT + else + logger -t sam-firewall "WARNING: ip6tables unavailable (kernel module not loaded), skipping IPv6 firewall rules" + fi + + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + + logger -t sam-firewall "Firewall configured: port $VM_AGENT_PORT restricted to Cloudflare IPs; metadata API block deferred until Docker restart" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-task.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-task.yaml new file mode 100644 index 0000000000..e5594a1d3b --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca-task.yaml @@ -0,0 +1,788 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: origin-ca-bootstrap"' + - | + ORIGIN_CA_CERTIFICATE_URL="https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/origin-ca-certificate" + TLS_CERT_PATH="/etc/sam/tls/origin-ca.pem" + TLS_KEY_PATH="/etc/sam/tls/origin-ca-key.pem" + TLS_CSR_PATH="/etc/sam/tls/origin-ca.csr" + if [ -n "$ORIGIN_CA_CERTIFICATE_URL" ]; then + logger -t sam-boot "Generating node-local Origin CA private key and CSR" + ORIGIN_CA_OK=true + if [ ! -s "$TLS_KEY_PATH" ]; then + if openssl genrsa -out "$TLS_KEY_PATH" 2048 >/dev/null 2>&1; then + chmod 600 "$TLS_KEY_PATH" + logger -t sam-boot "RSA key generated" + else + logger -t sam-boot "ERROR: openssl genrsa failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + if openssl req -new -key "$TLS_KEY_PATH" -out "$TLS_CSR_PATH" -subj "/CN=01SNAPSHOTNODE0000000000000" >/dev/null 2>&1; then + logger -t sam-boot "CSR generated" + else + logger -t sam-boot "ERROR: openssl req (CSR generation) failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + ATTEMPT=1 + DELAY=2 + ORIGIN_CA_OK=false + while [ "$ATTEMPT" -le 3 ]; do + CURL_EXIT=0 + HTTP_CODE=$(curl -sS --max-time 45 -o "$TLS_CERT_PATH" -w '%{http_code}' -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: text/plain" \ + --data-binary "@$TLS_CSR_PATH" \ + "$ORIGIN_CA_CERTIFICATE_URL" 2>/dev/null) || CURL_EXIT=$? + logger -t sam-boot "Origin CA cert request: attempt=$ATTEMPT HTTP=$HTTP_CODE curl_exit=$CURL_EXIT" + if [ "$CURL_EXIT" -eq 0 ] && { [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; }; then + if openssl x509 -in "$TLS_CERT_PATH" -noout >/dev/null 2>&1; then + ORIGIN_CA_OK=true + break + fi + logger -t sam-boot "ERROR: Origin CA response was not a certificate" + break + fi + # Auth/input failures cannot heal through retries. Transport/429/5xx can. + if [ "$CURL_EXIT" -eq 0 ]; then + case "$HTTP_CODE" in 429|5??) ;; *) break ;; esac + fi + if [ "$ATTEMPT" -ge 3 ]; then break; fi + if [ "$DELAY" -gt 8 ]; then DELAY=8; fi + sleep "$DELAY" + DELAY=$((DELAY * 2)) + ATTEMPT=$((ATTEMPT + 1)) + done + fi + rm -f "$TLS_CSR_PATH" + if [ "$ORIGIN_CA_OK" = true ] && [ -s "$TLS_CERT_PATH" ]; then + chmod 0644 "$TLS_CERT_PATH" + logger -t sam-boot "Node-local Origin CA certificate installed" + else + logger -t sam-boot "ERROR: Origin CA bootstrap failed — refusing to start vm-agent without TLS" + rm -f "$TLS_CERT_PATH" "$TLS_KEY_PATH" "$TLS_CSR_PATH" + /usr/local/sbin/sam-boot-failure origin_ca_bootstrap + exit 1 + fi + else + logger -t sam-boot "Skipping Origin CA bootstrap; TLS disabled" + fi + - 'logger -t sam-boot "PHASE END: origin-ca-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID=project-snapshot + Environment=CHAT_SESSION_ID=session-snapshot + Environment=TASK_ID=task-snapshot + Environment=TASK_MODE=conversation + Environment=VM_AGENT_PORT=8443 + Environment=VM_AGENT_TUNNEL_ENABLED=false + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH=/etc/sam/tls/origin-ca.pem + Environment=TLS_KEY_PATH=/etc/sam/tls/origin-ca-key.pem + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM Firewall — restricts VM agent port to Cloudflare IPs only. + # + # Policy: INPUT chain stays ACCEPT. A single targeted DROP rule is + # appended LAST for tcp dport VM_AGENT_PORT so only the explicit CF + # ACCEPT rules (and loopback / docker bridges) can reach the agent port. + # Outbound connections and their replies are unaffected — we do NOT rely + # on conntrack to let reply packets back in, because conntrack state is + # invalidated by Docker install + restart + veth churn and the resulting + # silent drops caused a sustained ~6-minute "Cloudflare API unreachable" + # window on every fresh boot. + set -euo pipefail + # NOTE: intentionally no EXIT trap that clamps policy to DROP. A failed + # script must not lock the box out — the previous trap caused total + # blackouts when any earlier step errored before ACCEPT rules were added. + + VM_AGENT_PORT="8443" + CF_IPV4_URL="https://www.cloudflare.com/ips-v4" + CF_IPV6_URL="https://www.cloudflare.com/ips-v6" + + FALLBACK_IPV4="173.245.48.0/20 + 103.21.244.0/22 + 103.22.200.0/22 + 103.31.4.0/22 + 141.101.64.0/18 + 108.162.192.0/18 + 190.93.240.0/20 + 188.114.96.0/20 + 197.234.240.0/22 + 198.41.128.0/17 + 162.158.0.0/15 + 104.16.0.0/13 + 104.24.0.0/14 + 172.64.0.0/13 + 131.0.72.0/22" + + FALLBACK_IPV6="2400:cb00::/32 + 2606:4700::/32 + 2803:f800::/32 + 2405:b500::/32 + 2405:8100::/32 + 2a06:98c0::/29 + 2c0f:f248::/32" + + CF_IPV4=$(curl -sf --max-time 10 "$CF_IPV4_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv4 ranges, using fallback" + CF_IPV4="$FALLBACK_IPV4" + } + CF_IPV6=$(curl -sf --max-time 10 "$CF_IPV6_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv6 ranges, using fallback" + CF_IPV6="$FALLBACK_IPV6" + } + + # IPv4: policy ACCEPT so outbound reply packets are never dropped when + # conntrack state is invalidated (the root cause of the 6-minute Cloudflare + # blackout after Docker install + restart). Restriction is via targeted + # DROP rules on specific ports. The Hetzner cloud firewall remains the + # primary ingress gate; iptables is defense in depth against misconfig. + # + # Rule installation order (critical): install DROPs FIRST (so the agent + # port is never unprotected during a re-apply), then INSERT ACCEPT rules + # at position 1 so they take precedence. INSERT order is reverse of + # final priority — last -I becomes rule #1. + iptables -P INPUT ACCEPT + iptables -F INPUT + + # Catch-all DROPs installed FIRST. TCP+UDP on the agent port blocks both + # service traffic and port-fingerprinting via ICMP unreachable replies. + # TCP :22 defense-in-depth against sshd exposure — Hetzner console works + # without iptables SSH access for operator emergencies. + iptables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p tcp --dport 22 -j DROP + + # INSERT CF ACCEPT rules for VM_AGENT_PORT at top of chain. + while IFS= read -r cidr; do + [ -n "$cidr" ] && iptables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV4" + + # INSERT trusted-interface ACCEPTs (lo last so it is rule #1 — loopback + # traffic, including localhost-to-sshd for operator tooling, is never + # filtered by the port-22 DROP above). + iptables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i lo -j ACCEPT + + # IPv6: same pattern. Load the kernel module first — some Hetzner + # images ship without ip6_tables loaded, causing all ip6tables + # commands to fail ("ip6tables: No chain/target/match by that name"). + if modprobe ip6_tables 2>/dev/null && ip6tables -L -n >/dev/null 2>&1; then + ip6tables -P INPUT ACCEPT + ip6tables -F INPUT + + ip6tables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p tcp --dport 22 -j DROP + + while IFS= read -r cidr; do + [ -n "$cidr" ] && ip6tables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV6" + + ip6tables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i lo -j ACCEPT + else + logger -t sam-firewall "WARNING: ip6tables unavailable (kernel module not loaded), skipping IPv6 firewall rules" + fi + + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + + logger -t sam-firewall "Firewall configured: port $VM_AGENT_PORT restricted to Cloudflare IPs; metadata API block deferred until Docker restart" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca.yaml new file mode 100644 index 0000000000..dc7b32f704 --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/direct-origin-ca.yaml @@ -0,0 +1,788 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: origin-ca-bootstrap"' + - | + ORIGIN_CA_CERTIFICATE_URL="https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/origin-ca-certificate" + TLS_CERT_PATH="/etc/sam/tls/origin-ca.pem" + TLS_KEY_PATH="/etc/sam/tls/origin-ca-key.pem" + TLS_CSR_PATH="/etc/sam/tls/origin-ca.csr" + if [ -n "$ORIGIN_CA_CERTIFICATE_URL" ]; then + logger -t sam-boot "Generating node-local Origin CA private key and CSR" + ORIGIN_CA_OK=true + if [ ! -s "$TLS_KEY_PATH" ]; then + if openssl genrsa -out "$TLS_KEY_PATH" 2048 >/dev/null 2>&1; then + chmod 600 "$TLS_KEY_PATH" + logger -t sam-boot "RSA key generated" + else + logger -t sam-boot "ERROR: openssl genrsa failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + if openssl req -new -key "$TLS_KEY_PATH" -out "$TLS_CSR_PATH" -subj "/CN=01SNAPSHOTNODE0000000000000" >/dev/null 2>&1; then + logger -t sam-boot "CSR generated" + else + logger -t sam-boot "ERROR: openssl req (CSR generation) failed" + ORIGIN_CA_OK=false + fi + fi + if [ "$ORIGIN_CA_OK" = true ]; then + ATTEMPT=1 + DELAY=2 + ORIGIN_CA_OK=false + while [ "$ATTEMPT" -le 3 ]; do + CURL_EXIT=0 + HTTP_CODE=$(curl -sS --max-time 45 -o "$TLS_CERT_PATH" -w '%{http_code}' -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: text/plain" \ + --data-binary "@$TLS_CSR_PATH" \ + "$ORIGIN_CA_CERTIFICATE_URL" 2>/dev/null) || CURL_EXIT=$? + logger -t sam-boot "Origin CA cert request: attempt=$ATTEMPT HTTP=$HTTP_CODE curl_exit=$CURL_EXIT" + if [ "$CURL_EXIT" -eq 0 ] && { [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; }; then + if openssl x509 -in "$TLS_CERT_PATH" -noout >/dev/null 2>&1; then + ORIGIN_CA_OK=true + break + fi + logger -t sam-boot "ERROR: Origin CA response was not a certificate" + break + fi + # Auth/input failures cannot heal through retries. Transport/429/5xx can. + if [ "$CURL_EXIT" -eq 0 ]; then + case "$HTTP_CODE" in 429|5??) ;; *) break ;; esac + fi + if [ "$ATTEMPT" -ge 3 ]; then break; fi + if [ "$DELAY" -gt 8 ]; then DELAY=8; fi + sleep "$DELAY" + DELAY=$((DELAY * 2)) + ATTEMPT=$((ATTEMPT + 1)) + done + fi + rm -f "$TLS_CSR_PATH" + if [ "$ORIGIN_CA_OK" = true ] && [ -s "$TLS_CERT_PATH" ]; then + chmod 0644 "$TLS_CERT_PATH" + logger -t sam-boot "Node-local Origin CA certificate installed" + else + logger -t sam-boot "ERROR: Origin CA bootstrap failed — refusing to start vm-agent without TLS" + rm -f "$TLS_CERT_PATH" "$TLS_KEY_PATH" "$TLS_CSR_PATH" + /usr/local/sbin/sam-boot-failure origin_ca_bootstrap + exit 1 + fi + else + logger -t sam-boot "Skipping Origin CA bootstrap; TLS disabled" + fi + - 'logger -t sam-boot "PHASE END: origin-ca-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8443 + Environment=VM_AGENT_TUNNEL_ENABLED=false + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH=/etc/sam/tls/origin-ca.pem + Environment=TLS_KEY_PATH=/etc/sam/tls/origin-ca-key.pem + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM Firewall — restricts VM agent port to Cloudflare IPs only. + # + # Policy: INPUT chain stays ACCEPT. A single targeted DROP rule is + # appended LAST for tcp dport VM_AGENT_PORT so only the explicit CF + # ACCEPT rules (and loopback / docker bridges) can reach the agent port. + # Outbound connections and their replies are unaffected — we do NOT rely + # on conntrack to let reply packets back in, because conntrack state is + # invalidated by Docker install + restart + veth churn and the resulting + # silent drops caused a sustained ~6-minute "Cloudflare API unreachable" + # window on every fresh boot. + set -euo pipefail + # NOTE: intentionally no EXIT trap that clamps policy to DROP. A failed + # script must not lock the box out — the previous trap caused total + # blackouts when any earlier step errored before ACCEPT rules were added. + + VM_AGENT_PORT="8443" + CF_IPV4_URL="https://www.cloudflare.com/ips-v4" + CF_IPV6_URL="https://www.cloudflare.com/ips-v6" + + FALLBACK_IPV4="173.245.48.0/20 + 103.21.244.0/22 + 103.22.200.0/22 + 103.31.4.0/22 + 141.101.64.0/18 + 108.162.192.0/18 + 190.93.240.0/20 + 188.114.96.0/20 + 197.234.240.0/22 + 198.41.128.0/17 + 162.158.0.0/15 + 104.16.0.0/13 + 104.24.0.0/14 + 172.64.0.0/13 + 131.0.72.0/22" + + FALLBACK_IPV6="2400:cb00::/32 + 2606:4700::/32 + 2803:f800::/32 + 2405:b500::/32 + 2405:8100::/32 + 2a06:98c0::/29 + 2c0f:f248::/32" + + CF_IPV4=$(curl -sf --max-time 10 "$CF_IPV4_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv4 ranges, using fallback" + CF_IPV4="$FALLBACK_IPV4" + } + CF_IPV6=$(curl -sf --max-time 10 "$CF_IPV6_URL" 2>/dev/null) || { + logger -t sam-firewall "WARNING: Failed to fetch CF IPv6 ranges, using fallback" + CF_IPV6="$FALLBACK_IPV6" + } + + # IPv4: policy ACCEPT so outbound reply packets are never dropped when + # conntrack state is invalidated (the root cause of the 6-minute Cloudflare + # blackout after Docker install + restart). Restriction is via targeted + # DROP rules on specific ports. The Hetzner cloud firewall remains the + # primary ingress gate; iptables is defense in depth against misconfig. + # + # Rule installation order (critical): install DROPs FIRST (so the agent + # port is never unprotected during a re-apply), then INSERT ACCEPT rules + # at position 1 so they take precedence. INSERT order is reverse of + # final priority — last -I becomes rule #1. + iptables -P INPUT ACCEPT + iptables -F INPUT + + # Catch-all DROPs installed FIRST. TCP+UDP on the agent port blocks both + # service traffic and port-fingerprinting via ICMP unreachable replies. + # TCP :22 defense-in-depth against sshd exposure — Hetzner console works + # without iptables SSH access for operator emergencies. + iptables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + iptables -A INPUT -p tcp --dport 22 -j DROP + + # INSERT CF ACCEPT rules for VM_AGENT_PORT at top of chain. + while IFS= read -r cidr; do + [ -n "$cidr" ] && iptables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV4" + + # INSERT trusted-interface ACCEPTs (lo last so it is rule #1 — loopback + # traffic, including localhost-to-sshd for operator tooling, is never + # filtered by the port-22 DROP above). + iptables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + iptables -I INPUT 1 -i lo -j ACCEPT + + # IPv6: same pattern. Load the kernel module first — some Hetzner + # images ship without ip6_tables loaded, causing all ip6tables + # commands to fail ("ip6tables: No chain/target/match by that name"). + if modprobe ip6_tables 2>/dev/null && ip6tables -L -n >/dev/null 2>&1; then + ip6tables -P INPUT ACCEPT + ip6tables -F INPUT + + ip6tables -A INPUT -p tcp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p udp --dport "$VM_AGENT_PORT" -j DROP + ip6tables -A INPUT -p tcp --dport 22 -j DROP + + while IFS= read -r cidr; do + [ -n "$cidr" ] && ip6tables -I INPUT 1 -s "$cidr" -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + done <<< "$CF_IPV6" + + ip6tables -I INPUT 1 -i br-+ -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i docker0 -p tcp --dport "$VM_AGENT_PORT" -j ACCEPT + ip6tables -I INPUT 1 -i lo -j ACCEPT + else + logger -t sam-firewall "WARNING: ip6tables unavailable (kernel module not loaded), skipping IPv6 firewall rules" + fi + + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + + logger -t sam-firewall "Firewall configured: port $VM_AGENT_PORT restricted to Cloudflare IPs; metadata API block deferred until Docker restart" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts b/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts new file mode 100644 index 0000000000..8acbff6d9a --- /dev/null +++ b/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts @@ -0,0 +1,94 @@ +/** + * Byte-identity guard for the Cloudflare deployment's boot output. + * + * The self-host reverse-tunnel mode (reverse-tunnel.ts) shares the tunnel firewall, the + * loopback listener wait gate and the replacement table with the Cloudflare modes. These + * file snapshots were recorded from `main` (bfa8cc57c) BEFORE that mode was added, so any + * change to what a direct-ingress (default) or Cloudflare Tunnel node renders fails here. + * Do not update them to make a reverse-tunnel change pass: a Cloudflare node must render + * exactly what it rendered before. + */ +import { describe, expect, it } from 'vitest'; + +import { generateCloudInit } from '../src/generate'; +import type { CloudInitVariables } from '../src/variables'; + +// Synthetic connector token: same base64 JSON shape as a real one, no secret material. +const TUNNEL_TOKEN = Buffer.from( + JSON.stringify({ a: 'fixture-account', t: 'fixture-tunnel', s: 'fixture-secret' }) +).toString('base64'); + +const base: CloudInitVariables = { + nodeId: '01SNAPSHOTNODE0000000000000', + nodeUserId: 'user-snapshot', + nodeRuntimeIncarnationId: 'incarnation-snapshot', + hostname: 'node-01snapshotnode0000000000000', + controlPlaneUrl: 'https://api.example.com', + jwksUrl: 'https://api.example.com/.well-known/jwks.json', + callbackToken: 'CALLBACK-SNAPSHOT', + provider: 'hetzner', + vmAgentRequiredVersion: '0123456789abcdef0123456789abcdef01234567', + vmAgentMemoryReserveMb: '1024', +}; + +const originCa = { + originCaCertificateUrl: + 'https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/origin-ca-certificate', +}; + +const cases: Array<[string, CloudInitVariables]> = [ + // The default Cloudflare node: direct ingress with a node-local Origin CA certificate. + ['direct-origin-ca', { ...base, ...originCa }], + [ + 'direct-origin-ca-task', + { + ...base, + ...originCa, + projectId: 'project-snapshot', + chatSessionId: 'session-snapshot', + taskId: 'task-snapshot', + taskMode: 'conversation', + }, + ], + [ + 'direct-origin-ca-deployment', + { + ...base, + ...originCa, + role: 'deployment', + environmentId: 'env-snapshot', + deploySigningPubKey: 'PUBKEY-SNAPSHOT', + }, + ], + // Minimal legacy direct node (no Origin CA URL). + ['direct-minimal', { ...base }], + // Cloudflare Tunnel with every tunnel tunable left at its default. + ['cloudflare-tunnel-defaults', { ...base, cloudflareTunnelToken: TUNNEL_TOKEN }], + // Cloudflare Tunnel as provisioning renders it with explicit port and timings. + [ + 'cloudflare-tunnel-configured', + { + ...base, + cloudflareTunnelToken: TUNNEL_TOKEN, + cloudflareTunnelPort: '8555', + tunnelListenerWaitSeconds: '200', + tunnelListenerProbeTimeoutSeconds: '3', + tunnelListenerProbeIntervalSeconds: '2', + tunnelConnectorRestartSeconds: '7', + }, + ], +]; + +describe('Cloudflare cloud-init output is byte-identical to main', () => { + it.each(cases)('%s', async (name, variables) => { + const rendered = generateCloudInit(variables); + await expect(rendered).toMatchFileSnapshot(`./__snapshots__/cloudflare-output/${name}.yaml`); + }); + + it('no Cloudflare rendering mentions the reverse-tunnel connector', () => { + for (const [, variables] of cases) { + const rendered = generateCloudInit(variables); + expect(rendered).not.toMatch(/frpc|sam-frpc|reverse[_ -]tunnel/i); + } + }); +}); diff --git a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md new file mode 100644 index 0000000000..fcb345c45b --- /dev/null +++ b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md @@ -0,0 +1,64 @@ +# L18: reverse-tunnel cloud-init (frpc connector) on main + +## Problem + +L17a (#2831) and L17b (#2859, b7502ba96) landed reverse-tunnel leases, frps authorization, routing +and the self-host gateway under `apps/api/src/selfhost/reverse-tunnel/`. The transport driver +(`installReverseTunnelTransport(render)` in `selfhost/reverse-tunnel/transport.ts`) passes +`reverseTunnelCredential`, `reverseTunnelRemotePort` and `reverseTunnelLocalPort` to its boot +renderer, but main's `@simple-agent-manager/cloud-init` ignores them: a reverse-tunnel node would +boot as a direct-ingress node with no frpc, so it could never be reached. L18 adds the +reverse-tunnel ingress mode to the cloud-init package. + +SAM task 01M7QB46M5C4GE1Z51D1ZNEBGJ; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; plan idea +01M72M9AEB933ZY8269D376DKC (LANDING PLAN part 6, row L18). Source `origin/sam/selfhost-pass-2` +(tip 942d2c0a4), ported with `git checkout -- `, no cherry-picks. + +## Research findings + +- The integration branch's cloud-init diff against main is exactly the L18 file list: + `reverse-tunnel.ts` (new), `template-reverse-tunnel.ts` (new), `tunnel.ts`, `template-ingress.ts`, + `variables.ts`, `index.ts`, plus `tests/reverse-tunnel.test.ts`. generate.ts / validate.ts / + template.ts are unchanged, so the mode plugs into main's existing `ingressFragments()` and + `tunnelReplacements()` seams. +- Seam on main: the reverse-tunnel driver is installed only by `withReverseTunnel(worker, render)` + (`selfhost/reverse-tunnel/entry.ts`), which nothing in the Cloudflare Worker imports. The + Cloudflare provisioning path (`buildNodeCloudInit`, `node-provisioning-cloud-init.ts`) never sets + the reverse-tunnel variables, so Cloudflare nodes take the existing branches. +- Cross-boundary contract: the frpc install block reports `sam-boot-failure frpc_install` to + `POST /api/nodes/:id/boot-failure`. Main's picklist (`routes/node-boot-failure.ts`) rejects that + reason with 400, so a failed frpc install would go unrecorded. The integration branch adds + `frpc_install`; include it with its route test (rule 23). Only reverse-tunnel nodes send it. +- Template refactor in `template-ingress.ts`: the listener wait script is split out as + `TUNNEL_LISTENER_WAIT_WRITE_FILE` and `TUNNEL_WRITE_FILES` re-composes it. Must be byte-identical + for Cloudflare Tunnel nodes: proven by file snapshots recorded on main before the change. +- frpc config keeps the credential out of the world-readable frpc.toml (frp `{{ .Envs.* }}` + template, root-only 0400 EnvironmentFile). The frpc release is pinned with sha256 per arch. +- No open PR touches these paths (checked `gh pr list`, 2026-11-18). + +## Checklist + +- [x] Record Cloudflare output snapshots (direct Origin CA default, task, deployment, minimal, + Cloudflare Tunnel defaults and configured) from main BEFORE the change +- [ ] Bring the L18 cloud-init files from `origin/sam/selfhost-pass-2`; confirm byte-identity + (`git diff origin/sam/selfhost-pass-2 -- ` empty) +- [ ] Add `frpc_install` to the boot-failure picklist + route test +- [ ] Snapshot test passes unchanged after the change (byte-identical Cloudflare output) +- [ ] Reverse-tunnel tests (render, validation, executed runcmd under /bin/sh) pass +- [ ] API reverse-tunnel tests that render through `installReverseTunnelTransport(generateCloudInit)` + pass against the new renderer +- [ ] Docs: check public docs for boot-failure reasons / cloud-init ingress modes +- [ ] lint, typecheck, test, build +- [ ] security-auditor, task-completion-validator +- [ ] BOX proof (byte-identical to integration tip: cite BOX run 01M7QB382PDGH42XEG3ZFFS6DE) +- [ ] Staging: real VM node provisioning with heartbeat, then cleanup + +## Acceptance criteria + +- A Cloudflare node (direct or Cloudflare Tunnel) renders byte-identical cloud-init to main + (file snapshot test). +- A reverse-tunnel node renders the frpc connector, the tunnel firewall, no Origin CA and no + cloudflared; the credential appears only in the 0400 credential file. +- Invalid reverse-tunnel variable combinations are rejected without echoing the credential. +- The control plane accepts `frpc_install` boot-failure reports. +- Staging node provisioning still boots a VM that heartbeats; VM cleaned up. From 7b3eaff648bc7901235428efc8313e26c6c0e774 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:06:14 +0000 Subject: [PATCH 2/7] feat(cloud-init): L18 reverse-tunnel frpc boot mode for self-hosted control planes Ports packages/cloud-init reverse-tunnel files byte-identical from sam/selfhost-pass-2 (942d2c0a4): reverse-tunnel.ts, template-reverse-tunnel.ts, and the tunnel.ts / template-ingress.ts / variables.ts / index.ts seams. A non-empty reverseTunnelCredential selects the mode; Cloudflare nodes never set it and render byte-identical output (pinned by the snapshot test recorded on main in the previous commit). Accepts the frpc_install boot-failure reason the frpc install block reports. Adds a vertical slice: real provisionNode -> self-host driver -> real renderer -> provider user-data. Documents the boot mode in the self-hosting guide. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/node-boot-failure.ts | 1 + .../unit/routes/node-boot-failure.test.ts | 1 + .../node-reverse-tunnel-boot-render.test.ts | 113 ++++++ .../content/docs/docs/guides/self-hosting.mdx | 15 +- packages/cloud-init/src/index.ts | 8 + packages/cloud-init/src/reverse-tunnel.ts | 128 +++++++ packages/cloud-init/src/template-ingress.ts | 16 +- .../cloud-init/src/template-reverse-tunnel.ts | 128 +++++++ packages/cloud-init/src/tunnel.ts | 83 ++++- packages/cloud-init/src/variables.ts | 11 + .../cloud-init/tests/reverse-tunnel.test.ts | 329 ++++++++++++++++++ 11 files changed, 814 insertions(+), 19 deletions(-) create mode 100644 apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts create mode 100644 packages/cloud-init/src/reverse-tunnel.ts create mode 100644 packages/cloud-init/src/template-reverse-tunnel.ts create mode 100644 packages/cloud-init/tests/reverse-tunnel.test.ts diff --git a/apps/api/src/routes/node-boot-failure.ts b/apps/api/src/routes/node-boot-failure.ts index 81ad688433..cea4bd8af9 100644 --- a/apps/api/src/routes/node-boot-failure.ts +++ b/apps/api/src/routes/node-boot-failure.ts @@ -16,6 +16,7 @@ const BootFailureSchema = v.object({ 'origin_ca_bootstrap', 'vm_agent_download', 'cloudflared_install', + 'frpc_install', 'tunnel_firewall', 'tunnel_connector', ]), diff --git a/apps/api/tests/unit/routes/node-boot-failure.test.ts b/apps/api/tests/unit/routes/node-boot-failure.test.ts index be7369ca74..981782a49a 100644 --- a/apps/api/tests/unit/routes/node-boot-failure.test.ts +++ b/apps/api/tests/unit/routes/node-boot-failure.test.ts @@ -46,6 +46,7 @@ describe('boot failure callback', () => { 'origin_ca_bootstrap', 'vm_agent_download', 'cloudflared_install', + 'frpc_install', 'tunnel_firewall', 'tunnel_connector', ])('records %s through authenticated callback routing', async (reason) => { diff --git a/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts b/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts new file mode 100644 index 0000000000..f7cbe0ba9e --- /dev/null +++ b/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts @@ -0,0 +1,113 @@ +// Register shared boundary mocks before importing production services. +import './node-tunnel-fixture'; + +import type * as CloudInit from '@simple-agent-manager/cloud-init'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import YAML from 'yaml'; + +import { installReverseTunnelTransport } from '../../../src/selfhost/reverse-tunnel/transport'; +import { provisionNode } from '../../../src/services/nodes'; +import { applySqliteMigration } from '../../helpers/sqlite-d1'; +import { env, freshNode, mocks, setEnv, sqlite, tunnelEnv } from './node-tunnel-fixture'; + +/** + * L18 vertical slice: the real provisionNode leases a reverse-tunnel port, the self-host driver + * passes the lease to the REAL cloud-init renderer (the fixture's capture mock is bypassed), and + * the provider receives user-data that boots frpc against that lease. The lifecycle slice + * (node-reverse-tunnel-lifecycle.test.ts) covers leases and teardown with captured variables; + * this one proves the rendered boot document is what a node would actually run. + */ +const GATEWAY_SECRET = ['gateway', 'fixture', 'value', 'for', 'reverse', 'tunnel', 'tests'].join( + '-' +); + +const rendered: string[] = []; + +type BootDoc = { + runcmd: string[]; + write_files: Array<{ path: string; content: string; permissions?: string; owner?: string }>; +}; + +function file(doc: BootDoc, path: string) { + const entry = doc.write_files.find((f) => f.path === path); + if (!entry) throw new Error(`missing write_files entry ${path}`); + return entry; +} + +beforeEach(async () => { + rendered.length = 0; + applySqliteMigration( + sqlite, + new URL('../../../src/selfhost/migrations/0255_node_reverse_tunnel_leases.sql', import.meta.url) + ); + const real = await vi.importActual('@simple-agent-manager/cloud-init'); + installReverseTunnelTransport((variables) => { + const userData = real.generateCloudInit(variables); + rendered.push(userData); + return userData; + }); +}); + +describe('reverse-tunnel node boot document', () => { + it('renders frpc bound to the leased port, with the credential only in the root-only file', async () => { + setEnv( + tunnelEnv({ + VM_AGENT_TRANSPORT: 'reverse-tunnel', + REVERSE_TUNNEL_GATEWAY_SECRET: GATEWAY_SECRET, + ENCRYPTION_KEY: 'test-encryption-key-for-reverse-tunnel-credentials', + CF_API_TOKEN: undefined, + CF_ACCOUNT_ID: undefined, + CF_ZONE_ID: undefined, + }) + ); + const node = await freshNode(); + await expect(provisionNode(node.id, env)).resolves.toEqual({ + allocationConfirmed: true, + }); + + expect(rendered).toHaveLength(1); + const userData = rendered[0]!; + // The provider received exactly the document the real renderer produced. + expect(mocks.createVM).toHaveBeenCalledWith(expect.objectContaining({ userData })); + + const lease = sqlite + .prepare('SELECT port FROM node_reverse_tunnel_leases WHERE node_id = ?') + .get(node.id) as { port: number }; + // The fixture's capture mock was bypassed: the real renderer produced this document. + expect(mocks.cloudInitVars).toHaveLength(0); + + const doc = YAML.parse(userData) as BootDoc; + const frpc = file(doc, '/etc/sam/frpc/frpc.toml'); + expect(frpc.content).toContain(`remotePort = ${lease.port}`); + expect(frpc.content).toContain('localPort = 8444'); + expect(frpc.content).toContain(`user = "${node.id}"`); + expect(frpc.content).toContain( + 'metadatas.credential = "{{ .Envs.SAM_REVERSE_TUNNEL_CREDENTIAL }}"' + ); + + const credentialFile = file(doc, '/etc/sam/frpc/credential.env'); + expect(credentialFile.permissions).toBe('0400'); + const [, secret] = /^SAM_REVERSE_TUNNEL_CREDENTIAL=([A-Za-z0-9_-]{43})$/m.exec( + credentialFile.content + )!; + // The credential appears in exactly one place in the whole boot document. + expect(userData.split(secret!).length - 1).toBe(1); + + file(doc, '/etc/systemd/system/sam-frpc.service'); + expect(doc.runcmd.join('\n')).toContain('systemctl enable --now sam-frpc.service'); + // No Cloudflare ingress, no Origin CA, no public agent ingress. + expect(userData).not.toMatch( + /sam-cloudflared|cloudflared-linux|origin-ca-certificate|PHASE START: origin-ca/ + ); + }); + + it('control: a Cloudflare node never reaches the reverse-tunnel renderer', async () => { + setEnv(tunnelEnv({ VM_AGENT_TRANSPORT: undefined })); + const node = await freshNode(); + await provisionNode(node.id, env); + + expect(rendered).toHaveLength(0); + expect(mocks.cloudInitVars).toHaveLength(1); + expect(mocks.cloudInitVars[0]).not.toHaveProperty('reverseTunnelCredential'); + }); +}); diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index b568052547..354b817747 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -33,7 +33,20 @@ instance owns session replacement. Its Login plugin must apply the server-select with `unchange: false`, and every subsequent operation checks that session against the lease. Credential-key rotation recovery is tracked separately. Changing the root key rejects stale resume derivation and old session IDs, but a credential matching the stored lease hash can -still log in and obtain the new session ID; root-key rotation alone does not revoke that lease. Cloud-init and installer packaging follow this foundation. +still log in and obtain the new session ID; root-key rotation alone does not revoke that lease. Installer packaging follows this foundation. + +The node boot document for this transport comes from `@simple-agent-manager/cloud-init`. A +non-empty `reverseTunnelCredential` selects reverse-tunnel mode (`isReverseTunnelMode` in +`packages/cloud-init/src/reverse-tunnel.ts`). The node then gets the Cloudflare Tunnel firewall +(no public agent or SSH ingress), no Origin CA certificate and no cloudflared. It installs a +pinned frpc release, checked against a per-architecture sha256, and runs it as the unprivileged +`sam-frpc` unit (`packages/cloud-init/src/template-reverse-tunnel.ts`). frpc dials the control +plane host over `wss` on its public HTTPS port, verifies its certificate against the system CA +store, and exposes only the agent's loopback tunnel listener as one TCP proxy on the leased port. +The credential is written only to the root-only `/etc/sam/frpc/credential.env`; `frpc.toml` +reads it through frp's environment template. A failed frpc install reports the +`frpc_install` boot-failure reason. Cloudflare nodes never set these variables and render +exactly as before. The self-host entry wraps the shared Worker with `withReverseTunnel(worker, render)` from `apps/api/src/selfhost/reverse-tunnel/entry.ts`. That call installs the transport driver, serves diff --git a/packages/cloud-init/src/index.ts b/packages/cloud-init/src/index.ts index 6dcacc3e85..bab4484252 100644 --- a/packages/cloud-init/src/index.ts +++ b/packages/cloud-init/src/index.ts @@ -6,6 +6,14 @@ export { validateCloudInitSize, validateCloudInitVariables, } from './generate'; +export { + DEFAULT_FRPC_VERSION, + FRPC_RELEASES, + isReverseTunnelMode, + REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS, + REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + REVERSE_TUNNEL_PROXY_NAME, +} from './reverse-tunnel'; export { CLOUD_INIT_TEMPLATE } from './template'; export { CLOUDFLARED_RELEASES, diff --git a/packages/cloud-init/src/reverse-tunnel.ts b/packages/cloud-init/src/reverse-tunnel.ts new file mode 100644 index 0000000000..7b34c966b6 --- /dev/null +++ b/packages/cloud-init/src/reverse-tunnel.ts @@ -0,0 +1,128 @@ +import type { CloudInitVariables } from './variables'; + +/** + * frp releases a reverse-tunnel node may install, with the sha256 of each Linux release + * tarball (`frp__linux_.tar.gz`). Values were checked against the + * `frp_sha256_checksums.txt` asset published with the GitHub release. Add a release here + * (both architectures) before changing {@link DEFAULT_FRPC_VERSION}. + */ +export const FRPC_RELEASES: Readonly>> = { + '0.72.0': { + amd64: 'daf719b32ca2778770bb92955e231a07414d754378b9af328aa2642862479804', + arm64: '02180b857480302fd934e9ddbd50fe2f73229f99062f88756abc6de9df5e95cf', + }, +}; + +/** + * frp release installed on reverse-tunnel nodes. Deliberately code-pinned (no override var): it + * moves in lockstep with the box's frps image (deploy/selfhost/docker-compose.yml) and needs a + * reviewed checksum anyway. Upgrading means adding a FRPC_RELEASES entry and bumping both. + */ +export const DEFAULT_FRPC_VERSION = '0.72.0'; + +/** Release download prefix; the pinned checksum, not the origin, authenticates the tarball. */ +export const FRPC_DOWNLOAD_BASE_URL = 'https://github.com/fatedier/frp/releases/download'; + +/** + * Name of the node's single frp proxy. frps reports it to the authorization plugin as + * `.`, with `user` set to the node id, so the plugin can bind it to the node. + */ +export const REVERSE_TUNNEL_PROXY_NAME = 'sam-agent'; + +/** + * frpc heartbeat cadence. Each heartbeat reaches the control plane's frps plugin as a `Ping`, + * which re-checks the lease, so a released lease disconnects within about one interval. + */ +export const REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS = '30'; +export const REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = '90'; +/** + * Work connections frpc opens ahead of use. Each one is authorized by the control plane + * (frps NewWorkConn plugin op) when it is opened, so a warm pool keeps that round trip off the + * first request of a burst. Must not exceed frps `transport.maxPoolCount` (frp default 5). + */ +export const REVERSE_TUNNEL_POOL_COUNT = '2'; + +/** base64url credential minted by the control plane (32-byte HMAC → 43 characters). */ +const CREDENTIAL_RE = /^[A-Za-z0-9_-]{32,128}$/; +const NUMERIC_RE = /^[0-9]+$/; + +function isSet(value: string | undefined): value is string { + return value !== undefined && value !== ''; +} + +export function isReverseTunnelMode(variables: CloudInitVariables): boolean { + return isSet(variables.reverseTunnelCredential); +} + +function validPort(value: string): boolean { + return NUMERIC_RE.test(value) && Number(value) >= 1 && Number(value) <= 65535; +} + +/** Validate reverse-tunnel variables; error messages never echo the credential. */ +export function validateReverseTunnelVariables( + variables: CloudInitVariables, + errors: string[] +): void { + const reverseOnly = ['reverseTunnelRemotePort', 'reverseTunnelLocalPort'] as const; + if (!isReverseTunnelMode(variables)) { + for (const name of reverseOnly) { + if (isSet(variables[name])) errors.push(`${name}: requires reverseTunnelCredential`); + } + return; + } + if (isSet(variables.cloudflareTunnelToken)) { + errors.push('reverseTunnelCredential: cannot be combined with cloudflareTunnelToken'); + } + if (!CREDENTIAL_RE.test(variables.reverseTunnelCredential ?? '')) { + errors.push('reverseTunnelCredential: must be 32-128 base64url characters'); + } + if (!isSet(variables.nodeRuntimeIncarnationId)) { + errors.push( + 'nodeRuntimeIncarnationId: required in reverse-tunnel mode (the frps plugin binds it)' + ); + } + if (isSet(variables.originCaCertificateUrl)) { + errors.push( + 'originCaCertificateUrl: must be empty in reverse-tunnel mode (the agent is reached only through the tunnel)' + ); + } + const remote = variables.reverseTunnelRemotePort ?? ''; + if (!validPort(remote)) { + errors.push(`reverseTunnelRemotePort: must be numeric 1-65535 (got ${JSON.stringify(remote)})`); + } +} + +/** Host and port frpc dials: the control plane's own public HTTPS endpoint. */ +export function reverseTunnelServerAddress(controlPlaneUrl: string): { + host: string; + port: string; +} { + try { + const url = new URL(controlPlaneUrl); + return { host: url.hostname, port: url.port || '443' }; + } catch { + // validateCloudInitVariables already rejected an unparseable control plane URL. + return { host: '', port: '443' }; + } +} + +/** Template replacements for reverse-tunnel mode; other nodes get inert values. */ +export function reverseTunnelReplacements(variables: CloudInitVariables): Record { + const reverse = isReverseTunnelMode(variables); + const release = FRPC_RELEASES[DEFAULT_FRPC_VERSION]; + const server = reverseTunnelServerAddress(variables.controlPlaneUrl); + return { + '{{ reverse_tunnel_credential }}': reverse ? (variables.reverseTunnelCredential ?? '') : '', + '{{ reverse_tunnel_remote_port }}': reverse ? (variables.reverseTunnelRemotePort ?? '') : '', + '{{ reverse_tunnel_server_addr }}': server.host, + '{{ reverse_tunnel_server_port }}': server.port, + '{{ reverse_tunnel_proxy_name }}': REVERSE_TUNNEL_PROXY_NAME, + '{{ reverse_tunnel_heartbeat_interval_seconds }}': REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS, + '{{ reverse_tunnel_heartbeat_timeout_seconds }}': REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + '{{ reverse_tunnel_pool_count }}': REVERSE_TUNNEL_POOL_COUNT, + '{{ frpc_version }}': DEFAULT_FRPC_VERSION, + '{{ frpc_url }}': `${FRPC_DOWNLOAD_BASE_URL}/v${DEFAULT_FRPC_VERSION}`, + '{{ frpc_sha256_amd64 }}': release?.amd64 ?? '', + '{{ frpc_sha256_arm64 }}': release?.arm64 ?? '', + }; +} diff --git a/packages/cloud-init/src/template-ingress.ts b/packages/cloud-init/src/template-ingress.ts index 8f7148d3dc..0002186c2d 100644 --- a/packages/cloud-init/src/template-ingress.ts +++ b/packages/cloud-init/src/template-ingress.ts @@ -6,6 +6,8 @@ * - Direct (legacy): Origin CA bootstrap; the agent serves TLS on its public * port, restricted to Cloudflare IPs by the firewall. * - Tunnel: pinned cloudflared connector; no public agent ingress at all. + * - Reverse tunnel: pinned frpc connector (template-reverse-tunnel.ts); same firewall + * and loopback listener as the Cloudflare tunnel. */ /** Direct mode: node-local Origin CA key/CSR, signed by the control plane. */ @@ -125,10 +127,10 @@ export const TUNNEL_CONNECTOR_RUNCMD = ` - 'logger -t sam-boot "PHASE START: tu - 'logger -t sam-boot "PHASE END: tunnel-connector"'`; /** - * Tunnel mode: the connector unit. ExecStartPre gates every start, including - * restarts and reboots, on the agent's loopback tunnel listener answering. + * Tunnel modes (Cloudflare and reverse tunnel): the connector's ExecStartPre gate. It + * exposes nothing until the vm-agent's loopback tunnel listener answers. */ -export const TUNNEL_WRITE_FILES = ` - path: /usr/local/sbin/sam-wait-tunnel-listener +export const TUNNEL_LISTENER_WAIT_WRITE_FILE = ` - path: /usr/local/sbin/sam-wait-tunnel-listener permissions: '0755' content: | #!/bin/sh @@ -141,7 +143,13 @@ export const TUNNEL_WRITE_FILES = ` - path: /usr/local/sbin/sam-wait-tunnel-lis exit 1 fi sleep {{ tunnel_listener_probe_interval_seconds }} - done + done`; + +/** + * Cloudflare Tunnel mode: the connector unit. ExecStartPre gates every start, including + * restarts and reboots, on the agent's loopback tunnel listener answering. + */ +export const TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} - path: /etc/systemd/system/sam-cloudflared.service permissions: '0644' diff --git a/packages/cloud-init/src/template-reverse-tunnel.ts b/packages/cloud-init/src/template-reverse-tunnel.ts new file mode 100644 index 0000000000..3307a644ab --- /dev/null +++ b/packages/cloud-init/src/template-reverse-tunnel.ts @@ -0,0 +1,128 @@ +/** + * Reverse-tunnel ingress fragments (self-hosted control plane). The node's frpc dials the + * control-plane box over wss on 443 and exposes ONLY the vm-agent's loopback tunnel + * listener as one TCP proxy bound to a SAM-leased loopback port on the box. It reuses the + * Cloudflare tunnel's firewall (no public ingress at all) and listener wait gate. + * + * The per-node credential lives in a root-only systemd EnvironmentFile; frpc.toml refers to + * it through frp's own `{{ .Envs.* }}` template (not a cloud-init placeholder), so the + * world-readable config never contains it. + */ +import { TUNNEL_LISTENER_WAIT_WRITE_FILE } from './template-ingress'; + +/** Install the pinned frpc and close public ingress BEFORE the vm-agent listens. */ +export const REVERSE_TUNNEL_BOOTSTRAP_RUNCMD = ` - 'logger -t sam-boot "PHASE START: tunnel-bootstrap"' + - | + case $(uname -m) in + x86_64) FRP_ARCH=amd64 FRP_SHA256={{ frpc_sha256_amd64 }} ;; + aarch64) FRP_ARCH=arm64 FRP_SHA256={{ frpc_sha256_arm64 }} ;; + *) FRP_ARCH="" ;; + esac + FRP_TMP=$(mktemp) + FRP_DIR=$(mktemp -d) + FRP_NAME="frp_{{ frpc_version }}_linux_$FRP_ARCH" + if [ -z "$FRP_ARCH" ] || ! curl --max-time {{ agent_download_timeout_seconds }} -fsSLo "$FRP_TMP" "{{ frpc_url }}/$FRP_NAME.tar.gz" || + [ "$(sha256sum "$FRP_TMP" | cut -d' ' -f1)" != "$FRP_SHA256" ] || + ! tar -xzf "$FRP_TMP" -C "$FRP_DIR" "$FRP_NAME/frpc"; then + rm -rf "$FRP_TMP" "$FRP_DIR" + /usr/local/sbin/sam-boot-failure frpc_install + exit 1 + fi + install -m 0755 "$FRP_DIR/$FRP_NAME/frpc" /usr/local/bin/frpc + rm -rf "$FRP_TMP" "$FRP_DIR" + id sam-frpc >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-frpc + if ! /etc/sam/firewall/setup-firewall.sh; then + /usr/local/sbin/sam-boot-failure tunnel_firewall + exit 1 + fi + logger -t sam-boot "frpc installed (sha256 verified); public agent/SSH ingress closed" + - 'logger -t sam-boot "PHASE END: tunnel-bootstrap"'`; + +/** Start the connector once the agent runs; ExecStartPre waits for its loopback listener. */ +export const REVERSE_TUNNEL_CONNECTOR_RUNCMD = ` - 'logger -t sam-boot "PHASE START: tunnel-connector"' + - | + if ! systemctl enable --now sam-frpc.service; then + /usr/local/sbin/sam-boot-failure tunnel_connector + exit 1 + fi + - 'logger -t sam-boot "PHASE END: tunnel-connector"'`; + +/** + * frpc config, credential file and unit. poolCount: frpc keeps work connections open ahead of + * use, so frps' NewWorkConn authorization (a plugin round trip to the control plane) happens + * when the pool refills, not on the path of each proxied connection. + * loginFailExit=false + Restart=always: frpc keeps + * retrying (an frps restart, a Caddy restart, an authz rejection while the lease is being + * fixed) instead of exiting. useSystemCa: frpc verifies the box's public certificate; without + * it frpc would accept any certificate. + */ +export const REVERSE_TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} + + - path: /etc/sam/frpc/credential.env + permissions: '0400' + owner: root:root + content: | + SAM_REVERSE_TUNNEL_CREDENTIAL={{ reverse_tunnel_credential }} + + - path: /etc/sam/frpc/frpc.toml + permissions: '0644' + content: | + serverAddr = "{{ reverse_tunnel_server_addr }}" + serverPort = {{ reverse_tunnel_server_port }} + loginFailExit = false + user = "{{ node_id }}" + metadatas.node_id = "{{ node_id }}" + metadatas.incarnation = "{{ node_runtime_incarnation_id }}" + metadatas.credential = "{{ .Envs.SAM_REVERSE_TUNNEL_CREDENTIAL }}" + transport.protocol = "wss" + transport.tls.enable = true + transport.tls.serverName = "{{ reverse_tunnel_server_addr }}" + transport.tls.useSystemCa = true + transport.heartbeatInterval = {{ reverse_tunnel_heartbeat_interval_seconds }} + transport.heartbeatTimeout = {{ reverse_tunnel_heartbeat_timeout_seconds }} + transport.poolCount = {{ reverse_tunnel_pool_count }} + log.to = "console" + + [[proxies]] + name = "{{ reverse_tunnel_proxy_name }}" + type = "tcp" + localIP = "127.0.0.1" + localPort = {{ tunnel_port }} + remotePort = {{ reverse_tunnel_remote_port }} + + - path: /etc/systemd/system/sam-frpc.service + permissions: '0644' + content: | + [Unit] + Description=SAM reverse tunnel connector (frpc) + After=network-online.target vm-agent.service + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + User=sam-frpc + EnvironmentFile=/etc/sam/frpc/credential.env + ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener + ExecStart=/usr/local/bin/frpc -c /etc/sam/frpc/frpc.toml + TimeoutStartSec=infinity + Restart=always + RestartSec={{ tunnel_connector_restart_seconds }} + Slice=sam-infra.slice + NoNewPrivileges=yes + ProtectSystem=strict + ProtectHome=yes + PrivateTmp=yes + PrivateDevices=yes + ProtectKernelTunables=yes + ProtectKernelModules=yes + ProtectControlGroups=yes + ProtectClock=yes + ProtectHostname=yes + RestrictSUIDSGID=yes + RestrictRealtime=yes + LockPersonality=yes + RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK + CapabilityBoundingSet= + + [Install] + WantedBy=multi-user.target`; diff --git a/packages/cloud-init/src/tunnel.ts b/packages/cloud-init/src/tunnel.ts index 5d2b751f1a..4b137a8127 100644 --- a/packages/cloud-init/src/tunnel.ts +++ b/packages/cloud-init/src/tunnel.ts @@ -1,3 +1,8 @@ +import { + isReverseTunnelMode, + reverseTunnelReplacements, + validateReverseTunnelVariables, +} from './reverse-tunnel'; import { DIRECT_FIREWALL_WRITE_FILE, ORIGIN_CA_BOOTSTRAP_RUNCMD, @@ -6,6 +11,11 @@ import { TUNNEL_FIREWALL_WRITE_FILE, TUNNEL_WRITE_FILES, } from './template-ingress'; +import { + REVERSE_TUNNEL_BOOTSTRAP_RUNCMD, + REVERSE_TUNNEL_CONNECTOR_RUNCMD, + REVERSE_TUNNEL_WRITE_FILES, +} from './template-reverse-tunnel'; import type { CloudInitVariables } from './variables'; /** @@ -65,11 +75,25 @@ function orDefault(value: string | undefined, fallback: string): string { return isSet(value) ? value : fallback; } -/** A node is in tunnel mode exactly when it is given a connector token. */ -export function isTunnelMode(variables: CloudInitVariables): boolean { +function isCloudflareTunnelMode(variables: CloudInitVariables): boolean { return isSet(variables.cloudflareTunnelToken); } +/** + * A node is in tunnel mode exactly when it is given a Cloudflare connector token or a + * reverse-tunnel credential. Both modes share the firewall and the loopback listener. + */ +export function isTunnelMode(variables: CloudInitVariables): boolean { + return isCloudflareTunnelMode(variables) || isReverseTunnelMode(variables); +} + +/** The agent's loopback tunnel listener port for whichever tunnel mode is active. */ +function tunnelListenerPort(variables: CloudInitVariables): string { + return isReverseTunnelMode(variables) + ? orDefault(variables.reverseTunnelLocalPort, DEFAULT_CLOUDFLARE_TUNNEL_PORT) + : orDefault(variables.cloudflareTunnelPort, DEFAULT_CLOUDFLARE_TUNNEL_PORT); +} + function effectiveVmAgentPort(variables: CloudInitVariables): string { if (isSet(variables.vmAgentPort)) return variables.vmAgentPort; return isSet(variables.originCaCertificateUrl) ? '8443' : '8080'; @@ -80,7 +104,16 @@ function effectiveVmAgentPort(variables: CloudInitVariables): string { * echo the connector token. */ export function validateTunnelVariables(variables: CloudInitVariables, errors: string[]): void { - if (!isTunnelMode(variables)) { + validateReverseTunnelVariables(variables, errors); + if (isReverseTunnelMode(variables)) { + for (const name of ['cloudflareTunnelPort', 'cloudflaredVersion'] as const) { + if (isSet(variables[name])) errors.push(`${name}: requires cloudflareTunnelToken`); + } + validateListenerPort(variables, 'reverseTunnelLocalPort', errors); + validateTunnelTimings(variables, errors); + return; + } + if (!isCloudflareTunnelMode(variables)) { // Tunnel settings without a token would silently boot a direct-ingress node. const tunnelOnly: Array = [ 'cloudflareTunnelPort', @@ -106,14 +139,7 @@ export function validateTunnelVariables(variables: CloudInitVariables, errors: s ); } - const port = orDefault(variables.cloudflareTunnelPort, DEFAULT_CLOUDFLARE_TUNNEL_PORT); - if (!NUMERIC_RE.test(port) || Number(port) < 1 || Number(port) > 65535) { - errors.push(`cloudflareTunnelPort: must be numeric 1-65535 (got ${JSON.stringify(port)})`); - } else if (Number(port) === Number(effectiveVmAgentPort(variables))) { - errors.push( - 'cloudflareTunnelPort: must differ from vmAgentPort (that listener serves the bearerless Docker Git helper)' - ); - } + validateListenerPort(variables, 'cloudflareTunnelPort', errors); const version = orDefault(variables.cloudflaredVersion, DEFAULT_CLOUDFLARED_VERSION); if (!Object.hasOwn(CLOUDFLARED_RELEASES, version)) { @@ -122,6 +148,25 @@ export function validateTunnelVariables(variables: CloudInitVariables, errors: s ); } + validateTunnelTimings(variables, errors); +} + +function validateListenerPort( + variables: CloudInitVariables, + name: 'cloudflareTunnelPort' | 'reverseTunnelLocalPort', + errors: string[] +): void { + const port = orDefault(variables[name], DEFAULT_CLOUDFLARE_TUNNEL_PORT); + if (!NUMERIC_RE.test(port) || Number(port) < 1 || Number(port) > 65535) { + errors.push(`${name}: must be numeric 1-65535 (got ${JSON.stringify(port)})`); + } else if (Number(port) === Number(effectiveVmAgentPort(variables))) { + errors.push( + `${name}: must differ from vmAgentPort (that listener serves the bearerless Docker Git helper)` + ); + } +} + +function validateTunnelTimings(variables: CloudInitVariables, errors: string[]): void { for (const [name, max] of TUNNEL_TIMING_LIMITS) { const value = variables[name]; if (isSet(value) && (!NUMERIC_RE.test(value) || Number(value) < 1 || Number(value) > max)) { @@ -136,7 +181,15 @@ export function validateTunnelVariables(variables: CloudInitVariables, errors: s * connector, which also keeps user-data under the 32 KB Hetzner limit. */ export function ingressFragments(variables: CloudInitVariables): Record { - const tunnel = isTunnelMode(variables); + if (isReverseTunnelMode(variables)) { + return { + '{{ ingress_bootstrap_runcmd }}': REVERSE_TUNNEL_BOOTSTRAP_RUNCMD, + '{{ ingress_connector_runcmd }}': REVERSE_TUNNEL_CONNECTOR_RUNCMD, + '{{ ingress_write_files }}': REVERSE_TUNNEL_WRITE_FILES, + '{{ ingress_firewall_write_file }}': TUNNEL_FIREWALL_WRITE_FILE, + }; + } + const tunnel = isCloudflareTunnelMode(variables); return { '{{ ingress_bootstrap_runcmd }}': tunnel ? TUNNEL_BOOTSTRAP_RUNCMD : ORIGIN_CA_BOOTSTRAP_RUNCMD, '{{ ingress_connector_runcmd }}': tunnel ? TUNNEL_CONNECTOR_RUNCMD : '', @@ -150,6 +203,7 @@ export function ingressFragments(variables: CloudInitVariables): Record { const tunnel = isTunnelMode(variables); + const cloudflare = isCloudflareTunnelMode(variables); const version = orDefault(variables.cloudflaredVersion, DEFAULT_CLOUDFLARED_VERSION); const release = CLOUDFLARED_RELEASES[version]; return { @@ -159,8 +213,8 @@ export function tunnelReplacements(variables: CloudInitVariables): Record): CloudInitVariables { + return { + nodeId: '01M72NODEREVERSE0000000001', + nodeRuntimeIncarnationId: INCARNATION, + hostname: 'sam-reverse-node', + controlPlaneUrl: 'https://api.box.example.org', + jwksUrl: 'https://api.box.example.org/.well-known/jwks.json', + callbackToken: CALLBACK_TOKEN, + swapSizeMb: '0', + ...overrides, + }; +} + +const reverse = (overrides?: Partial) => + variables({ + reverseTunnelCredential: CREDENTIAL, + reverseTunnelRemotePort: '20007', + ...overrides, + }); + +type Parsed = { + runcmd: string[]; + write_files: Array<{ path: string; content: string; permissions?: string; owner?: string }>; +}; + +const parse = (vars: CloudInitVariables) => YAML.parse(generateCloudInit(vars)) as Parsed; + +function file(parsed: Parsed, path: string) { + const entry = parsed.write_files.find((f) => f.path === path); + if (!entry) throw new Error(`missing write_files entry ${path}`); + return entry; +} + +const tempDirs: string[] = []; +afterEach(() => { + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe('reverse-tunnel variable validation', () => { + it('accepts a credential and lease port with defaults', () => { + expect(() => validateCloudInitVariables(reverse())).not.toThrow(); + }); + + it.each([ + ['credential with shell metacharacters', { reverseTunnelCredential: `${'a'.repeat(40)}';id` }], + ['credential too short', { reverseTunnelCredential: 'short' }], + ['missing lease port', { reverseTunnelRemotePort: '' }], + ['lease port out of range', { reverseTunnelRemotePort: '70000' }], + ['listener port equal to the agent port', { reverseTunnelLocalPort: '8080' }], + [ + 'Origin CA in reverse-tunnel mode', + { originCaCertificateUrl: 'https://api.box.example.org/c' }, + ], + ['a Cloudflare token as well', { cloudflareTunnelToken: 'c'.repeat(64) }], + ['no runtime incarnation', { nodeRuntimeIncarnationId: '' }], + ['a cloudflared-only setting', { cloudflaredVersion: '2026.10.7' }], + ['wait seconds out of range', { tunnelListenerWaitSeconds: '0' }], + ])('rejects %s', (_name, overrides) => { + expect(() => validateCloudInitVariables(reverse(overrides))).toThrow(/validation failed/); + }); + + it('never echoes the credential in validation errors', () => { + let message = ''; + try { + validateCloudInitVariables(reverse({ reverseTunnelCredential: `${'Q'.repeat(40)}$(id)` })); + } catch (error) { + message = (error as Error).message; + } + expect(message).toContain('reverseTunnelCredential'); + expect(message).not.toContain('QQQQ'); + }); + + it.each(['reverseTunnelRemotePort', 'reverseTunnelLocalPort'] as const)( + 'rejects %s without a credential instead of booting a direct-ingress node', + (name) => { + expect(() => validateCloudInitVariables(variables({ [name]: '20001' }))).toThrow( + `${name}: requires reverseTunnelCredential` + ); + } + ); +}); + +describe('rendered reverse-tunnel user-data', () => { + it('runs the agent with the loopback tunnel listener and no Origin CA', () => { + const output = generateCloudInit(reverse()); + const unit = file(parse(reverse()), '/etc/systemd/system/vm-agent.service').content; + expect(unit).toContain('Environment=VM_AGENT_PORT=8080\n'); + expect(unit).toContain('Environment=TLS_CERT_PATH=\n'); + expect(unit).toContain('Environment=VM_AGENT_TUNNEL_ENABLED=true\n'); + expect(unit).toContain('Environment=VM_AGENT_TUNNEL_PORT=8444\n'); + expect(unit).toContain('ExecStartPre=/etc/sam/firewall/setup-firewall.sh'); + expect(output).not.toContain('origin-ca'); + expect(output).not.toContain('sam-cloudflared'); + expect(output).not.toContain('/usr/local/bin/cloudflared'); + }); + + it('writes an frpc config that dials the control plane over verified wss with one proxy', () => { + const toml = file(parse(reverse()), '/etc/sam/frpc/frpc.toml'); + // Pre-opened work connections keep the NewWorkConn plugin round trip off the data path. + expect(toml.content).toContain('transport.poolCount = 2\n'); + expect(toml.permissions).toBe('0644'); + const lines = toml.content.split('\n'); + for (const expected of [ + 'serverAddr = "api.box.example.org"', + 'serverPort = 443', + 'loginFailExit = false', + 'user = "01M72NODEREVERSE0000000001"', + 'metadatas.node_id = "01M72NODEREVERSE0000000001"', + `metadatas.incarnation = "${INCARNATION}"`, + 'metadatas.credential = "{{ .Envs.SAM_REVERSE_TUNNEL_CREDENTIAL }}"', + 'transport.protocol = "wss"', + 'transport.tls.enable = true', + 'transport.tls.serverName = "api.box.example.org"', + 'transport.tls.useSystemCa = true', + `name = "${REVERSE_TUNNEL_PROXY_NAME}"`, + 'type = "tcp"', + 'localIP = "127.0.0.1"', + 'localPort = 8444', + 'remotePort = 20007', + ]) { + expect(lines).toContain(expected); + } + expect(toml.content.match(/\[\[proxies\]\]/g)).toHaveLength(1); + expect(toml.content).not.toContain(CREDENTIAL); + }); + + it('keeps the credential in a root-only environment file, exactly once in user-data', () => { + const output = generateCloudInit(reverse()); + expect(output.split(CREDENTIAL)).toHaveLength(2); + const env = file(parse(reverse()), '/etc/sam/frpc/credential.env'); + expect(env.permissions).toBe('0400'); + expect(env.owner).toBe('root:root'); + expect(env.content.trim()).toBe(`SAM_REVERSE_TUNNEL_CREDENTIAL=${CREDENTIAL}`); + }); + + it('supervises frpc as an unprivileged, restart-always unit gated on the agent listener', () => { + const parsed = parse(reverse()); + const unit = file(parsed, '/etc/systemd/system/sam-frpc.service').content; + expect(unit).toContain('User=sam-frpc\n'); + expect(unit).toContain('EnvironmentFile=/etc/sam/frpc/credential.env\n'); + expect(unit).toContain('ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener\n'); + expect(unit).toContain('ExecStart=/usr/local/bin/frpc -c /etc/sam/frpc/frpc.toml\n'); + expect(unit).toContain('Restart=always\n'); + expect(unit).toContain('StartLimitIntervalSec=0\n'); + expect(unit).toContain('NoNewPrivileges=yes\n'); + expect(unit).not.toContain(CREDENTIAL); + expect(file(parsed, '/usr/local/sbin/sam-wait-tunnel-listener').content).toContain( + 'http://127.0.0.1:8444/health' + ); + }); + + it('uses the control plane port when the URL carries one', () => { + const toml = file( + parse(reverse({ controlPlaneUrl: 'https://api.box.example.org:8443' })), + '/etc/sam/frpc/frpc.toml' + ).content; + expect(toml).toContain('serverPort = 8443\n'); + }); + + it('pins the release tarball checksum for both architectures', () => { + const parsed = parse(reverse()); + const block = parsed.runcmd.find((e) => typeof e === 'string' && e.includes('FRP_SHA256'))!; + expect(block).toContain(`FRP_SHA256=${RELEASE.amd64}`); + expect(block).toContain(`FRP_SHA256=${RELEASE.arm64}`); + expect(block).toContain( + `https://github.com/fatedier/frp/releases/download/v${DEFAULT_FRPC_VERSION}/$FRP_NAME.tar.gz` + ); + }); + + it('stays under the Hetzner limit with production-sized identifiers', () => { + const output = generateCloudInit( + reverse({ + callbackToken: 'c'.repeat(900), + nodeUserId: 'u'.repeat(32), + projectId: 'p'.repeat(26), + chatSessionId: 's'.repeat(36), + taskId: 'k'.repeat(26), + vmAgentRequiredVersion: 'a'.repeat(40), + provider: 'hetzner', + }), + { validateSize: false } + ); + expect(validateCloudInitSize(output)).toBe(true); + }); + + it('control: direct and Cloudflare-tunnel nodes render no frpc at all', () => { + for (const vars of [ + variables({ originCaCertificateUrl: 'https://api.box.example.org/cert' }), + variables({ cloudflareTunnelToken: Buffer.from('x'.repeat(48)).toString('base64') }), + ]) { + const output = generateCloudInit(vars); + expect(output).not.toContain('frpc'); + expect(output).not.toContain('sam-frpc'); + expect(output).not.toContain('SAM_REVERSE_TUNNEL_CREDENTIAL'); + } + }); +}); + +/** Run the whole runcmd script under /bin/sh with the frp tarball served by a curl stub. */ +function runBootScript(vars: CloudInitVariables, env: Record = {}) { + const dir = mkdtempSync(join(tmpdir(), 'sam-reverse-tunnel-test-')); + tempDirs.push(dir); + const bin = join(dir, 'bin'); + const root = join(dir, 'root'); + mkdirSync(bin); + mkdirSync(join(root, 'etc-sam', 'firewall'), { recursive: true }); + mkdirSync(join(root, 'usr-local-bin'), { recursive: true }); + writeFileSync(join(dir, 'calls.log'), ''); + + // A real release-shaped tarball: frp__linux_amd64/frpc + const releaseName = `frp_${DEFAULT_FRPC_VERSION}_linux_amd64`; + mkdirSync(join(dir, 'release', releaseName), { recursive: true }); + writeFileSync(join(dir, 'release', releaseName, 'frpc'), '#!/bin/sh\necho fake-frpc\n'); + writeFileSync(join(dir, 'release', releaseName, 'frps'), 'not-installed'); + spawnSync('tar', ['-czf', join(dir, 'frp.tar.gz'), '-C', join(dir, 'release'), releaseName]); + + const stubs: Record = { + logger: 'cat >/dev/null 2>&1; true', + systemctl: 'case "$*" in *sam-frpc*) exit "${FRPC_UNIT_EXIT:-0}" ;; esac', + chage: 'true', + sysctl: 'true', + uname: 'echo x86_64', + curl: `case "$*" in *fatedier/frp*) [ -z "\${FRP_CURL_EXIT:-}" ] || exit "$FRP_CURL_EXIT" + while [ "$#" -gt 0 ]; do if [ "$1" = -fsSLo ]; then shift; cp "$TEST_DIR/frp.tar.gz" "$1"; fi; shift; done; exit 0 ;; esac +while [ "$#" -gt 0 ]; do if [ "$1" = -fLo ] || [ "$1" = -fsSLo ]; then shift; printf 'binary' > "$1"; fi; shift; done`, + sha256sum: `echo "\${FAKE_SHA:-${RELEASE.amd64}} $1"`, + install: 'true', + id: 'exit 1', + useradd: 'true', + chown: 'true', + 'sam-boot-failure': 'true', + 'sam-configure-docker-memory.sh': 'true', + }; + for (const [name, body] of Object.entries(stubs)) { + writeFileSync( + join(bin, name), + `#!/bin/sh\nprintf '%s %s\\n' "${name}" "$*" >> "$TEST_DIR/calls.log"\n${body}\n`, + { mode: 0o755 } + ); + } + writeFileSync( + join(root, 'etc-sam', 'firewall', 'setup-firewall.sh'), + `#!/bin/sh\nprintf 'firewall\\n' >> "$TEST_DIR/calls.log"\nexit "\${FIREWALL_EXIT:-0}"\n`, + { mode: 0o755 } + ); + const script = parse(vars) + .runcmd.join('\n') + .replaceAll('/usr/local/sbin/', `${bin}/`) + .replaceAll('/usr/local/bin/', `${root}/usr-local-bin/`) + .replaceAll('/etc/sam/', `${root}/etc-sam/`) + .replaceAll('/var/lib/vm-agent', `${root}/var-lib-vm-agent`); + const result = spawnSync('/bin/sh', ['-c', script], { + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, TEST_DIR: dir, ...env }, + encoding: 'utf8', + timeout: 20_000, + }); + return { result, calls: readFileSync(join(dir, 'calls.log'), 'utf8') }; +} + +const lineIndex = (calls: string, needle: string) => + calls.split('\n').findIndex((line) => line.includes(needle)); + +describe('executed reverse-tunnel boot sequence', () => { + it('verifies and extracts frpc, closes ingress, then starts the agent and the connector', () => { + const { result, calls } = runBootScript(reverse()); + expect(result.status).toBe(0); + expect(calls).toMatch( + /install -m 0755 \S+\/frp_0\.72\.0_linux_amd64\/frpc \S+\/usr-local-bin\/frpc/ + ); + expect(calls).toContain('useradd --system --no-create-home --shell /usr/sbin/nologin sam-frpc'); + expect(calls).not.toContain('sam-boot-failure'); + const firewall = lineIndex(calls, 'firewall'); + const agentStart = lineIndex(calls, 'systemctl start vm-agent'); + const connector = lineIndex(calls, 'systemctl enable --now sam-frpc.service'); + expect(firewall).toBeGreaterThan(-1); + expect(agentStart).toBeGreaterThan(firewall); + expect(connector).toBeGreaterThan(agentStart); + expect(result.stdout + result.stderr + calls).not.toContain(CREDENTIAL); + }); + + it.each([ + ['checksum mismatch', { FAKE_SHA: '0'.repeat(64) }, 'frpc_install'], + ['download failure', { FRP_CURL_EXIT: '22' }, 'frpc_install'], + ['firewall failure', { FIREWALL_EXIT: '1' }, 'tunnel_firewall'], + ])('fails closed on %s: reports and never starts the agent or connector', (_n, env, reason) => { + const { result, calls } = runBootScript(reverse(), env); + expect(result.status).toBe(1); + expect(calls).toContain(`sam-boot-failure ${reason}`); + expect(calls).not.toContain('systemctl start vm-agent'); + expect(calls).not.toContain('sam-frpc.service'); + if (reason === 'frpc_install') expect(calls).not.toMatch(/^install /m); + }); + + it('reports a connector that cannot start', () => { + const { result, calls } = runBootScript(reverse(), { FRPC_UNIT_EXIT: '1' }); + expect(result.status).toBe(1); + expect(calls).toContain('sam-boot-failure tunnel_connector'); + }); +}); From a0bb64b279a33729cf4c0efe99215daa48300926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:09:41 +0000 Subject: [PATCH 3/7] docs(cloud-init): document reverse-tunnel ingress; pin two more Cloudflare tunnel shapes Validator follow-ups: security.md no longer ties isTunnelMode to the Cloudflare token only, and gains a reverse-tunnel ingress section; cloud-init AGENTS.md and rule 06 list the frpc blocks. Snapshots for a Cloudflare Tunnel task node and deployment node were recorded against main's cloud-init src (bfa8cc57c) and pass unchanged with L18. Co-Authored-By: Claude Opus 5.5 --- .claude/rules/06-vm-agent-patterns.md | 2 +- .../docs/docs/architecture/security.md | 10 +- packages/cloud-init/AGENTS.md | 1 + .../cloudflare-tunnel-deployment.yaml | 731 ++++++++++++++++++ .../cloudflare-tunnel-task.yaml | 731 ++++++++++++++++++ .../tests/cloudflare-output-snapshot.test.ts | 22 + ...-selfhost-l18-reverse-tunnel-cloud-init.md | 16 +- 7 files changed, 1503 insertions(+), 10 deletions(-) create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-deployment.yaml create mode 100644 packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-task.yaml diff --git a/.claude/rules/06-vm-agent-patterns.md b/.claude/rules/06-vm-agent-patterns.md index d9f60bfb3e..1e489f8c5d 100644 --- a/.claude/rules/06-vm-agent-patterns.md +++ b/.claude/rules/06-vm-agent-patterns.md @@ -58,7 +58,7 @@ Required pattern: 1. Edit `packages/cloud-init/src/template.ts` 2. Update variable types in `src/variables.ts`, validation in `src/validate.ts` and wiring in `src/generate.ts` when needed -3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts` and render only for their mode; keep user-data under the 32 KB Hetzner limit +3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts`, and the self-host reverse-tunnel (frpc) blocks in `src/template-reverse-tunnel.ts`; each renders only for its mode. Keep user-data under the 32 KB Hetzner limit, and keep `tests/cloudflare-output-snapshot.test.ts` passing unchanged when editing shared fragments 4. Test cloud-init generation through the workspace provisioning flow ### Runcmd Interpreter Contract diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index e7d53b100e..341177ff9c 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -323,13 +323,21 @@ Forwarded HTTP and WebSocket applications never receive SAM preview cookies, VM ### Tunnel Ingress Nodes -Cloud-init and the VM agent also support a node that is reachable only through an outbound Cloudflare Tunnel connector. A node is in this mode when cloud-init receives `cloudflareTunnelToken` (`isTunnelMode` in `packages/cloud-init/src/tunnel.ts`). With `VM_AGENT_TRANSPORT=cloudflare-tunnel`, the control plane creates one tunnel per managed VM incarnation, workspace and deployment nodes alike, and journals its ownership before provisioning (`resolveManagedNodeTransport` in `apps/api/src/services/node-tunnel-config.ts`). Direct-ingress nodes and instant-container routing retain their existing transports. On a deployment node the tunnel carries only the VM agent connection: its app routes still reach Caddy on ports 80 and 443 over the public IP, so the firewall leaves those ports open while dropping the agent port, the tunnel listener and SSH. +Cloud-init and the VM agent also support a node that is reachable only through an outbound Cloudflare Tunnel connector. A node is in this mode when cloud-init receives `cloudflareTunnelToken`. With `VM_AGENT_TRANSPORT=cloudflare-tunnel`, the control plane creates one tunnel per managed VM incarnation, workspace and deployment nodes alike, and journals its ownership before provisioning (`resolveManagedNodeTransport` in `apps/api/src/services/node-tunnel-config.ts`). Direct-ingress nodes and instant-container routing retain their existing transports. On a deployment node the tunnel carries only the VM agent connection: its app routes still reach Caddy on ports 80 and 443 over the public IP, so the firewall leaves those ports open while dropping the agent port, the tunnel listener and SSH. - The node receives only its own connector run token, never an account API token. Cloud-init writes it to `/etc/sam/cloudflared/tunnel-token` (mode `0400`, owned by the connector's system user) and skips Origin CA bootstrap entirely (`TUNNEL_BOOTSTRAP_RUNCMD` in `packages/cloud-init/src/template-ingress.ts`). - Cloud-init installs a pinned `cloudflared` release only after its SHA-256 matches the value recorded for that architecture (`CLOUDFLARED_RELEASES` in `packages/cloud-init/src/tunnel.ts`), then applies the firewall before the VM agent starts. In tunnel mode the firewall drops inbound IPv4 and IPv6 traffic to the agent port, the tunnel listener port and SSH, allows Docker bridges to reach the agent port, and does not allowlist Cloudflare IPs. The rules live in a dedicated `SAM-TUNNEL-INGRESS` chain replaced by one `iptables-restore --noflush` transaction per address family (the existing INPUT jump is checked before the restore starts, because the restore holds the xtables lock), so re-applying (daily cron, provisioning, every VM agent start via `ExecStartPre`) never leaves a window without them, and the VM agent does not start if the firewall fails. It fails closed when the host has a global IPv6 address but `ip6tables` is unusable (`TUNNEL_FIREWALL_WRITE_FILE` in `packages/cloud-init/src/template-ingress.ts`). - The VM agent serves the connector on a separate listener bound to `127.0.0.1` (`VM_AGENT_TUNNEL_ENABLED`, `VM_AGENT_TUNNEL_PORT`, default `8444`). Every request on it is classified as relayed before routing (`classifyTunnelIngress` in `packages/vm-agent/internal/server/tunnel_ingress.go`). The connector reaches the agent from loopback, so this classification is what refuses the node-local Git credential helper bearer (see Workspace Git credential exchange below) on the tunnel listener. Tunnel requests use the same JWT, session and callback-token checks as before. - `sam-cloudflared.service` runs as an unprivileged system user and starts only after the tunnel listener answers `/health` (`TUNNEL_WRITE_FILES` in `packages/cloud-init/src/template-ingress.ts`). The tunnel's ingress service must be `http://127.0.0.1:`. The main agent port is never a valid tunnel target. +### Reverse-Tunnel Ingress Nodes (Self-Hosted) + +A self-hosted control plane boots workspace nodes in a third mode, selected when cloud-init receives a non-empty `reverseTunnelCredential` (`isReverseTunnelMode` in `packages/cloud-init/src/reverse-tunnel.ts`; the Cloudflare deployment never sets it). `isTunnelMode` in `packages/cloud-init/src/tunnel.ts` is true for both tunnel modes, because they share the same firewall, the loopback tunnel listener and its classification as relayed traffic, and both skip Origin CA bootstrap. + +- The node receives only its own lease credential, an HMAC derived per lease, node and incarnation (`apps/api/src/selfhost/reverse-tunnel/`). Cloud-init writes it only to `/etc/sam/frpc/credential.env` (mode `0400`, root), which systemd reads into the connector's environment; `frpc.toml` refers to it through frp's environment template and holds no secret. Validation errors never echo it. +- Cloud-init installs a pinned frpc release only after its SHA-256 matches the value recorded for that architecture (`FRPC_RELEASES` in `packages/cloud-init/src/reverse-tunnel.ts`), then applies the tunnel firewall before the VM agent starts. A failed install reports the `frpc_install` boot-failure reason. +- `sam-frpc.service` runs as an unprivileged system user, starts only after the tunnel listener answers, and dials the control-plane host over `wss` on its public HTTPS port, verifying the certificate against the system CA store. It exposes only the tunnel listener, as one TCP proxy on the leased loopback port of the control-plane host (`REVERSE_TUNNEL_WRITE_FILES` in `packages/cloud-init/src/template-reverse-tunnel.ts`). + ### Workspace Git credential exchange Git inside a workspace authenticates through a credential helper that asks the VM agent's local `/git-credential` route for a short-lived repository token; the agent exchanges it with the control plane using the workspace's callback token, which the helper does not carry. A node runs one user's workspaces, which can belong to different projects, so the route must not let one workspace obtain another's token. diff --git a/packages/cloud-init/AGENTS.md b/packages/cloud-init/AGENTS.md index 1635e16f71..a68c26c689 100644 --- a/packages/cloud-init/AGENTS.md +++ b/packages/cloud-init/AGENTS.md @@ -14,6 +14,7 @@ Generates cloud-init YAML templates for VM provisioning. Produces the user-data | `src/variables.ts` / `src/validate.ts` | `CloudInitVariables` and their validation | | `src/template-resources.ts` | Slice hierarchy and Docker headroom write_files, interpolated into the template | | `src/template-ingress.ts` / `src/tunnel.ts` | Ingress-mode blocks (Origin CA direct vs Cloudflare Tunnel) and tunnel validation; each node renders only its own mode | +| `src/reverse-tunnel.ts` / `src/template-reverse-tunnel.ts` | Self-host reverse-tunnel (frpc) mode: validation, pinned release, replacements and connector blocks. Cloudflare nodes never set its variables; `tests/cloudflare-output-snapshot.test.ts` pins their output byte for byte | ## Commands diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-deployment.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-deployment.yaml new file mode 100644 index 0000000000..e31439133b --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-deployment.yaml @@ -0,0 +1,731 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: tunnel-bootstrap"' + - | + case $(uname -m) in + x86_64) CF_ARCH=amd64 CF_SHA256=1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872 ;; + aarch64) CF_ARCH=arm64 CF_SHA256=3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775 ;; + *) CF_ARCH="" ;; + esac + CF_TMP=$(mktemp) + if [ -z "$CF_ARCH" ] || ! curl --max-time 60 -fsSLo "$CF_TMP" "https://github.com/cloudflare/cloudflared/releases/download/2026.10.7/cloudflared-linux-$CF_ARCH" || + [ "$(sha256sum "$CF_TMP" | cut -d' ' -f1)" != "$CF_SHA256" ]; then + rm -f "$CF_TMP" + /usr/local/sbin/sam-boot-failure cloudflared_install + exit 1 + fi + install -m 0755 "$CF_TMP" /usr/local/bin/cloudflared + rm -f "$CF_TMP" + id sam-cloudflared >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-cloudflared + (umask 077; printf '%s' 'eyJhIjoiZml4dHVyZS1hY2NvdW50IiwidCI6ImZpeHR1cmUtdHVubmVsIiwicyI6ImZpeHR1cmUtc2VjcmV0In0=' > /etc/sam/cloudflared/tunnel-token) + chown sam-cloudflared /etc/sam/cloudflared/tunnel-token + chmod 0400 /etc/sam/cloudflared/tunnel-token + if ! /etc/sam/firewall/setup-firewall.sh; then + /usr/local/sbin/sam-boot-failure tunnel_firewall + exit 1 + fi + logger -t sam-boot "cloudflared installed (sha256 verified); public agent/SSH ingress closed" + - 'logger -t sam-boot "PHASE END: tunnel-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + - 'logger -t sam-boot "PHASE START: tunnel-connector"' + - | + if ! systemctl enable --now sam-cloudflared.service; then + /usr/local/sbin/sam-boot-failure tunnel_connector + exit 1 + fi + - 'logger -t sam-boot "PHASE END: tunnel-connector"' + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="deployment" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID= + Environment=CHAT_SESSION_ID= + Environment=TASK_ID= + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8080 + Environment=VM_AGENT_TUNNEL_ENABLED=true + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH= + Environment=TLS_KEY_PATH= + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE=deployment + Environment=NODE_ROLE=deployment + Environment=ENVIRONMENT_ID=env-snapshot + Environment=DEPLOY_SIGNING_PUB_KEY=PUBKEY-SNAPSHOT + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + ExecStartPre=/etc/sam/firewall/setup-firewall.sh + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + - path: /usr/local/sbin/sam-wait-tunnel-listener + permissions: '0755' + content: | + #!/bin/sh + # Expose nothing until the vm-agent's loopback tunnel listener answers, + # giving up after an elapsed-time deadline (not an attempt count). + deadline=$(($(date +%s) + 120)) + until curl -fsS --max-time 2 -o /dev/null "http://127.0.0.1:8444/health"; do + if [ "$(date +%s)" -ge "$deadline" ]; then + logger -t sam-tunnel "tunnel listener 127.0.0.1:8444 not ready" + exit 1 + fi + sleep 1 + done + + - path: /etc/systemd/system/sam-cloudflared.service + permissions: '0644' + content: | + [Unit] + Description=SAM Cloudflare Tunnel connector + After=network-online.target vm-agent.service + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + User=sam-cloudflared + ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener + ExecStart=/usr/local/bin/cloudflared tunnel --no-autoupdate run --token-file /etc/sam/cloudflared/tunnel-token + TimeoutStartSec=infinity + Restart=always + RestartSec=5 + Slice=sam-infra.slice + NoNewPrivileges=yes + ProtectSystem=strict + ProtectHome=yes + PrivateTmp=yes + PrivateDevices=yes + ProtectKernelTunables=yes + ProtectKernelModules=yes + ProtectControlGroups=yes + ProtectClock=yes + ProtectHostname=yes + RestrictSUIDSGID=yes + RestrictRealtime=yes + LockPersonality=yes + RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK + CapabilityBoundingSet= + + [Install] + WantedBy=multi-user.target + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM tunnel-node firewall: no public ingress to the VM agent, its loopback + # tunnel listener, or SSH, on IPv4 and IPv6. Docker bridges may reach the + # agent port (Git credential helper). Egress and INPUT policy are untouched. + # The rules live in one chain replaced by a single iptables-restore + # transaction, so a re-run (cron, provisioning, every vm-agent start) + # never opens a gap. + set -euo pipefail + VM_AGENT_PORT="8080" + TUNNEL_PORT="8444" + CHAIN=SAM-TUNNEL-INGRESS + # Whether the INPUT jump exists is decided BEFORE iptables-restore starts. The restore + # holds the xtables lock while it reads stdin, so an iptables call inside the producer + # below would wait on that lock forever under iptables-legacy. + # -w waits for the lock instead of misreading contention as "absent" (a duplicate jump). + jump_state() { if "$1" -C INPUT -j "$CHAIN" -w 2>/dev/null; then echo present; else echo absent; fi; } + rules() { + echo '*filter' + echo ":$CHAIN - [0:0]" + [ "$2" = present ] || echo "-I INPUT 1 -j $CHAIN" + echo "-A $CHAIN -i lo -j RETURN" + echo "-A $CHAIN -i docker0 -p tcp --dport $VM_AGENT_PORT -j RETURN" + echo "-A $CHAIN -i br-+ -p tcp --dport $VM_AGENT_PORT -j RETURN" + for port in "$VM_AGENT_PORT" "$TUNNEL_PORT"; do + echo "-A $CHAIN -p tcp --dport $port -j DROP" + echo "-A $CHAIN -p udp --dport $port -j DROP" + done + echo "-A $CHAIN -p tcp --dport 22 -j DROP" + echo COMMIT + } + jump_v4=$(jump_state iptables) + rules iptables "$jump_v4" | iptables-restore --noflush + # Usability of ip6tables, not modprobe, decides: the module may be built in. + modprobe ip6_tables 2>/dev/null || true + if ip6tables -L -n >/dev/null 2>&1; then + jump_v6=$(jump_state ip6tables) + rules ip6tables "$jump_v6" | ip6tables-restore --noflush + elif [ -n "$(ip -6 addr show scope global 2>/dev/null)" ]; then + # Go serves 0.0.0.0 dual-stack: global IPv6 without ip6tables is exposure. + logger -t sam-firewall "ERROR: ip6tables unavailable on a tunnel node with global IPv6; refusing" + exit 1 + fi + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + logger -t sam-firewall "Firewall configured: tunnel node, no public agent/SSH ingress" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-task.yaml b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-task.yaml new file mode 100644 index 0000000000..0f35c0afed --- /dev/null +++ b/packages/cloud-init/tests/__snapshots__/cloudflare-output/cloudflare-tunnel-task.yaml @@ -0,0 +1,731 @@ +#cloud-config + +# Skip default apt-get update/upgrade — the vm-agent handles package installs. +# Without this, cloud-init blocks runcmd for 5-10 min on apt operations. +package_update: false +package_upgrade: false + +hostname: node-01snapshotnode0000000000000 + +users: + - name: workspace + shell: /bin/bash + sudo: ALL=(ALL) NOPASSWD:ALL + +runcmd: + # ===================================================================== + # Cloud-init keeps bootstrap minimal: download vm-agent, perform + # start vm-agent, then perform role-specific service setup required before + # traffic can be served. The agent handles Docker, firewall, Node.js, release + # apply, and heartbeats; release apply remains retryable while role-specific + # dependencies are still converging. + # ===================================================================== + + # Disable automatic OS upgrades — ephemeral VMs gain nothing from them + # and unattended-upgrades can trigger systemd daemon-reexec which kills + # the vm-agent mid-work. Must run before vm-agent starts. + - systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true + - systemctl disable --now unattended-upgrades || true + - chage -E -1 -M -1 -d "$(date +%Y-%m-%d)" root || true + + - 'logger -t sam-boot "PHASE START: swap-setup"' + - | + SWAP_SIZE_MB="2048" + SWAP_SWAPPINESS="60" + if [ "$SWAP_SIZE_MB" -gt 0 ] 2>/dev/null; then + logger -t sam-boot "Configuring ${SWAP_SIZE_MB}MB swap file" + fallocate -l "${SWAP_SIZE_MB}M" /swapfile + chmod 600 /swapfile + mkswap /swapfile + swapon /swapfile + echo '/swapfile none swap sw 0 0' >> /etc/fstab + sysctl -w "vm.swappiness=${SWAP_SWAPPINESS}" + logger -t sam-boot "Swap configured: ${SWAP_SIZE_MB}MB, swappiness=${SWAP_SWAPPINESS}" + else + logger -t sam-boot "Swap disabled (SWAP_SIZE_MB=0)" + fi + - 'logger -t sam-boot "PHASE END: swap-setup"' + + - 'logger -t sam-boot "PHASE START: vm-agent-download"' + - mkdir -p /var/lib/vm-agent /etc/sam/tls /etc/sam/firewall /etc/sam/cloudflared + - | + ARCH=$(uname -m) + case $ARCH in + x86_64) ARCH="amd64" ;; + aarch64) ARCH="arm64" ;; + esac + logger -t sam-boot "Downloading vm-agent for arch=$ARCH" + curl_output=$(mktemp) + if curl --max-time 60 -fLo /usr/local/bin/vm-agent "https://api.example.com/api/agent/download?arch=${ARCH}&release=0123456789abcdef0123456789abcdef01234567" >"$curl_output" 2>&1; then + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + else + curl_status=$? + cat "$curl_output" | logger -t sam-boot + rm -f "$curl_output" + logger -t sam-boot "vm-agent download failed status=$curl_status" + /usr/local/sbin/sam-boot-failure vm_agent_download + exit "$curl_status" + fi + chmod +x /usr/local/bin/vm-agent + logger -t sam-boot "vm-agent binary downloaded, size=$(stat -c%s /usr/local/bin/vm-agent 2>/dev/null || echo unknown)" + - 'logger -t sam-boot "PHASE END: vm-agent-download"' + + - 'logger -t sam-boot "PHASE START: tunnel-bootstrap"' + - | + case $(uname -m) in + x86_64) CF_ARCH=amd64 CF_SHA256=1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872 ;; + aarch64) CF_ARCH=arm64 CF_SHA256=3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775 ;; + *) CF_ARCH="" ;; + esac + CF_TMP=$(mktemp) + if [ -z "$CF_ARCH" ] || ! curl --max-time 60 -fsSLo "$CF_TMP" "https://github.com/cloudflare/cloudflared/releases/download/2026.10.7/cloudflared-linux-$CF_ARCH" || + [ "$(sha256sum "$CF_TMP" | cut -d' ' -f1)" != "$CF_SHA256" ]; then + rm -f "$CF_TMP" + /usr/local/sbin/sam-boot-failure cloudflared_install + exit 1 + fi + install -m 0755 "$CF_TMP" /usr/local/bin/cloudflared + rm -f "$CF_TMP" + id sam-cloudflared >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-cloudflared + (umask 077; printf '%s' 'eyJhIjoiZml4dHVyZS1hY2NvdW50IiwidCI6ImZpeHR1cmUtdHVubmVsIiwicyI6ImZpeHR1cmUtc2VjcmV0In0=' > /etc/sam/cloudflared/tunnel-token) + chown sam-cloudflared /etc/sam/cloudflared/tunnel-token + chmod 0400 /etc/sam/cloudflared/tunnel-token + if ! /etc/sam/firewall/setup-firewall.sh; then + /usr/local/sbin/sam-boot-failure tunnel_firewall + exit 1 + fi + logger -t sam-boot "cloudflared installed (sha256 verified); public agent/SSH ingress closed" + - 'logger -t sam-boot "PHASE END: tunnel-bootstrap"' + + - 'logger -t sam-boot "PHASE START: resource-headroom"' + - /usr/local/sbin/sam-configure-docker-memory.sh || exit $? + - 'logger -t sam-boot "PHASE END: resource-headroom"' + + - 'logger -t sam-boot "PHASE START: vm-agent-start"' + - systemctl daemon-reload + - systemctl enable vm-agent + - systemctl start vm-agent + - 'logger -t sam-boot "PHASE END: vm-agent-start"' + + - 'logger -t sam-boot "PHASE START: tunnel-connector"' + - | + if ! systemctl enable --now sam-cloudflared.service; then + /usr/local/sbin/sam-boot-failure tunnel_connector + exit 1 + fi + - 'logger -t sam-boot "PHASE END: tunnel-connector"' + + - 'logger -t sam-boot "PHASE START: caddy-setup"' + - | + set -eu + ROLE="" + if [ "$ROLE" = "deployment" ]; then + logger -t sam-boot "Preparing Caddy paths for deployment node routing" + mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy + logger -t sam-boot "Caddy paths ready; vm-agent owns Caddy install/start" + else + logger -t sam-boot "Skipping Caddy setup for ROLE=$ROLE" + fi + - 'logger -t sam-boot "PHASE END: caddy-setup"' + - 'logger -t sam-boot "ALL PHASES COMPLETE"' + +write_files: + - path: /etc/systemd/system/vm-agent.service + permissions: '0644' + content: | + [Unit] + Description=VM Agent + After=network.target + + [Service] + Type=simple + User=root + Environment=NODE_ID=01SNAPSHOTNODE0000000000000 + Environment=NODE_USER_ID=user-snapshot + Environment=NODE_RUNTIME_INCARNATION_ID=incarnation-snapshot + Environment=CONTROL_PLANE_URL=https://api.example.com + Environment=JWKS_ENDPOINT=https://api.example.com/.well-known/jwks.json + Environment=CALLBACK_TOKEN_FILE=/etc/sam/callback-token + Environment=PROJECT_ID=project-snapshot + Environment=CHAT_SESSION_ID=session-snapshot + Environment=TASK_ID=task-snapshot + Environment=TASK_MODE=task + Environment=VM_AGENT_PORT=8080 + Environment=VM_AGENT_TUNNEL_ENABLED=true + Environment=VM_AGENT_TUNNEL_PORT=8444 + Environment=TLS_CERT_PATH= + Environment=TLS_KEY_PATH= + Environment=PROVIDER=hetzner + Environment=DEVCONTAINER_CACHE_ENABLED=false + Environment=WORKSPACE_BUILD_QUEUE_DEPTH=1 + Environment=ROLE= + Environment=NODE_ROLE= + Environment=ENVIRONMENT_ID= + Environment=DEPLOY_SIGNING_PUB_KEY= + Environment=DEPLOY_ACME_EMAIL= + Environment=DEPLOY_ACME_CA= + Environment="DEPLOY_COMPOSE_CMD=" + Environment=DEPLOY_HEALTH_TIMEOUT= + Environment=SESSION_SNAPSHOT_OPERATION_TIMEOUT=15m + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL=15s + Environment=SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT=5s + Environment=ERROR_REPORT_FLUSH_INTERVAL=30s + Environment=ERROR_REPORT_MAX_BATCH_SIZE=10 + Environment=ERROR_REPORT_MAX_BATCH_BYTES=32768 + Environment=ERROR_REPORT_MAX_QUEUE_SIZE=1000 + Environment=ERROR_REPORT_HTTP_TIMEOUT=10s + Environment=ERROR_REPORT_RETRY_INITIAL=1s + Environment=ERROR_REPORT_RETRY_MAX=5m + Environment=ERROR_REPORT_MAX_ATTEMPTS=20 + Environment=ERROR_REPORT_DB_PATH=/var/lib/vm-agent/error-reports.db + Environment=ERROR_REPORT_DB_BUSY_TIMEOUT=5s + Environment=ERROR_REPORT_SPOOL_DIR=/var/lib/vm-agent/diagnostic-incidents + Environment=ERROR_REPORT_ARTIFACT_MAX_BYTES=2097152 + Environment=ERROR_REPORT_SPOOL_MAX_BYTES=20971520 + Environment=ERROR_REPORT_RETENTION=24h + Environment=ERROR_REPORT_COLLECTOR_TIMEOUT=10s + Environment=ERROR_REPORT_MAX_COLLECTOR_DOCS=8 + Environment=ERROR_REPORT_MAX_DOCUMENT_BYTES=131072 + Environment=ERROR_REPORT_MAX_VALUE_DEPTH=8 + Environment=ERROR_REPORT_MAX_VALUE_ITEMS=256 + Environment=ERROR_REPORT_MAX_STRING_BYTES=4096 + Environment=ERROR_REPORT_EVENT_LIMIT=100 + Environment=ERROR_REPORT_RESPONSE_MAX_BYTES=4096 + Environment=ERROR_REPORT_STORED_ERROR_MAX_BYTES=512 + Environment=ERROR_REPORT_COLLECTOR_CONCURRENCY=1 + Environment=HEARTBEAT_DOCKER_STATS_TIMEOUT=2s + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS=8 + Environment=HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES=65536 + Slice=sam-infra.slice + MemoryAccounting=yes + OOMScoreAdjust=-900 + ExecStartPre=/etc/sam/firewall/setup-firewall.sh + ExecStart=/usr/local/bin/vm-agent + Restart=always + RestartSec=5 + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/system/sam.slice + permissions: '0644' + content: | + [Unit] + Description=SAM managed services and workload hierarchy + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + + - path: /etc/systemd/system/sam-infra.slice + permissions: '0644' + content: | + [Unit] + Description=SAM infrastructure services + Before=slices.target + + [Slice] + MemoryAccounting=yes + MemoryMin=256M + CPUAccounting=yes + CPUWeight=1000 + + - path: /etc/systemd/system/sam-workload.slice + permissions: '0644' + content: | + [Unit] + Description=SAM Docker workload containers + Before=slices.target + + [Slice] + MemoryAccounting=yes + CPUAccounting=yes + CPUWeight=100 + + - path: /usr/local/sbin/sam-configure-docker-memory.sh + permissions: '0755' + content: | + #!/bin/sh + set -eu + + RESERVE_MB="1024" + SYSTEMD_SYSTEM_DIR="${SAM_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" + if [ "$RESERVE_MB" = "0" ]; then + rm -f "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" + systemctl daemon-reload + logger -t sam-headroom "SAM workload MemoryMax reserve disabled" + exit 0 + fi + + MIN_DOCKER_MB="512" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + logger -t sam-headroom "Cannot determine host memory from $PROC_MEMINFO" + exit 78 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + logger -t sam-headroom "Refusing to run without SAM workload MemoryMax: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" + exit 78 + fi + + mkdir -p "$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d" + cat >"$SYSTEMD_SYSTEM_DIR/sam-workload.slice.d/50-headroom.conf" <" >&2 + exit 64 + fi + + RESERVE_MB="1024" + INFRA_MIN_MB="256" + MIN_DOCKER_MB="512" + INFRA_CPU_WEIGHT_EXPECTED="1000" + WORKLOAD_CPU_WEIGHT_EXPECTED="100" + PROC_ROOT="${SAM_PROC_ROOT:-/proc}" + CGROUP_ROOT="${SAM_CGROUP_ROOT:-/sys/fs/cgroup}" + PROC_MEMINFO="${SAM_PROC_MEMINFO:-/proc/meminfo}" + + PID="$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_ID")" + if [ -z "$PID" ] || [ "$PID" = "0" ]; then + echo "container $CONTAINER_ID is not running" >&2 + exit 65 + fi + + CGROUP_FILE="$PROC_ROOT/$PID/cgroup" + if [ ! -r "$CGROUP_FILE" ]; then + echo "cannot read cgroup for container $CONTAINER_ID pid $PID at $CGROUP_FILE" >&2 + exit 66 + fi + + CGROUP="$(cat "$CGROUP_FILE")" + CGROUP_PATH="$(awk -F: '$1 == "0" && $2 == "" { print $3; found = 1 } END { if (!found) exit 1 }' "$CGROUP_FILE")" || { + echo "container $CONTAINER_ID pid $PID has no cgroup v2 entry" >&2 + echo "$CGROUP" >&2 + exit 66 + } + + find_cgroup_ancestor() { + target="$1" + path="$2" + while [ "$path" != "/" ] && [ "$path" != "." ] && [ -n "$path" ]; do + if [ "$(basename "$path")" = "$target" ]; then + printf '%s\n' "$path" + return 0 + fi + path="$(dirname "$path")" + done + return 1 + } + + SAM_CGROUP="$(find_cgroup_ancestor sam.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + WORKLOAD_CGROUP="$(find_cgroup_ancestor sam-workload.slice "$CGROUP_PATH")" || { + echo "container $CONTAINER_ID pid $PID is outside sam-workload.slice" >&2 + echo "$CGROUP" >&2 + exit 66 + } + if [ "$SAM_CGROUP" != "/sam.slice" ] || [ "$WORKLOAD_CGROUP" != "/sam.slice/sam-workload.slice" ]; then + echo "container $CONTAINER_ID pid $PID has unexpected SAM cgroup ancestry: $CGROUP_PATH" >&2 + exit 66 + fi + + read_cgroup_value() { + name="$1" + rel_path="$2" + file="$CGROUP_ROOT$rel_path/$name" + if [ ! -r "$file" ]; then + echo "missing cgroup $name at $file" >&2 + exit 67 + fi + tr -d '\n' < "$file" + } + + require_bytes_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -ne "$expected" ]; then + echo "$name expected $expected bytes, got $actual" >&2 + exit 67 + fi + } + + require_bytes_at_least() { + name="$1" + actual="$2" + minimum="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" -lt "$minimum" ]; then + echo "$name expected at least $minimum bytes, got $actual" >&2 + exit 67 + fi + } + + require_int_equal() { + name="$1" + actual="$2" + expected="$3" + case "$actual" in + ''|*[!0-9]*) + echo "$name is not an integer: $actual" >&2 + exit 67 + ;; + esac + if [ "$actual" != "$expected" ]; then + echo "$name expected $expected, got $actual" >&2 + exit 67 + fi + } + + prop_value() { + props="$1" + key="$2" + printf '%s\n' "$props" | awk -F= -v key="$key" '$1 == key { print $2; found = 1; exit } END { if (!found) exit 1 }' + } + + # CPU weights are verified BEFORE the memory-reserve early return on + # purpose: disabling the memory reserve must not silently disable the CPU + # check too. Memory starvation kills the agent and CPU starvation only + # delays its heartbeat, but a delayed heartbeat is what gets a healthy node + # declared dead, so both are load-bearing. + INFRA_CPU_WEIGHT="$(read_cgroup_value cpu.weight /sam.slice/sam-infra.slice)" + WORKLOAD_CPU_WEIGHT="$(read_cgroup_value cpu.weight "$WORKLOAD_CGROUP")" + require_int_equal "sam-infra.slice cgroup cpu.weight" "$INFRA_CPU_WEIGHT" "$INFRA_CPU_WEIGHT_EXPECTED" + require_int_equal "sam-workload.slice cgroup cpu.weight" "$WORKLOAD_CPU_WEIGHT" "$WORKLOAD_CPU_WEIGHT_EXPECTED" + if [ "$INFRA_CPU_WEIGHT" -le "$WORKLOAD_CPU_WEIGHT" ]; then + echo "vm-agent slice cpu.weight $INFRA_CPU_WEIGHT does not outrank workload $WORKLOAD_CPU_WEIGHT" >&2 + exit 67 + fi + + if [ "$RESERVE_MB" = "0" ]; then + echo "SAM workload MemoryMax reserve disabled; verified cgroup ancestry and CPU weights only" + systemctl show sam.slice sam-infra.slice sam-workload.slice -p MemoryMin -p MemoryMax -p EffectiveMemoryMax -p CPUWeight --no-pager + echo "$CGROUP" + exit 0 + fi + + TOTAL_KB="$(awk '/MemTotal:/ { print $2; exit }' "$PROC_MEMINFO")" + case "$TOTAL_KB" in + ''|*[!0-9]*) + echo "cannot determine host memory from $PROC_MEMINFO" >&2 + exit 67 + ;; + esac + TOTAL_MB="$((TOTAL_KB / 1024))" + DOCKER_MEMORY_MAX_MB="$((TOTAL_MB - RESERVE_MB))" + if [ "$DOCKER_MEMORY_MAX_MB" -lt "$MIN_DOCKER_MB" ]; then + echo "SAM workload MemoryMax is not enforceable: total=${TOTAL_MB}M reserve=${RESERVE_MB}M leaves ${DOCKER_MEMORY_MAX_MB}M below minimum ${MIN_DOCKER_MB}M" >&2 + exit 67 + fi + + EXPECTED_WORKLOAD_MAX_BYTES="$((DOCKER_MEMORY_MAX_MB * 1024 * 1024))" + EXPECTED_INFRA_MIN_BYTES="$((INFRA_MIN_MB * 1024 * 1024))" + WORKLOAD_MEMORY_MAX="$(read_cgroup_value memory.max "$WORKLOAD_CGROUP")" + SAM_MEMORY_MIN="$(read_cgroup_value memory.min "$SAM_CGROUP")" + INFRA_MEMORY_MIN="$(read_cgroup_value memory.min /sam.slice/sam-infra.slice)" + + require_bytes_equal "sam-workload.slice cgroup memory.max" "$WORKLOAD_MEMORY_MAX" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice cgroup memory.min" "$SAM_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice cgroup memory.min" "$INFRA_MEMORY_MIN" "$EXPECTED_INFRA_MIN_BYTES" + + WORKLOAD_PROPS="$(systemctl show sam-workload.slice -p MemoryMax -p EffectiveMemoryMax --no-pager)" + SAM_PROPS="$(systemctl show sam.slice -p MemoryMin --no-pager)" + INFRA_PROPS="$(systemctl show sam-infra.slice -p MemoryMin --no-pager)" + + require_bytes_equal "sam-workload.slice MemoryMax" "$(prop_value "$WORKLOAD_PROPS" MemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_equal "sam-workload.slice EffectiveMemoryMax" "$(prop_value "$WORKLOAD_PROPS" EffectiveMemoryMax)" "$EXPECTED_WORKLOAD_MAX_BYTES" + require_bytes_at_least "sam.slice MemoryMin" "$(prop_value "$SAM_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + require_bytes_at_least "sam-infra.slice MemoryMin" "$(prop_value "$INFRA_PROPS" MemoryMin)" "$EXPECTED_INFRA_MIN_BYTES" + + printf '%s\n' "$SAM_PROPS" "$INFRA_PROPS" "$WORKLOAD_PROPS" + echo "$CGROUP" + + - path: /etc/caddy/Caddyfile + permissions: '0644' + content: | + # Managed by SAM deployment agent. + # Release applies replace this file and run caddy reload. + { + auto_https off + } + + :80 { + respond "SAM deployment node awaiting release" 200 + } + + - path: /etc/sam/callback-token + permissions: '0600' + owner: root:root + content: | + CALLBACK-SNAPSHOT + + - path: /usr/local/sbin/sam-boot-failure + permissions: '0700' + content: | + #!/bin/sh + # Best-effort boot failure report while the vm-agent is not running yet. + # Reads the token file so the callback token is not repeated in user-data. + logger -t sam-boot "ERROR: boot failed reason=$1" + curl -sS --max-time 45 -o /dev/null -X POST \ + -H "Authorization: Bearer $(cat /etc/sam/callback-token)" \ + -H "Content-Type: application/json" --data "{\"reason\":\"$1\"}" \ + "https://api.example.com/api/nodes/01SNAPSHOTNODE0000000000000/boot-failure" 2>/dev/null || true + + - path: /usr/local/sbin/sam-wait-tunnel-listener + permissions: '0755' + content: | + #!/bin/sh + # Expose nothing until the vm-agent's loopback tunnel listener answers, + # giving up after an elapsed-time deadline (not an attempt count). + deadline=$(($(date +%s) + 120)) + until curl -fsS --max-time 2 -o /dev/null "http://127.0.0.1:8444/health"; do + if [ "$(date +%s)" -ge "$deadline" ]; then + logger -t sam-tunnel "tunnel listener 127.0.0.1:8444 not ready" + exit 1 + fi + sleep 1 + done + + - path: /etc/systemd/system/sam-cloudflared.service + permissions: '0644' + content: | + [Unit] + Description=SAM Cloudflare Tunnel connector + After=network-online.target vm-agent.service + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + User=sam-cloudflared + ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener + ExecStart=/usr/local/bin/cloudflared tunnel --no-autoupdate run --token-file /etc/sam/cloudflared/tunnel-token + TimeoutStartSec=infinity + Restart=always + RestartSec=5 + Slice=sam-infra.slice + NoNewPrivileges=yes + ProtectSystem=strict + ProtectHome=yes + PrivateTmp=yes + PrivateDevices=yes + ProtectKernelTunables=yes + ProtectKernelModules=yes + ProtectControlGroups=yes + ProtectClock=yes + ProtectHostname=yes + RestrictSUIDSGID=yes + RestrictRealtime=yes + LockPersonality=yes + RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK + CapabilityBoundingSet= + + [Install] + WantedBy=multi-user.target + + - path: /etc/workspace/config.json + content: | + { + "node_id": "01SNAPSHOTNODE0000000000000", + "control_plane_url": "https://api.example.com" + } + permissions: '0644' + + - path: /etc/sam/firewall/setup-firewall.sh + permissions: '0755' + content: | + #!/bin/bash + # SAM tunnel-node firewall: no public ingress to the VM agent, its loopback + # tunnel listener, or SSH, on IPv4 and IPv6. Docker bridges may reach the + # agent port (Git credential helper). Egress and INPUT policy are untouched. + # The rules live in one chain replaced by a single iptables-restore + # transaction, so a re-run (cron, provisioning, every vm-agent start) + # never opens a gap. + set -euo pipefail + VM_AGENT_PORT="8080" + TUNNEL_PORT="8444" + CHAIN=SAM-TUNNEL-INGRESS + # Whether the INPUT jump exists is decided BEFORE iptables-restore starts. The restore + # holds the xtables lock while it reads stdin, so an iptables call inside the producer + # below would wait on that lock forever under iptables-legacy. + # -w waits for the lock instead of misreading contention as "absent" (a duplicate jump). + jump_state() { if "$1" -C INPUT -j "$CHAIN" -w 2>/dev/null; then echo present; else echo absent; fi; } + rules() { + echo '*filter' + echo ":$CHAIN - [0:0]" + [ "$2" = present ] || echo "-I INPUT 1 -j $CHAIN" + echo "-A $CHAIN -i lo -j RETURN" + echo "-A $CHAIN -i docker0 -p tcp --dport $VM_AGENT_PORT -j RETURN" + echo "-A $CHAIN -i br-+ -p tcp --dport $VM_AGENT_PORT -j RETURN" + for port in "$VM_AGENT_PORT" "$TUNNEL_PORT"; do + echo "-A $CHAIN -p tcp --dport $port -j DROP" + echo "-A $CHAIN -p udp --dport $port -j DROP" + done + echo "-A $CHAIN -p tcp --dport 22 -j DROP" + echo COMMIT + } + jump_v4=$(jump_state iptables) + rules iptables "$jump_v4" | iptables-restore --noflush + # Usability of ip6tables, not modprobe, decides: the module may be built in. + modprobe ip6_tables 2>/dev/null || true + if ip6tables -L -n >/dev/null 2>&1; then + jump_v6=$(jump_state ip6tables) + rules ip6tables "$jump_v6" | ip6tables-restore --noflush + elif [ -n "$(ip -6 addr show scope global 2>/dev/null)" ]; then + # Go serves 0.0.0.0 dual-stack: global IPv6 without ip6tables is exposure. + logger -t sam-firewall "ERROR: ip6tables unavailable on a tunnel node with global IPv6; refusing" + exit 1 + fi + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true + logger -t sam-firewall "Firewall configured: tunnel node, no public agent/SSH ingress" + + - path: /etc/iptables/rules.v4 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/iptables/rules.v6 + permissions: '0644' + content: | + *filter + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + COMMIT + + - path: /etc/cron.daily/update-cloudflare-firewall + permissions: '0755' + content: | + #!/bin/bash + /etc/sam/firewall/setup-firewall.sh 2>&1 | logger -t sam-firewall-update + + - path: /etc/sam/firewall/apply-metadata-block.sh + permissions: '0755' + content: | + #!/bin/bash + set -euo pipefail + METADATA_IP="169.254.169.254" + if iptables -L DOCKER-USER -n >/dev/null 2>&1; then + iptables -D DOCKER-USER -d "$METADATA_IP" -j DROP 2>/dev/null || true + iptables -I DOCKER-USER 1 -d "$METADATA_IP" -j DROP + logger -t sam-firewall "Metadata API blocked for containers (DOCKER-USER chain)" + else + logger -t sam-firewall "WARNING: DOCKER-USER chain not found, cannot block metadata API" + fi + + - path: /etc/systemd/system/sam-metadata-block.service + permissions: '0644' + content: | + [Unit] + Description=SAM metadata API block for Docker containers + After=docker.service + Requires=docker.service + PartOf=docker.service + + [Service] + Type=oneshot + ExecStart=/etc/sam/firewall/apply-metadata-block.sh + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + + - path: /etc/systemd/journald.conf.d/sam.conf + content: | + [Journal] + Storage=persistent + Compress=yes + SystemMaxUse=500M + SystemKeepFree=1G + MaxRetentionSec=7day + permissions: '0644' + + - path: /etc/sysctl.d/99-sam-swap.conf + content: | + vm.swappiness=60 + permissions: '0644' + + - path: /etc/docker/daemon.json + content: | + { + "log-driver": "journald", + "log-opts": { + "tag": "docker/{{.Name}}" + }, + "cgroup-parent": "sam-workload.slice", + "dns": ["1.1.1.1", "8.8.8.8"], + "live-restore": true + } + permissions: '0644' + + - path: /etc/apt/apt.conf.d/80-retries + content: | + Acquire::Retries "3"; + Acquire::http::Timeout "30"; + Acquire::https::Timeout "30"; + permissions: '0644' + + - path: /etc/sam/apt-mirror-config.sh + permissions: '0755' + content: | + #!/bin/bash + # Provider-specific apt mirror configuration for Docker containers. + # Sourced by the VM agent bootstrap to inject fast mirrors into containers. + # Only overrides for providers with known fast local mirrors. + PROVIDER="hetzner" + case "$PROVIDER" in + hetzner) + APT_MIRROR="mirror.hetzner.com" + ;; + *) + APT_MIRROR="" + ;; + esac + export APT_MIRROR + +final_message: "Simple Agent Manager node 01SNAPSHOTNODE0000000000000 provisioning started!" diff --git a/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts b/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts index 8acbff6d9a..8cf678bf41 100644 --- a/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts +++ b/packages/cloud-init/tests/cloudflare-output-snapshot.test.ts @@ -64,6 +64,28 @@ const cases: Array<[string, CloudInitVariables]> = [ ['direct-minimal', { ...base }], // Cloudflare Tunnel with every tunnel tunable left at its default. ['cloudflare-tunnel-defaults', { ...base, cloudflareTunnelToken: TUNNEL_TOKEN }], + // Cloudflare Tunnel on a task node and on a deployment node (#2646 gives both the tunnel). + [ + 'cloudflare-tunnel-task', + { + ...base, + cloudflareTunnelToken: TUNNEL_TOKEN, + projectId: 'project-snapshot', + chatSessionId: 'session-snapshot', + taskId: 'task-snapshot', + taskMode: 'task', + }, + ], + [ + 'cloudflare-tunnel-deployment', + { + ...base, + cloudflareTunnelToken: TUNNEL_TOKEN, + role: 'deployment', + environmentId: 'env-snapshot', + deploySigningPubKey: 'PUBKEY-SNAPSHOT', + }, + ], // Cloudflare Tunnel as provisioning renders it with explicit port and timings. [ 'cloudflare-tunnel-configured', diff --git a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md index fcb345c45b..b7b74833b4 100644 --- a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md +++ b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md @@ -39,17 +39,17 @@ SAM task 01M7QB46M5C4GE1Z51D1ZNEBGJ; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; pla ## Checklist - [x] Record Cloudflare output snapshots (direct Origin CA default, task, deployment, minimal, - Cloudflare Tunnel defaults and configured) from main BEFORE the change -- [ ] Bring the L18 cloud-init files from `origin/sam/selfhost-pass-2`; confirm byte-identity + Cloudflare Tunnel defaults, task, deployment and configured) from main's cloud-init src +- [x] Bring the L18 cloud-init files from `origin/sam/selfhost-pass-2`; confirm byte-identity (`git diff origin/sam/selfhost-pass-2 -- ` empty) -- [ ] Add `frpc_install` to the boot-failure picklist + route test -- [ ] Snapshot test passes unchanged after the change (byte-identical Cloudflare output) -- [ ] Reverse-tunnel tests (render, validation, executed runcmd under /bin/sh) pass -- [ ] API reverse-tunnel tests that render through `installReverseTunnelTransport(generateCloudInit)` +- [x] Add `frpc_install` to the boot-failure picklist + route test +- [x] Snapshot test passes unchanged after the change (byte-identical Cloudflare output) +- [x] Reverse-tunnel tests (render, validation, executed runcmd under /bin/sh) pass +- [x] API reverse-tunnel tests that render through `installReverseTunnelTransport(generateCloudInit)` pass against the new renderer -- [ ] Docs: check public docs for boot-failure reasons / cloud-init ingress modes +- [x] Docs: self-hosting.mdx (boot mode), security.md (reverse-tunnel ingress; `isTunnelMode` now covers both tunnel modes), packages/cloud-init/AGENTS.md, rule 06 cloud-init step - [ ] lint, typecheck, test, build -- [ ] security-auditor, task-completion-validator +- [ ] security-auditor, task-completion-validator (validator: WARN, no CRITICAL/HIGH; doc-sync, checklist and two extra snapshot cases addressed) - [ ] BOX proof (byte-identical to integration tip: cite BOX run 01M7QB382PDGH42XEG3ZFFS6DE) - [ ] Staging: real VM node provisioning with heartbeat, then cleanup From 9c9045694a375b1cfac44a1e85a5f6e9c075c9bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:10:10 +0000 Subject: [PATCH 4/7] task: record L18 review outcomes; defer security LOWs to backlog Co-Authored-By: Claude Opus 5.5 --- ...-selfhost-l18-reverse-tunnel-cloud-init.md | 2 +- ...-18-reverse-tunnel-cloud-init-hardening.md | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md diff --git a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md index b7b74833b4..269f10acdb 100644 --- a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md +++ b/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md @@ -49,7 +49,7 @@ SAM task 01M7QB46M5C4GE1Z51D1ZNEBGJ; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; pla pass against the new renderer - [x] Docs: self-hosting.mdx (boot mode), security.md (reverse-tunnel ingress; `isTunnelMode` now covers both tunnel modes), packages/cloud-init/AGENTS.md, rule 06 cloud-init step - [ ] lint, typecheck, test, build -- [ ] security-auditor, task-completion-validator (validator: WARN, no CRITICAL/HIGH; doc-sync, checklist and two extra snapshot cases addressed) +- [x] security-auditor (PASS: 0 CRITICAL/HIGH/MEDIUM; 3 LOW deferred to tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md to keep byte-identity with the BOX-proven tip), task-completion-validator (WARN, no CRITICAL/HIGH; all four items addressed in a0bb64b27) - [ ] BOX proof (byte-identical to integration tip: cite BOX run 01M7QB382PDGH42XEG3ZFFS6DE) - [ ] Staging: real VM node provisioning with heartbeat, then cleanup diff --git a/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md new file mode 100644 index 0000000000..6288b53df6 --- /dev/null +++ b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md @@ -0,0 +1,39 @@ +# Reverse-tunnel cloud-init hardening (L18 security review LOWs) + +## Problem + +The security review of L18 (PR #2885, reverse-tunnel cloud-init) found no CRITICAL, HIGH or +MEDIUM issues and three LOW ones. They were deferred so the L18 files stay byte-identical to the +integration branch `sam/selfhost-pass-2`, whose live BOX run is the L18 box evidence. Land them on +the integration branch first (so the next BOX run covers them), then on main with the slice that +next touches `packages/cloud-init/src/reverse-tunnel.ts`. + +## Context + +- Found by the security-auditor reviewer on PR #2885, 2026-11-18. +- Landing plan: idea 01M72M9AEB933ZY8269D376DKC. + +## Findings + +1. `reverseTunnelServerAddress` (`packages/cloud-init/src/reverse-tunnel.ts`) renders + `serverAddr = ""` when `new URL(controlPlaneUrl)` throws (for example a port above 65535 that + passes `SAFE_URL_RE`). frpc then dials `0.0.0.0` and fails TLS before sending the credential, + so the node boots but never connects. The comment claims validation already rejected it; it + does not. Provisioning always passes `https://api.${BASE_DOMAIN}`, so this is unreachable + today. +2. `reverseTunnelRemotePort` accepts 1-65535. The value comes from the lease allocator; the real + enforcement is the box's frps (`allowPorts` = lease range, `proxyBindAddr = 127.0.0.1`) and + the authorization plugin comparing `remotePort` with the lease (L22 front-door criteria). +3. Parity hardening for both connector units and downloads: `curl --proto '=https' + --proto-redir '=https'`; `RestrictNamespaces=yes`, `ProtectProc=invisible`, + `SystemCallArchitectures=native`, `UMask=0077`; write `credential.env` under `umask 077`. + +## Acceptance Criteria + +- [ ] Reverse mode rejects a control-plane URL with no parseable host or an invalid port, with a + validation error that does not echo the credential; the misleading comment is fixed. +- [ ] Reverse mode rejects remote ports below 1024 (or outside a configured lease range). +- [ ] Box frps config confirmed: `allowPorts` equals the lease range, `proxyBindAddr = 127.0.0.1`, + plugin checks `remotePort` against the lease on NewProxy. +- [ ] Download and unit hardening applied to both cloudflared and frpc, with the Cloudflare + snapshot change reviewed deliberately (it changes Cloudflare output). From 8e1a22a47b791e299fdb41fc3bed878a6690d202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:44:31 +0000 Subject: [PATCH 5/7] fix(cloud-init): fail closed when frpc install fails or the control plane URL is unusable CodeRabbit review on #2885: - the frpc install block ignored install's exit status, so a failed install booted the agent with no connector and never reported frpc_install; - reverse mode rendered serverAddr="" for a control plane URL that passes the shared character check but not new URL() (e.g. port 65536); it now fails validation instead (also security-review LOW-1); - the boot-render slice compares whole port lines and its Cloudflare control now runs the Cloudflare Tunnel path with a liveness assertion. Cloudflare output is unchanged: all 8 byte-identity snapshots pass. Each new guard was removed once and exactly its test went red. Co-Authored-By: Claude Opus 5.5 --- .../node-reverse-tunnel-boot-render.test.ts | 8 +++-- packages/cloud-init/src/reverse-tunnel.ts | 26 +++++++++----- .../cloud-init/src/template-reverse-tunnel.ts | 6 +++- .../cloud-init/tests/reverse-tunnel.test.ts | 36 ++++++++++++++++++- ...-18-reverse-tunnel-cloud-init-hardening.md | 10 ++++-- 5 files changed, 70 insertions(+), 16 deletions(-) diff --git a/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts b/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts index f7cbe0ba9e..fb280a86a4 100644 --- a/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts +++ b/apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts @@ -78,8 +78,8 @@ describe('reverse-tunnel node boot document', () => { const doc = YAML.parse(userData) as BootDoc; const frpc = file(doc, '/etc/sam/frpc/frpc.toml'); - expect(frpc.content).toContain(`remotePort = ${lease.port}`); - expect(frpc.content).toContain('localPort = 8444'); + expect(frpc.content).toMatch(new RegExp(`^remotePort = ${lease.port}$`, 'm')); + expect(frpc.content).toMatch(/^localPort = 8444$/m); expect(frpc.content).toContain(`user = "${node.id}"`); expect(frpc.content).toContain( 'metadatas.credential = "{{ .Envs.SAM_REVERSE_TUNNEL_CREDENTIAL }}"' @@ -102,12 +102,14 @@ describe('reverse-tunnel node boot document', () => { }); it('control: a Cloudflare node never reaches the reverse-tunnel renderer', async () => { - setEnv(tunnelEnv({ VM_AGENT_TRANSPORT: undefined })); + setEnv(tunnelEnv({ VM_AGENT_TRANSPORT: 'cloudflare-tunnel' })); const node = await freshNode(); await provisionNode(node.id, env); expect(rendered).toHaveLength(0); expect(mocks.cloudInitVars).toHaveLength(1); expect(mocks.cloudInitVars[0]).not.toHaveProperty('reverseTunnelCredential'); + // Liveness: this really is the Cloudflare Tunnel provisioning path. + expect(mocks.cloudInitVars[0]).toMatchObject({ cloudflareTunnelToken: expect.any(String) }); }); }); diff --git a/packages/cloud-init/src/reverse-tunnel.ts b/packages/cloud-init/src/reverse-tunnel.ts index 7b34c966b6..e741c0a091 100644 --- a/packages/cloud-init/src/reverse-tunnel.ts +++ b/packages/cloud-init/src/reverse-tunnel.ts @@ -90,19 +90,28 @@ export function validateReverseTunnelVariables( if (!validPort(remote)) { errors.push(`reverseTunnelRemotePort: must be numeric 1-65535 (got ${JSON.stringify(remote)})`); } + // frpc dials the control plane's host. The shared URL check is a character allowlist, so an + // unparseable URL (for example port 65536) would otherwise render an empty serverAddr. + if (!reverseTunnelServerAddress(variables.controlPlaneUrl)) { + errors.push( + 'controlPlaneUrl: must be an HTTPS URL with a host and a valid port in reverse-tunnel mode' + ); + } } -/** Host and port frpc dials: the control plane's own public HTTPS endpoint. */ -export function reverseTunnelServerAddress(controlPlaneUrl: string): { - host: string; - port: string; -} { +/** + * Host and port frpc dials: the control plane's own public HTTPS endpoint. Null when the URL is + * not an HTTPS URL with a host; validateReverseTunnelVariables rejects that case in reverse mode. + */ +export function reverseTunnelServerAddress( + controlPlaneUrl: string +): { host: string; port: string } | null { try { const url = new URL(controlPlaneUrl); + if (url.protocol !== 'https:' || !url.hostname) return null; return { host: url.hostname, port: url.port || '443' }; } catch { - // validateCloudInitVariables already rejected an unparseable control plane URL. - return { host: '', port: '443' }; + return null; } } @@ -110,7 +119,8 @@ export function reverseTunnelServerAddress(controlPlaneUrl: string): { export function reverseTunnelReplacements(variables: CloudInitVariables): Record { const reverse = isReverseTunnelMode(variables); const release = FRPC_RELEASES[DEFAULT_FRPC_VERSION]; - const server = reverseTunnelServerAddress(variables.controlPlaneUrl); + // Inert for non-reverse nodes, whose controlPlaneUrl this mode does not validate. + const server = reverseTunnelServerAddress(variables.controlPlaneUrl) ?? { host: '', port: '443' }; return { '{{ reverse_tunnel_credential }}': reverse ? (variables.reverseTunnelCredential ?? '') : '', '{{ reverse_tunnel_remote_port }}': reverse ? (variables.reverseTunnelRemotePort ?? '') : '', diff --git a/packages/cloud-init/src/template-reverse-tunnel.ts b/packages/cloud-init/src/template-reverse-tunnel.ts index 3307a644ab..9181e77431 100644 --- a/packages/cloud-init/src/template-reverse-tunnel.ts +++ b/packages/cloud-init/src/template-reverse-tunnel.ts @@ -28,7 +28,11 @@ export const REVERSE_TUNNEL_BOOTSTRAP_RUNCMD = ` - 'logger -t sam-boot "PHASE S /usr/local/sbin/sam-boot-failure frpc_install exit 1 fi - install -m 0755 "$FRP_DIR/$FRP_NAME/frpc" /usr/local/bin/frpc + if ! install -m 0755 "$FRP_DIR/$FRP_NAME/frpc" /usr/local/bin/frpc; then + rm -rf "$FRP_TMP" "$FRP_DIR" + /usr/local/sbin/sam-boot-failure frpc_install + exit 1 + fi rm -rf "$FRP_TMP" "$FRP_DIR" id sam-frpc >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-frpc if ! /etc/sam/firewall/setup-firewall.sh; then diff --git a/packages/cloud-init/tests/reverse-tunnel.test.ts b/packages/cloud-init/tests/reverse-tunnel.test.ts index bf6135dcae..95e9ed3d90 100644 --- a/packages/cloud-init/tests/reverse-tunnel.test.ts +++ b/packages/cloud-init/tests/reverse-tunnel.test.ts @@ -89,6 +89,31 @@ describe('reverse-tunnel variable validation', () => { expect(() => validateCloudInitVariables(reverse(overrides))).toThrow(/validation failed/); }); + it('rejects a control plane URL that frpc could not dial (no empty serverAddr)', () => { + const url = 'https://api.box.example.org:65536'; + expect(() => validateCloudInitVariables(reverse({ controlPlaneUrl: url }))).toThrow( + 'controlPlaneUrl: must be an HTTPS URL with a host and a valid port in reverse-tunnel mode' + ); + // Control: the same URL is not this mode's concern on other nodes. + let message = ''; + try { + validateCloudInitVariables(variables({ controlPlaneUrl: url })); + } catch (error) { + message = (error as Error).message; + } + expect(message).not.toContain('reverse-tunnel mode'); + }); + + it('keeps an explicit control plane port and defaults to 443', () => { + const toml = (url: string) => + file( + parse(reverse({ controlPlaneUrl: url, jwksUrl: `${url}/jwks` })), + '/etc/sam/frpc/frpc.toml' + ).content; + expect(toml('https://api.box.example.org:8443')).toMatch(/^serverPort = 8443$/m); + expect(toml('https://api.box.example.org')).toMatch(/^serverPort = 443$/m); + }); + it('never echoes the credential in validation errors', () => { let message = ''; try { @@ -254,7 +279,7 @@ function runBootScript(vars: CloudInitVariables, env: Record = { while [ "$#" -gt 0 ]; do if [ "$1" = -fsSLo ]; then shift; cp "$TEST_DIR/frp.tar.gz" "$1"; fi; shift; done; exit 0 ;; esac while [ "$#" -gt 0 ]; do if [ "$1" = -fLo ] || [ "$1" = -fsSLo ]; then shift; printf 'binary' > "$1"; fi; shift; done`, sha256sum: `echo "\${FAKE_SHA:-${RELEASE.amd64}} $1"`, - install: 'true', + install: 'case "$*" in *frpc*) exit "${FRPC_INSTALL_EXIT:-0}" ;; esac', id: 'exit 1', useradd: 'true', chown: 'true', @@ -321,6 +346,15 @@ describe('executed reverse-tunnel boot sequence', () => { if (reason === 'frpc_install') expect(calls).not.toMatch(/^install /m); }); + it('fails closed when the verified frpc cannot be installed', () => { + const { result, calls } = runBootScript(reverse(), { FRPC_INSTALL_EXIT: '1' }); + expect(result.status).toBe(1); + expect(calls).toMatch(/^install -m 0755 \S+\/frpc /m); + expect(calls).toContain('sam-boot-failure frpc_install'); + expect(calls).not.toContain('systemctl start vm-agent'); + expect(calls).not.toContain('sam-frpc.service'); + }); + it('reports a connector that cannot start', () => { const { result, calls } = runBootScript(reverse(), { FRPC_UNIT_EXIT: '1' }); expect(result.status).toBe(1); diff --git a/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md index 6288b53df6..0cca8f48d9 100644 --- a/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md +++ b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md @@ -3,7 +3,7 @@ ## Problem The security review of L18 (PR #2885, reverse-tunnel cloud-init) found no CRITICAL, HIGH or -MEDIUM issues and three LOW ones. They were deferred so the L18 files stay byte-identical to the +MEDIUM issues and three LOW ones. Finding 1 was then fixed in PR #2885 after CodeRabbit raised it too. The others were deferred so the L18 files stay close to the integration branch `sam/selfhost-pass-2`, whose live BOX run is the L18 box evidence. Land them on the integration branch first (so the next BOX run covers them), then on main with the slice that next touches `packages/cloud-init/src/reverse-tunnel.ts`. @@ -30,10 +30,14 @@ next touches `packages/cloud-init/src/reverse-tunnel.ts`. ## Acceptance Criteria -- [ ] Reverse mode rejects a control-plane URL with no parseable host or an invalid port, with a - validation error that does not echo the credential; the misleading comment is fixed. +- [x] Reverse mode rejects a control-plane URL with no parseable host or an invalid port (fixed in + PR #2885 after CodeRabbit raised it too; port to `sam/selfhost-pass-2`). - [ ] Reverse mode rejects remote ports below 1024 (or outside a configured lease range). - [ ] Box frps config confirmed: `allowPorts` equals the lease range, `proxyBindAddr = 127.0.0.1`, plugin checks `remotePort` against the lease on NewProxy. - [ ] Download and unit hardening applied to both cloudflared and frpc, with the Cloudflare snapshot change reviewed deliberately (it changes Cloudflare output). +- [ ] cloudflared parity with PR #2885's frpc fix: `TUNNEL_BOOTSTRAP_RUNCMD` ignores the exit status + of `install -m 0755 ... /usr/local/bin/cloudflared`, so a failed install boots without a + connector and never reports `cloudflared_install`. Left unchanged in L18 because L18 must + not change Cloudflare output. From b7e8dec0ddef401a0fb154fb8a2256d8d4cac3c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 13:48:00 +0000 Subject: [PATCH 6/7] fix(cloud-init): canonical reverse-mode numbers, Type=exec frpc unit, read-only CF baselines CodeRabbit review on #2885: - reverse mode renders validated ports and listener timings in canonical decimal (frpc TOML rejects leading zeros; dash reads them as octal), with a test that executes the rendered wait script under /bin/sh; - sam-frpc.service is Type=exec so a non-executable binary fails 'systemctl enable --now' and reports tunnel_connector; - the Cloudflare byte-identity test compares committed baselines byte for byte and fails when one is missing (no snapshot update mode). Cloudflare output is unchanged: all 8 baselines match. The write_files credential race applies equally to every node's callback token, so it is tracked with the Cloudflare parity items in the backlog task. Co-Authored-By: Claude Opus 5.5 --- packages/cloud-init/src/reverse-tunnel.ts | 5 ++- .../cloud-init/src/template-reverse-tunnel.ts | 7 +++- packages/cloud-init/src/tunnel.ts | 33 +++++++++------ .../tests/cloudflare-output-snapshot.test.ts | 16 ++++++-- .../cloud-init/tests/reverse-tunnel.test.ts | 40 +++++++++++++++++++ ...-18-reverse-tunnel-cloud-init-hardening.md | 26 +++++++++--- 6 files changed, 101 insertions(+), 26 deletions(-) diff --git a/packages/cloud-init/src/reverse-tunnel.ts b/packages/cloud-init/src/reverse-tunnel.ts index e741c0a091..6ad2aaf809 100644 --- a/packages/cloud-init/src/reverse-tunnel.ts +++ b/packages/cloud-init/src/reverse-tunnel.ts @@ -123,7 +123,10 @@ export function reverseTunnelReplacements(variables: CloudInitVariables): Record const server = reverseTunnelServerAddress(variables.controlPlaneUrl) ?? { host: '', port: '443' }; return { '{{ reverse_tunnel_credential }}': reverse ? (variables.reverseTunnelCredential ?? '') : '', - '{{ reverse_tunnel_remote_port }}': reverse ? (variables.reverseTunnelRemotePort ?? '') : '', + // Canonical decimal: frpc's TOML rejects a leading zero (validated numeric before render). + '{{ reverse_tunnel_remote_port }}': reverse + ? String(Number(variables.reverseTunnelRemotePort ?? '')) + : '', '{{ reverse_tunnel_server_addr }}': server.host, '{{ reverse_tunnel_server_port }}': server.port, '{{ reverse_tunnel_proxy_name }}': REVERSE_TUNNEL_PROXY_NAME, diff --git a/packages/cloud-init/src/template-reverse-tunnel.ts b/packages/cloud-init/src/template-reverse-tunnel.ts index 9181e77431..dfdfeafcfa 100644 --- a/packages/cloud-init/src/template-reverse-tunnel.ts +++ b/packages/cloud-init/src/template-reverse-tunnel.ts @@ -57,8 +57,10 @@ export const REVERSE_TUNNEL_CONNECTOR_RUNCMD = ` - 'logger -t sam-boot "PHASE S * when the pool refills, not on the path of each proxied connection. * loginFailExit=false + Restart=always: frpc keeps * retrying (an frps restart, a Caddy restart, an authz rejection while the lease is being - * fixed) instead of exiting. useSystemCa: frpc verifies the box's public certificate; without - * it frpc would accept any certificate. + * fixed) instead of exiting. Type=exec makes `systemctl enable --now` fail when the binary + * cannot be executed, so the connector runcmd reports tunnel_connector rather than booting + * without a connector. useSystemCa: frpc verifies the box's public certificate; without it + * frpc would accept any certificate. */ export const REVERSE_TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} @@ -104,6 +106,7 @@ export const REVERSE_TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} StartLimitIntervalSec=0 [Service] + Type=exec User=sam-frpc EnvironmentFile=/etc/sam/frpc/credential.env ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener diff --git a/packages/cloud-init/src/tunnel.ts b/packages/cloud-init/src/tunnel.ts index 4b137a8127..0c1d57b454 100644 --- a/packages/cloud-init/src/tunnel.ts +++ b/packages/cloud-init/src/tunnel.ts @@ -204,6 +204,11 @@ export function ingressFragments(variables: CloudInitVariables): Record { const tunnel = isTunnelMode(variables); const cloudflare = isCloudflareTunnelMode(variables); + // Reverse mode renders validated numbers in canonical decimal: frpc's TOML rejects leading + // zeros and dash arithmetic reads them as octal. Cloudflare output stays byte-identical to + // before the reverse mode existed (tests/cloudflare-output-snapshot.test.ts); its own + // leading-zero handling is tracked in tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md. + const num = (value: string) => (isReverseTunnelMode(variables) ? String(Number(value)) : value); const version = orDefault(variables.cloudflaredVersion, DEFAULT_CLOUDFLARED_VERSION); const release = CLOUDFLARED_RELEASES[version]; return { @@ -213,23 +218,25 @@ export function tunnelReplacements(variables: CloudInitVariables): Record = [ ]; describe('Cloudflare cloud-init output is byte-identical to main', () => { - it.each(cases)('%s', async (name, variables) => { - const rendered = generateCloudInit(variables); - await expect(rendered).toMatchFileSnapshot(`./__snapshots__/cloudflare-output/${name}.yaml`); + // Read-only byte comparison: a missing baseline fails (readFileSync throws) instead of being + // written from the current output, and no line-ending normalization applies. + it.each(cases)('%s', (name, variables) => { + const baseline = readFileSync( + new URL(`./__snapshots__/cloudflare-output/${name}.yaml`, import.meta.url) + ); + const rendered = Buffer.from(generateCloudInit(variables), 'utf8'); + expect(rendered.equals(baseline)).toBe(true); }); it('no Cloudflare rendering mentions the reverse-tunnel connector', () => { diff --git a/packages/cloud-init/tests/reverse-tunnel.test.ts b/packages/cloud-init/tests/reverse-tunnel.test.ts index 95e9ed3d90..e904b94781 100644 --- a/packages/cloud-init/tests/reverse-tunnel.test.ts +++ b/packages/cloud-init/tests/reverse-tunnel.test.ts @@ -114,6 +114,24 @@ describe('reverse-tunnel variable validation', () => { expect(toml('https://api.box.example.org')).toMatch(/^serverPort = 443$/m); }); + it('renders leading-zero numbers in canonical decimal (TOML and dash arithmetic)', () => { + const parsed = parse( + reverse({ + reverseTunnelRemotePort: '020007', + reverseTunnelLocalPort: '08444', + tunnelListenerWaitSeconds: '08', + tunnelListenerProbeIntervalSeconds: '09', + }) + ); + const toml = file(parsed, '/etc/sam/frpc/frpc.toml').content; + expect(toml).toMatch(/^remotePort = 20007$/m); + expect(toml).toMatch(/^localPort = 8444$/m); + const wait = file(parsed, '/usr/local/sbin/sam-wait-tunnel-listener').content; + expect(wait).toContain('+ 8))'); + expect(wait).toContain('sleep 9'); + expect(wait).toContain('http://127.0.0.1:8444/health'); + }); + it('never echoes the credential in validation errors', () => { let message = ''; try { @@ -191,6 +209,7 @@ describe('rendered reverse-tunnel user-data', () => { it('supervises frpc as an unprivileged, restart-always unit gated on the agent listener', () => { const parsed = parse(reverse()); const unit = file(parsed, '/etc/systemd/system/sam-frpc.service').content; + expect(unit).toContain('Type=exec\n'); expect(unit).toContain('User=sam-frpc\n'); expect(unit).toContain('EnvironmentFile=/etc/sam/frpc/credential.env\n'); expect(unit).toContain('ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener\n'); @@ -355,6 +374,27 @@ describe('executed reverse-tunnel boot sequence', () => { expect(calls).not.toContain('sam-frpc.service'); }); + it('runs the rendered listener wait script under /bin/sh with a leading-zero wait', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-reverse-wait-test-')); + tempDirs.push(dir); + const bin = join(dir, 'bin'); + mkdirSync(bin); + for (const [name, body] of Object.entries({ curl: 'exit 0', logger: 'true', sleep: 'true' })) { + writeFileSync(join(bin, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 }); + } + const script = file( + parse(reverse({ tunnelListenerWaitSeconds: '08' })), + '/usr/local/sbin/sam-wait-tunnel-listener' + ).content; + const result = spawnSync('/bin/sh', ['-c', script], { + env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + encoding: 'utf8', + timeout: 10_000, + }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + }); + it('reports a connector that cannot start', () => { const { result, calls } = runBootScript(reverse(), { FRPC_UNIT_EXIT: '1' }); expect(result.status).toBe(1); diff --git a/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md index 0cca8f48d9..663e20f14e 100644 --- a/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md +++ b/tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md @@ -15,18 +15,28 @@ next touches `packages/cloud-init/src/reverse-tunnel.ts`. ## Findings -1. `reverseTunnelServerAddress` (`packages/cloud-init/src/reverse-tunnel.ts`) renders - `serverAddr = ""` when `new URL(controlPlaneUrl)` throws (for example a port above 65535 that - passes `SAFE_URL_RE`). frpc then dials `0.0.0.0` and fails TLS before sending the credential, - so the node boots but never connects. The comment claims validation already rejected it; it - does not. Provisioning always passes `https://api.${BASE_DOMAIN}`, so this is unreachable - today. +1. (Fixed in PR #2885.) `reverseTunnelServerAddress` rendered `serverAddr = ""` when + `new URL(controlPlaneUrl)` threw (for example port 70000, which passes `SAFE_URL_RE`), and + cloud-init validation did not reject it. Provisioning builds the URL from `BASE_DOMAIN` + without checking it; only the installer's domain pattern (which rejects a port) kept + installer-deployed control planes from producing such a value. Reverse mode now rejects it at + the renderer. 2. `reverseTunnelRemotePort` accepts 1-65535. The value comes from the lease allocator; the real enforcement is the box's frps (`allowPorts` = lease range, `proxyBindAddr = 127.0.0.1`) and the authorization plugin comparing `remotePort` with the lease (L22 front-door criteria). 3. Parity hardening for both connector units and downloads: `curl --proto '=https' --proto-redir '=https'`; `RestrictNamespaces=yes`, `ProtectProc=invisible`, `SystemCallArchitectures=native`, `UMask=0077`; write `credential.env` under `umask 077`. +4. Boot secrets are written by cloud-init `write_files`, which opens the file under the process + umask, writes, then chmods (CodeRabbit on #2885). This applies to the reverse-tunnel + `credential.env` (0400) and equally to `/etc/sam/callback-token` (0600) on every Cloudflare + node. The window is cloud-init's init stage, before SSH, devcontainers or user workloads + exist. Fix both together, for example a root-only `/etc/sam` created in `bootcmd` (which + runs before `write_files`), and review the Cloudflare snapshot change deliberately. +5. Cloudflare mode passes tunnel numbers through verbatim, so a leading zero + (`VM_AGENT_TUNNEL_LISTENER_WAIT_SECONDS=08`) would break dash arithmetic in the listener wait + script. Reverse mode renders canonical decimal since #2885; Cloudflare output was left + byte-identical in L18. ## Acceptance Criteria @@ -37,6 +47,10 @@ next touches `packages/cloud-init/src/reverse-tunnel.ts`. plugin checks `remotePort` against the lease on NewProxy. - [ ] Download and unit hardening applied to both cloudflared and frpc, with the Cloudflare snapshot change reviewed deliberately (it changes Cloudflare output). +- [ ] Boot secrets (`credential.env`, `callback-token`) are never readable by non-root, even + transiently (finding 4). +- [ ] Cloudflare mode renders tunnel numbers in canonical decimal (finding 5), with the snapshot + change reviewed. - [ ] cloudflared parity with PR #2885's frpc fix: `TUNNEL_BOOTSTRAP_RUNCMD` ignores the exit status of `install -m 0755 ... /usr/local/bin/cloudflared`, so a failed install boots without a connector and never reports `cloudflared_install`. Left unchanged in L18 because L18 must From a92ec057339a10c18796923d18958e74e84c96f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 14:33:45 +0000 Subject: [PATCH 7/7] task: archive L18 with staging and BOX evidence Co-Authored-By: Claude Opus 5.5 --- ...6-11-18-selfhost-l18-reverse-tunnel-cloud-init.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) rename tasks/{active => archive}/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md (83%) diff --git a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md b/tasks/archive/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md similarity index 83% rename from tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md rename to tasks/archive/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md index 269f10acdb..8850c8d9ed 100644 --- a/tasks/active/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md +++ b/tasks/archive/2026-11-18-selfhost-l18-reverse-tunnel-cloud-init.md @@ -48,10 +48,10 @@ SAM task 01M7QB46M5C4GE1Z51D1ZNEBGJ; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; pla - [x] API reverse-tunnel tests that render through `installReverseTunnelTransport(generateCloudInit)` pass against the new renderer - [x] Docs: self-hosting.mdx (boot mode), security.md (reverse-tunnel ingress; `isTunnelMode` now covers both tunnel modes), packages/cloud-init/AGENTS.md, rule 06 cloud-init step -- [ ] lint, typecheck, test, build +- [x] lint, typecheck, test, build (local full suite 41/41 tasks; CI green on b7e8dec0d) - [x] security-auditor (PASS: 0 CRITICAL/HIGH/MEDIUM; 3 LOW deferred to tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md to keep byte-identity with the BOX-proven tip), task-completion-validator (WARN, no CRITICAL/HIGH; all four items addressed in a0bb64b27) -- [ ] BOX proof (byte-identical to integration tip: cite BOX run 01M7QB382PDGH42XEG3ZFFS6DE) -- [ ] Staging: real VM node provisioning with heartbeat, then cleanup +- [x] BOX proof: original port covered by BOX run 01M7QB382PDGH42XEG3ZFFS6DE; after CodeRabbit fixes, own BOX proof on ba35d4905 (integration PR #2886): reverse-tunnel node 01M7QEZFVAB723NYBXXD4EPAQQ lease 20008, frpc login, heartbeat, gateway system-info, terminal, cleanup +- [x] Staging: primary staging at b7e8dec0d, Cloudflare Tunnel node 01M7QGWHQDPNB74YWAQK37SB67 heartbeat 14:32:02Z, workspace + terminal, cleaned up. staging2 unusable for VMs (GCP STS 400, #2880) ## Acceptance criteria @@ -62,3 +62,9 @@ SAM task 01M7QB46M5C4GE1Z51D1ZNEBGJ; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; pla - Invalid reverse-tunnel variable combinations are rejected without echoing the credential. - The control plane accepts `frpc_install` boot-failure reports. - Staging node provisioning still boots a VM that heartbeats; VM cleaned up. + +## Outcome + +- CodeRabbit (10 threads): 9 fixed (8e1a22a47, b7e8dec0d), 1 deferred with reason (write_files secret window shared with callback-token). +- Review changes moved the slice off the integration tip; the same changes are on integration PR #2886. +- Follow-ups: tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md.