552 lines
24 KiB
Bash
Executable File
552 lines
24 KiB
Bash
Executable File
#!/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
|