feat(deploy): run the code runner in a dedicated LXD VM on the app host

This commit is contained in:
shira committed 2026-10-11 09:45:12 +03:00
1 parent 1ebd23693e
commit 53a125f2b5
11 files changed
+832 -10

No files matched your search

+34 -2
View File
@@ -64,7 +64,7 @@ DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DE
DEMO_RELEASE_MANIFEST="$(DEMO_RELEASE_MANIFEST)"
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs runner-dev-config runner-dev-build runner-dev-up runner-dev-down runner-dev-logs check-runner-dev check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs runner-dev-config runner-dev-build runner-dev-up runner-dev-down runner-dev-logs check-runner-dev check-runner-vm check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
help: ## Show deployment commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -155,6 +155,35 @@ runner-dev-down: ## Stop the dev-only runner
runner-dev-logs: ## Follow dev-only runner logs
RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" logs -f
# Production code runner VM (deploy/labs/runner-vm.sh). The runner-vm-*
# targets run on the app host as a member of the docker and lxd groups,
# without sudo. Secrets and reports stay in RUNNER_VM_STATE_DIR (default
# ~/lincodex-runner), never in the repository. Settings come from the
# environment or the make command line, for example A16_BUNDLE=<path>.
.PHONY: runner-vm-up runner-vm-secrets runner-vm-rootfs runner-vm-create runner-vm-install runner-vm-a16 runner-vm-check
RUNNER_VM_SCRIPT := $(ROOT)/deploy/labs/runner-vm.sh
runner-vm-up: ## App host: secrets, runner file system, VM (once), install, and checks
@bash "$(RUNNER_VM_SCRIPT)" up
runner-vm-secrets: ## App host: create the runner CA, server certificate, and token outside the repository
@bash "$(RUNNER_VM_SCRIPT)" secrets
runner-vm-rootfs: ## App host: build runner/Dockerfile and export its file system for the VM
@bash "$(RUNNER_VM_SCRIPT)" rootfs
runner-vm-create: ## App host: create and start the runner VM with its static address
@bash "$(RUNNER_VM_SCRIPT)" create
runner-vm-install: ## App host: push the runner, its secrets, and the systemd unit into the VM and restart it
@bash "$(RUNNER_VM_SCRIPT)" install
runner-vm-a16: ## App host: run the A16 suite in the runner VM (bundle from make -C runner a16-bundle)
@bash "$(RUNNER_VM_SCRIPT)" a16
runner-vm-check: ## App host: check the VM, TLS and token, a harmless run, mounts, secrets, limits, and network denial
@bash "$(RUNNER_VM_SCRIPT)" check
# Edge proxy (TLS and tunnel templates under deploy/edge). edge.env is local;
# the checked-in example is used when it does not exist.
.PHONY: edge-render edge-config
@@ -168,7 +197,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release check-perimeter check-e2e-mail check-demo check-runner-dev ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check: config check-workflows check-release check-perimeter check-e2e-mail check-demo check-runner-dev check-runner-vm ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py'
@@ -185,6 +214,9 @@ check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E
check-runner-dev: ## Check that the dev-only runner switches stay out of production files
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_runner_dev.py'
check-runner-vm: ## Check that the runner VM script keeps the VM boundary (no LXD needed)
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_runner_vm.py'
check-demo: ## Check the guards of the demo targets and the demo overlay without starting services
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_demo.py'
+1
View File
@@ -12,6 +12,7 @@ Configuration for running the application with Docker Compose and Nginx.
- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand).
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
- `labs/` holds the LXD layout of the app host for the isolated runner and the labs (`lxd-preseed.yaml`, `acls.sh`) and `runner-vm.sh`, which builds, updates, and checks the production runner VM: `make -C deploy runner-vm-up`, `runner-vm-a16`, and `runner-vm-check` on the app host, and `check-runner-vm` anywhere; see [the runner VM](../docs/en/DEPLOY.md#production-the-runner-vm).
- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address).
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; `make -C deploy test-e2e-registration` enables a local Resend-compatible inbox only for registration browser tests. See [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite) for details.
+1
View File
@@ -12,6 +12,7 @@
- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд).
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
- `labs/` содержит раскладку LXD хоста приложения для изолированного исполнителя и лабораторий (`lxd-preseed.yaml`, `acls.sh`) и `runner-vm.sh`, который собирает, обновляет и проверяет production VM исполнителя: `make -C deploy runner-vm-up`, `runner-vm-a16` и `runner-vm-check` на хосте приложения и `check-runner-vm` где угодно; см. [VM исполнителя](../docs/ru/DEPLOY.md#production-vm-исполнителя).
- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента).
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; `make -C deploy test-e2e-registration` включает локальный Resend-compatible inbox только для браузерных тестов регистрации. Подробности см. в [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
+551
View File
@@ -0,0 +1,551 @@
#!/usr/bin/env bash
# Provisions and checks the code runner VM on the app host.
#
# The runner runs in an LXD virtual machine (a separate guest kernel) on the
# lxdbr-runner bridge with the lincodex-runner profile from lxd-preseed.yaml.
# The VM gets no shared folder, no Docker socket, and no secret of the core:
# only its own TLS certificate and key and the runner API token. It has a
# static address and no default route; the network ACL of the bridge lets
# only the app network and the host side open TCP 8443 and drops everything
# the guest starts. Run this as a member of the docker and lxd groups; it
# never uses sudo and never touches the Docker stack, ufw, or the LXD
# network, ACL, and profile objects.
#
# Commands (run from a checkout of the repository on the app host):
# secrets create the private CA, the server certificate, and the token
# (kept when present; the server certificate is reissued when it
# expires within 30 days)
# rootfs build runner/Dockerfile and export its file system to a tarball
# create create and start the VM with its static address (once)
# install push the file system, secrets, and systemd unit; restart the
# service; harden the guest
# a16 run the A16 hostile-program suite in the VM with the service's
# sandbox settings and copy the report to the host
# check check the VM configuration, TLS and the token, a harmless run,
# mounts, credentials, limits, cleanup, and network denial
# up secrets, rootfs, create (when missing), install, and check
set -euo pipefail
script_dir=$(cd "$(dirname "$0")" && pwd)
repo_root=$(cd "$script_dir/../.." && pwd)
vm=${RUNNER_VM_NAME:-lincodex-runner}
vm_profile=${RUNNER_VM_PROFILE:-lincodex-runner}
vm_image=${RUNNER_VM_IMAGE:-images:debian/12/cloud}
vm_network=${RUNNER_VM_NETWORK:-lxdbr-runner}
vm_address=${RUNNER_VM_ADDRESS:-10.80.0.10}
vm_prefix=${RUNNER_VM_PREFIX:-24}
host_side=${RUNNER_HOST_SIDE:-10.80.0.1}
app_subnet=${APP_SUBNET:-172.29.79.0/24}
app_network=${APP_NETWORK:-app_default}
port=${RUNNER_PORT:-8443}
state_dir=${RUNNER_VM_STATE_DIR:-$HOME/lincodex-runner}
secrets_dir=$state_dir/secrets
reports_dir=$state_dir/reports
rootfs_tar=$state_dir/runner-rootfs.tar.gz
runner_src=${RUNNER_SRC:-$repo_root/runner}
runner_version=${RUNNER_VERSION:-$(git -C "$repo_root" describe --always --dirty --abbrev=12 2>/dev/null || echo local)}
a16_bundle=${A16_BUNDLE:-$runner_src/bin/a16-bundle.tar.gz}
probe_image=${RUNNER_VM_PROBE_IMAGE:-curlimages/curl:latest}
# Hosts the guest must not reach; the LAN gateway is the host's default route.
lan_gateway=${RUNNER_VM_LAN_GATEWAY:-$(ip route show default 2>/dev/null | awk '{print $3; exit}')}
work_tmpfs_size=${RUNNER_WORK_TMPFS_SIZE:-256m}
service_memory_max=${RUNNER_SERVICE_MEMORY_MAX:-2560M}
service_tasks_max=${RUNNER_SERVICE_TASKS_MAX:-512}
# Layout inside the VM.
guest_root=/opt/lincodex-runner/root
guest_a16=/opt/lincodex-runner/a16
guest_secrets=/etc/lincodex-runner
service=lincodex-runner
a16_unit=lincodex-runner-a16
log() { printf '%s %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
die() { log "error: $*"; exit 1; }
# Without a terminal, lxc reads stdin; every call gets /dev/null and no
# progress output.
lxcq() { lxc --quiet "$@" </dev/null; }
guest() { lxc exec "$vm" -- "$@" </dev/null; }
need() {
local tool
for tool in "$@"; do
command -v "$tool" >/dev/null 2>&1 || die "missing tool: $tool"
done
}
vm_exists() { lxcq info "$vm" >/dev/null 2>&1; }
wait_for_agent() {
for _ in $(seq 1 90); do
if guest true >/dev/null 2>&1; then
return 0
fi
sleep 2
done
die "the LXD agent of $vm did not answer"
}
# Sandbox settings shared by the service and the A16 run, so the suite
# checks exactly what the service gets. The work directory is a fresh tmpfs
# per start; exec lets built Go solutions run from it.
sandbox_properties() {
printf '%s\n' \
"RootDirectory=$guest_root" \
"MountAPIVFS=yes" \
"Delegate=yes" \
"TemporaryFileSystem=/var/lib/lincodex-runner/work:mode=0711,size=$work_tmpfs_size,exec,nosuid,nodev" \
"PrivateTmp=yes" \
"ProtectSystem=strict" \
"ProtectHome=yes" \
"NoNewPrivileges=yes" \
"LimitCORE=0" \
"KillMode=control-group" \
"MemoryMax=$service_memory_max" \
"TasksMax=$service_tasks_max"
}
# The runner reads its delegated cgroup from the path of its own unit.
cgroup_root() { printf '/sys/fs/cgroup/system.slice/%s.service' "$1"; }
cmd_secrets() {
need openssl
(umask 077 && mkdir -p "$secrets_dir")
chmod 700 "$state_dir" "$secrets_dir"
cd "$secrets_dir"
umask 077
if [ ! -s ca.key ] || [ ! -s ca.crt ]; then
log "creating the private runner CA"
openssl req -x509 -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
-keyout ca.key -out ca.crt -days 1825 -subj "/CN=Lincodex runner CA" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign" 2>/dev/null
fi
if [ ! -s tls.crt ] || [ ! -s tls.key ] || ! openssl x509 -in tls.crt -noout -checkend 2592000 >/dev/null; then
log "issuing the server certificate for $vm_address"
openssl req -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
-keyout tls.key -out tls.csr -subj "/CN=$vm" 2>/dev/null
printf '%s\n' \
"basicConstraints=critical,CA:FALSE" \
"keyUsage=critical,digitalSignature" \
"extendedKeyUsage=serverAuth" \
"subjectAltName=IP:$vm_address" >tls.ext
openssl x509 -req -in tls.csr -CA ca.crt -CAkey ca.key -set_serial "0x$(openssl rand -hex 16)" \
-days 397 -sha256 -extfile tls.ext -out tls.crt 2>/dev/null
rm -f tls.csr tls.ext
fi
if [ ! -s api-token ]; then
log "creating the runner API token"
openssl rand -hex 32 >api-token
fi
# The backend sends the same header; curl reads it from this file, so the
# token never appears on a command line.
printf 'Authorization: Bearer %s\n' "$(cat api-token)" >auth-header
chmod 600 ./*
log "secrets are in $secrets_dir (CA key stays on the host)"
}
cmd_rootfs() {
need docker
[ -f "$runner_src/Dockerfile" ] || die "no runner/Dockerfile under $runner_src"
local image="lincodex-runner-vm:$runner_version" container
log "building $image from $runner_src"
docker build --pull --file "$runner_src/Dockerfile" --tag "$image" "$runner_src" >&2
container=$(docker create "$image")
(umask 077 && mkdir -p "$state_dir")
docker export "$container" | gzip -1 >"$rootfs_tar.tmp"
docker rm "$container" >/dev/null
mv "$rootfs_tar.tmp" "$rootfs_tar"
printf '%s\n' "$runner_version" >"$state_dir/runner-rootfs.version"
log "exported $(du -h "$rootfs_tar" | cut -f1) to $rootfs_tar; remove the image with: docker image rm $image"
}
cmd_create() {
need lxc
vm_exists && die "$vm already exists; remove it with 'lxc delete --force $vm' to recreate it"
log "creating VM $vm from $vm_image with profile $vm_profile"
# Only the runner profile: no default profile, so no other network or disk.
lxcq init "$vm_image" "$vm" --vm --profile "$vm_profile"
lxcq config set "$vm" boot.autostart=true
local mac
mac=$(lxcq config get "$vm" volatile.eth0.hwaddr)
[ -n "$mac" ] || die "no MAC address for eth0"
# Static address, no gateway, no DNS: the guest has no route anywhere but
# its own subnet. Replies to the host side stay on that subnet.
lxcq config set "$vm" cloud-init.network-config "version: 2
ethernets:
runner0:
match:
macaddress: \"$mac\"
addresses: [$vm_address/$vm_prefix]
dhcp4: false
dhcp6: false
accept-ra: false
link-local: []
"
lxcq config set "$vm" cloud-init.user-data "#cloud-config
package_update: false
package_upgrade: false
ssh_pwauth: false
disable_root: true
"
lxcq start "$vm"
wait_for_agent
guest cloud-init status --wait >/dev/null 2>&1 || true
# The rendered network configuration stays; cloud-init and the guest API
# (/dev/lxd) are needed only for this first boot.
guest touch /etc/cloud/cloud-init.disabled
lxcq config set "$vm" security.devlxd=false
lxcq restart "$vm"
wait_for_agent
log "VM $vm is running"
}
cmd_install() {
need lxc
vm_exists || die "$vm does not exist; run create first"
[ -s "$rootfs_tar" ] || die "no root file system at $rootfs_tar; run rootfs first"
for file in tls.crt tls.key api-token; do
[ -s "$secrets_dir/$file" ] || die "missing $secrets_dir/$file; run secrets first"
done
wait_for_agent
log "hardening the guest"
# Nothing in the guest needs SSH, IPv6, or timers that try the network.
# shellcheck disable=SC2016 # $unit expands in the guest.
guest sh -c 'for unit in ssh.service ssh.socket sshd.service apt-daily.timer apt-daily-upgrade.timer man-db.timer e2scrub_all.timer; do
systemctl disable --now "$unit" >/dev/null 2>&1 || true
systemctl mask "$unit" >/dev/null 2>&1 || true
done
printf "%s\n" "net.ipv6.conf.all.disable_ipv6 = 1" "net.ipv6.conf.default.disable_ipv6 = 1" >/etc/sysctl.d/90-lincodex-runner.conf
sysctl -q -p /etc/sysctl.d/90-lincodex-runner.conf'
log "pushing the runner file system ($(cat "$state_dir/runner-rootfs.version" 2>/dev/null || echo unknown))"
lxcq file push "$rootfs_tar" "$vm/var/tmp/runner-rootfs.tar.gz"
guest sh -euc "
rm -rf $guest_root.new
mkdir -p $guest_root.new
tar --warning=no-unknown-keyword -xzf /var/tmp/runner-rootfs.tar.gz -C $guest_root.new
rm -f /var/tmp/runner-rootfs.tar.gz $guest_root.new/.dockerenv
# Mount points of the unit inside the root.
mkdir -p $guest_root.new$guest_secrets $guest_root.new/opt/a16 $guest_root.new/var/lib/lincodex-runner/work
chmod 0755 $guest_root.new
"
log "pushing the runner secrets"
guest sh -euc "install -d -m 0700 -o root -g root $guest_secrets"
local file
for file in tls.crt tls.key api-token; do
lxcq file push --mode 0600 --uid 0 --gid 0 "$secrets_dir/$file" "$vm$guest_secrets/$file"
done
log "writing the systemd unit"
local unit
unit=$(mktemp)
{
printf '%s\n' "# Managed by deploy/labs/runner-vm.sh; edits are overwritten." \
"[Unit]" \
"Description=Lincodex code runner" \
"" \
"[Service]" \
"Type=exec" \
"ExecStart=/opt/lincodex-runner/lincodex-runner" \
"Restart=on-failure" \
"RestartSec=2s" \
"TimeoutStopSec=45s"
sandbox_properties
printf '%s\n' \
"BindReadOnlyPaths=$guest_secrets" \
"IPAddressDeny=any" \
"IPAddressAllow=$host_side/32 $app_subnet localhost" \
"Environment=RUNNER_LISTEN_ADDRESS=:$port" \
"Environment=RUNNER_TLS_CERT_FILE=$guest_secrets/tls.crt" \
"Environment=RUNNER_TLS_KEY_FILE=$guest_secrets/tls.key" \
"Environment=RUNNER_API_TOKEN_FILE=$guest_secrets/api-token" \
"Environment=RUNNER_CGROUP_ROOT=$(cgroup_root "$service")" \
"Environment=RUNNER_MAX_CONCURRENT_RUNS=1" \
"" \
"[Install]" \
"WantedBy=multi-user.target"
} >"$unit"
lxcq file push --mode 0644 --uid 0 --gid 0 "$unit" "$vm/etc/systemd/system/$service.service"
rm -f "$unit"
log "switching to the new file system and restarting the service"
guest sh -euc "
systemctl daemon-reload
systemctl stop $service 2>/dev/null || true
if [ -d $guest_root ]; then mv $guest_root $guest_root.old; fi
mv $guest_root.new $guest_root
rm -rf $guest_root.old
systemctl enable --now $service >/dev/null 2>&1
"
wait_ready
}
wait_ready() {
for _ in $(seq 1 30); do
if curl -fsS -m 3 --cacert "$secrets_dir/ca.crt" "https://$vm_address:$port/readyz" >/dev/null 2>&1; then
log "the runner answers ready on https://$vm_address:$port"
return 0
fi
sleep 2
done
guest journalctl -u "$service" -n 30 --no-pager >&2 || true
die "the runner did not become ready"
}
cmd_a16() {
need lxc python3
[ -s "$a16_bundle" ] || die "no A16 bundle at $a16_bundle; build it with make -C runner a16-bundle"
vm_exists || die "$vm does not exist"
wait_for_agent
log "pushing the A16 bundle"
lxcq file push "$a16_bundle" "$vm/var/tmp/a16-bundle.tar.gz"
guest sh -euc "
rm -rf $guest_a16
mkdir -p $guest_a16
tar --warning=no-unknown-keyword -xzf /var/tmp/a16-bundle.tar.gz -C $guest_a16 --strip-components=1
rm -f /var/tmp/a16-bundle.tar.gz
"
local args=() property status=0 stamp report
while IFS= read -r property; do
args+=(-p "$property")
done < <(sandbox_properties)
stamp=$(date -u +%Y%m%dT%H%M%SZ)
log "running the A16 suite in a transient unit with the service's sandbox settings"
guest systemd-run --unit "$a16_unit" --wait --pipe --collect --quiet \
"${args[@]}" -p "BindPaths=$guest_a16:/opt/a16" -p "IPAddressDeny=any" \
-E "RUNNER_CGROUP_ROOT=$(cgroup_root "$a16_unit")" \
/bin/sh /opt/a16/run-a16.sh /opt/a16/report.json >"$state_dir/a16-$stamp.log" 2>&1 || status=$?
(umask 077 && mkdir -p "$reports_dir")
report="$reports_dir/a16-$stamp.json"
lxcq file pull "$vm$guest_a16/report.json" "$report" || die "no A16 report; see $state_dir/a16-$stamp.log"
mv "$state_dir/a16-$stamp.log" "$reports_dir/a16-$stamp.log"
python3 - "$report" <<'EOF'
import json, sys
report = json.load(open(sys.argv[1]))
for case in report["cases"]:
print(f'{"PASS" if case.get("passed") else "FAIL"} {case["name"]}')
print(f'verdict={report["verdict"]} passed={report["passed"]} failed={report["failed"]} '
f'nothing_left_after_runs={report["nothing_left_after_runs"]} '
f'practice_may_be_enabled={report["practice_may_be_enabled"]}')
EOF
log "A16 report: $report (exit status $status)"
return "$status"
}
# check helpers: every check prints PASS or FAIL and the run fails at the end.
failures=0
pass() { printf 'PASS %s\n' "$*"; }
fail() { printf 'FAIL %s\n' "$*"; failures=$((failures + 1)); }
expect() {
local name=$1 want=$2 got=$3
if [ "$got" = "$want" ]; then pass "$name ($got)"; else fail "$name: got '$got', want '$want'"; fi
}
https_code() {
curl -sS -o /dev/null -w '%{http_code}' -m 10 --cacert "$secrets_dir/ca.crt" "$@" 2>/dev/null || true
}
check_config() {
python3 - "$vm" "$vm_network" <<'EOF'
import json, subprocess, sys
vm, network = sys.argv[1], sys.argv[2]
data = json.loads(subprocess.run(["lxc", "query", f"/1.0/instances/{vm}"], stdin=subprocess.DEVNULL,
capture_output=True, check=True, text=True).stdout)
config, devices = data["expanded_config"], data["expanded_devices"]
checks = [
("instance is a virtual machine", data["type"] == "virtual-machine", data["type"]),
("devices are only the root disk and eth0", sorted(devices) == ["eth0", "root"], sorted(devices)),
("eth0 is on the runner bridge", devices.get("eth0", {}).get("network") == network, devices.get("eth0")),
("no host path is shared", all(d.get("type") != "disk" or d.get("path") == "/" and "source" not in d
for d in devices.values()), "disks"),
("limits.cpu is 2", config.get("limits.cpu") == "2", config.get("limits.cpu")),
("limits.memory is 3GiB", config.get("limits.memory") == "3GiB", config.get("limits.memory")),
("the guest API /dev/lxd is off", config.get("security.devlxd") == "false", config.get("security.devlxd")),
("the VM starts with the host", config.get("boot.autostart") == "true", config.get("boot.autostart")),
("no privileged, nesting, or raw settings", not any(k.startswith("raw.") or k in ("security.privileged", "security.nesting")
for k in config), "config"),
]
for name, ok, value in checks:
print(f'{"PASS" if ok else "FAIL"} {name} ({value})')
EOF
}
cmd_check() {
need lxc curl python3
vm_exists || die "$vm does not exist"
wait_for_agent
local base="https://$vm_address:$port" output
output=$(check_config)
printf '%s\n' "$output"
failures=$((failures + $(grep -c '^FAIL' <<<"$output" || true)))
# TLS and the token, from the host side of the bridge.
expect "healthz over TLS from the host side" 200 "$(https_code "$base/healthz")"
expect "readyz over TLS from the host side" 200 "$(https_code "$base/readyz")"
expect "a run read without a token" 401 "$(https_code "$base/v1/runs/00000000-0000-4000-8000-000000000000")"
expect "a run read with a wrong token" 401 "$(https_code -H "Authorization: Bearer wrong-token-0123456789abcdefghijklmnop" "$base/v1/runs/00000000-0000-4000-8000-000000000000")"
expect "a run read with the token (unknown run)" 404 "$(https_code -H "@$secrets_dir/auth-header" "$base/v1/runs/00000000-0000-4000-8000-000000000000")"
if curl -sS -o /dev/null -m 5 --cacert "$secrets_dir/ca.crt" --tls-max 1.2 "$base/healthz" 2>/dev/null; then
fail "TLS 1.2 is refused"
else
pass "TLS 1.2 is refused"
fi
local plain
plain=$(curl -sS -o /dev/null -w '%{http_code}' -m 5 "http://$vm_address:$port/healthz" 2>/dev/null || true)
if [ "$plain" = 200 ]; then fail "plain HTTP is served"; else pass "plain HTTP is not served ($plain)"; fi
# A harmless run in each language.
harmless_run python3 'import sys
a, b = map(int, sys.stdin.read().split())
print(a + b)'
harmless_run go 'package main
import "fmt"
func main() {
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
}'
check_app_network "$base"
check_guest
printf '\n'
if [ "$failures" -gt 0 ]; then
log "$failures check(s) failed"
return 1
fi
log "all checks passed"
}
harmless_run() {
local language=$1 source=$2 id body state outcome
id=$(python3 -c 'import uuid; print(uuid.uuid4())')
body=$(python3 -c 'import json, sys
print(json.dumps({"language": sys.argv[1], "source": sys.argv[2],
"limits": {"time_limit_ms": 2000, "memory_limit_mb": 128, "output_limit_kb": 64},
"groups": [{"id": "public", "visibility": "public", "checker": {"kind": "exact"},
"tests": [{"id": "t1", "input": "2 3\n", "expected_output": "5\n"}]}]}))' "$language" "$source")
expect "submit a harmless $language run" 202 "$(https_code -X PUT -H "@$secrets_dir/auth-header" -H 'Content-Type: application/json' --data "$body" "https://$vm_address:$port/v1/runs/$id")"
for _ in $(seq 1 60); do
state=$(curl -sS -m 10 --cacert "$secrets_dir/ca.crt" -H "@$secrets_dir/auth-header" "https://$vm_address:$port/v1/runs/$id" 2>/dev/null || true)
if [ "$(python3 -c 'import json, sys; print(json.loads(sys.argv[1]).get("state", ""))' "$state" 2>/dev/null)" = finished ]; then
break
fi
sleep 1
done
outcome=$(python3 -c 'import json, sys; print(json.loads(sys.argv[1])["result"]["outcome"])' "$state" 2>/dev/null || echo none)
expect "the harmless $language run is accepted" accepted "$outcome"
}
# The backend's network: a throwaway container on the app network calls the
# runner the way the backend will. It mounts only the CA and the header file.
check_app_network() {
local base=$1
if ! command -v docker >/dev/null 2>&1 || ! docker network inspect "$app_network" >/dev/null 2>&1; then
fail "the app network $app_network is not available for the reachability check"
return
fi
local probe=(docker run --rm --network "$app_network" --user "$(id -u):$(id -g)"
--read-only --cap-drop ALL --security-opt no-new-privileges
-v "$secrets_dir/ca.crt:/probe/ca.crt:ro" -v "$secrets_dir/auth-header:/probe/auth-header:ro"
--entrypoint curl "$probe_image" -sS -o /dev/null -w '%{http_code}' -m 10 --cacert /probe/ca.crt)
expect "readyz from the app network" 200 "$("${probe[@]}" "$base/readyz" 2>/dev/null || true)"
expect "a run read from the app network without a token" 401 "$("${probe[@]}" "$base/v1/runs/00000000-0000-4000-8000-000000000000" 2>/dev/null || true)"
expect "a run read from the app network with the token" 404 "$("${probe[@]}" -H @/probe/auth-header "$base/v1/runs/00000000-0000-4000-8000-000000000000" 2>/dev/null || true)"
expect "SSH port of the VM from the app network" 000 "$(docker run --rm --network "$app_network" --entrypoint curl "$probe_image" -sS -o /dev/null -w '%{http_code}' -m 5 "telnet://$vm_address:22" 2>/dev/null || true)"
}
# Checks that run inside the guest; they read their settings from the
# environment and print PASS or FAIL lines.
guest_checks() {
cat <<'EOF'
ok() { printf 'PASS %s\n' "$*"; }
bad() { printf 'FAIL %s\n' "$*"; }
is() { if [ "$2" = "$3" ]; then ok "$1 ($3)"; else bad "$1: got '$3', want '$2'"; fi; }
is "the runner service is active" active "$(systemctl is-active "$SERVICE")"
is "the guest sees 2 CPUs" 2 "$(nproc)"
mem=$(awk '/^MemTotal/ {printf "%d", $2/1024}' /proc/meminfo)
if [ "$mem" -ge 2700 ] && [ "$mem" -le 3100 ]; then ok "guest memory is about 3 GiB (${mem} MiB)"; else bad "guest memory ${mem} MiB"; fi
is "service MemoryMax" 2684354560 "$(systemctl show -p MemoryMax --value "$SERVICE")"
is "service TasksMax" 512 "$(systemctl show -p TasksMax --value "$SERVICE")"
is "service cgroup is delegated" yes "$(systemctl show -p Delegate --value "$SERVICE")"
pid=$(systemctl show -p MainPID --value "$SERVICE")
is "one concurrent run" RUNNER_MAX_CONCURRENT_RUNS=1 "$(tr '\0' '\n' </proc/"$pid"/environ | grep '^RUNNER_MAX_CONCURRENT_RUNS=')"
# Mounts: no shared folder of the host. The LXD agent copies itself from its
# config drive to a tmpfs at boot; the drive is not left mounted.
shared=$(findmnt -rn -o TARGET,FSTYPE | awk '$2 ~ /^(9p|virtiofs|nfs|nfs4|cifs|smb3|fuse|fuse\..*)$/ {print $1}')
is "no shared folder is mounted" "" "$shared"
is "no Docker socket" none "$(ls /var/run/docker.sock /run/docker.sock 2>/dev/null || echo none)"
is "no docker or lxc client" none "$(command -v docker lxc lxd 2>/dev/null || echo none)"
# Credentials: only the runner's own TLS pair and token, readable by root only.
is "secret files" "api-token tls.crt tls.key" "$(ls "$SECRETS" | tr '\n' ' ' | sed 's/ $//')"
is "secret file modes" "600 600 600" "$(stat -c %a "$SECRETS"/* | tr '\n' ' ' | sed 's/ $//')"
is "no CA key in the guest" none "$(find / -xdev -name 'ca.key' 2>/dev/null | head -1 | grep . || echo none)"
leaked=$(tr '\0' '\n' </proc/"$pid"/environ | cut -d= -f1 | grep -Ei 'DATABASE|POSTGRES|REDIS|KAFKA|SEAWEED|S3_|IDENTITY|RESEND|SMTP|SESSION|PASSWORD|SECRET' || true)
is "no business secret in the service environment" "" "$leaked"
# Cleanup: an empty work directory and no run cgroup after the runs.
work=$(nsenter --target "$pid" --mount --root ls -A /var/lib/lincodex-runner/work 2>&1)
is "work directory is empty after the runs" "" "$work"
is "no run cgroup is left" "" "$(find "$CGROUP/jails" -mindepth 1 -maxdepth 1 -type d 2>/dev/null)"
# mountinfo of the service: mount options are field 6, the file system type
# follows the separator.
mount=$(awk '$5 == "/var/lib/lincodex-runner/work" {for (i = 7; $i != "-"; i++); print $(i + 1), $6}' /proc/"$pid"/mountinfo)
case ",${mount#* }," in
*,noexec,*) bad "work directory must allow exec ($mount)" ;;
*,nosuid,*nodev,*) [ "${mount%% *}" = tmpfs ] && ok "work directory is a tmpfs with exec, nosuid, nodev ($mount)" || bad "work directory is not a tmpfs ($mount)" ;;
*) bad "work directory lacks nosuid or nodev ($mount)" ;;
esac
# Network: no default route, and every connection the guest starts fails.
is "no default route" "" "$(ip route show default)"
is "IPv6 is off" 1 "$(cat /proc/sys/net/ipv6/conf/all/disable_ipv6)"
probe() { timeout 3 bash -c "exec 3<>/dev/tcp/$1/$2" 2>/dev/null && bad "connect $3 $1:$2 succeeded" || ok "connect $3 $1:$2 is blocked"; }
probe "$HOST_SIDE" 22 "host SSH"
probe "$HOST_SIDE" 53 "host DNS"
probe "${APP_PROBE%:*}" "${APP_PROBE#*:}" "app network"
[ -n "$LAN_GATEWAY" ] && probe "$LAN_GATEWAY" 80 "LAN gateway"
probe 1.1.1.1 443 "internet"
probe 8.8.8.8 53 "internet DNS"
EOF
}
check_guest() {
local output
# The checks arrive on stdin, so this call cannot use guest().
output=$(guest_checks | lxc exec "$vm" -- env SERVICE="$service" SECRETS="$guest_secrets" \
CGROUP="$(cgroup_root "$service")" HOST_SIDE="$host_side" \
LAN_GATEWAY="$lan_gateway" APP_PROBE="${RUNNER_VM_APP_PROBE:-172.29.79.10:80}" bash -s || true)
printf '%s\n' "$output"
failures=$((failures + $(grep -c '^FAIL' <<<"$output" || true)))
}
cmd_up() {
cmd_secrets
cmd_rootfs
vm_exists || cmd_create
cmd_install
cmd_check
}
case ${1:-} in
secrets) cmd_secrets ;;
rootfs) cmd_rootfs ;;
create) cmd_create ;;
install) cmd_install ;;
a16) cmd_a16 ;;
check) cmd_check ;;
up) cmd_up ;;
*)
sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//' >&2
exit 2
;;
esac
+103
View File
@@ -0,0 +1,103 @@
"""Check that the runner VM script keeps the boundary of the production runner.
Production runs the code runner only in an LXD virtual machine with its own
kernel, no shared folder, no Docker socket, and no secret of the core. A
privileged container on the core host must never replace it. These tests
read files and run `bash -n`; they need no LXD, Docker, or network.
"""
from __future__ import annotations
import re
import shutil
import subprocess
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "deploy" / "labs" / "runner-vm.sh"
PRESEED = ROOT / "deploy" / "labs" / "lxd-preseed.yaml"
DEPLOY_MAKEFILE = ROOT / "deploy" / "Makefile"
# Switches that would share the host with the guest or weaken the VM.
FORBIDDEN = {
"a device added to the instance (shared folder or socket)": r"\bdevice\s+add\b",
"a privileged or nested instance": r"security\.(privileged|nesting)\s*=\s*true",
"raw LXC or QEMU settings": r"\braw\.(lxc|qemu)\b",
"a privileged container": r"--privileged",
"a mounted Docker socket": r"-v\s+\S*docker\.sock",
"sudo": r"\bsudo\b",
"the dev plaintext switch": r"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP",
}
# Settings of the runner unit that carry the isolation and the budget.
UNIT_SETTINGS = (
"RootDirectory=$guest_root",
"Delegate=yes",
"ProtectSystem=strict",
"NoNewPrivileges=yes",
"IPAddressDeny=any",
"exec,nosuid,nodev",
"Environment=RUNNER_TLS_CERT_FILE=",
"Environment=RUNNER_API_TOKEN_FILE=",
"Environment=RUNNER_MAX_CONCURRENT_RUNS=1",
)
class RunnerVMScriptTest(unittest.TestCase):
text = SCRIPT.read_text(encoding="utf-8")
# Comments may name what the script never does.
code = "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))
@unittest.skipUnless(shutil.which("bash"), "bash is not installed")
def test_the_script_parses(self) -> None:
subprocess.run(["bash", "-n", str(SCRIPT)], check=True)
def test_the_runner_is_a_virtual_machine_with_only_its_profile(self) -> None:
init = [line for line in self.text.splitlines() if re.search(r"\blxcq init\b", line)]
self.assertEqual(len(init), 1, init)
self.assertIn("--vm", init[0])
self.assertIn('--profile "$vm_profile"', init[0])
self.assertIn("vm_profile=${RUNNER_VM_PROFILE:-lincodex-runner}", self.text)
def test_nothing_shares_the_host_or_weakens_the_vm(self) -> None:
for name, pattern in FORBIDDEN.items():
with self.subTest(switch=name):
self.assertIsNone(re.search(pattern, self.code), name)
def test_the_unit_keeps_the_sandbox_and_budget_settings(self) -> None:
for setting in UNIT_SETTINGS:
with self.subTest(setting=setting):
self.assertIn(setting, self.text)
def test_the_guest_gets_a_static_address_and_no_route(self) -> None:
self.assertIn("dhcp4: false", self.text)
self.assertNotRegex(self.text, r"\b(gateway4|routes|nameservers)\s*:")
self.assertIn("security.devlxd=false", self.text)
def test_secrets_live_outside_the_repository(self) -> None:
self.assertIn("state_dir=${RUNNER_VM_STATE_DIR:-$HOME/lincodex-runner}", self.text)
self.assertIn("umask 077", self.text)
# Only the runner's own TLS pair and token enter the guest; the CA key stays on the host.
pushed = re.findall(r"for file in ([a-z. -]+); do", self.text)
self.assertTrue(pushed)
for files in pushed:
self.assertEqual(files.split(), ["tls.crt", "tls.key", "api-token"])
def test_the_profile_keeps_the_initial_budget(self) -> None:
preseed = PRESEED.read_text(encoding="utf-8")
profile = preseed.split("- name: lincodex-runner\n", 1)[1].split("\n - name:", 1)[0]
self.assertIn('limits.cpu: "2"', profile)
self.assertIn("limits.memory: 3GiB", profile)
self.assertIn("limits.memory.enforce: hard", profile)
self.assertIn("network: lxdbr-runner", profile)
def test_make_targets_call_the_script(self) -> None:
makefile = DEPLOY_MAKEFILE.read_text(encoding="utf-8")
for command in ("up", "secrets", "rootfs", "create", "install", "a16", "check"):
with self.subTest(command=command):
self.assertRegex(makefile, rf"runner-vm-{command}:.*\n\t@bash \"\$\(RUNNER_VM_SCRIPT\)\" {command}\n")
if __name__ == "__main__":
unittest.main()