From 53a125f2b5b195d696c9cb98d9b8bdc065c49802 Mon Sep 17 00:00:00 2001 From: shira Date: Sun, 11 Oct 2026 09:45:12 +0300 Subject: [PATCH] feat(deploy): run the code runner in a dedicated LXD VM on the app host --- deploy/Makefile | 36 +- deploy/README.en.md | 1 + deploy/README.md | 1 + deploy/labs/runner-vm.sh | 551 +++++++++++++++++++++++++++++++ deploy/scripts/test_runner_vm.py | 103 ++++++ docs/en/DEPLOY.md | 64 +++- docs/en/SECURITY.md | 6 + docs/en/TESTING.md | 5 +- docs/ru/DEPLOY.md | 64 +++- docs/ru/SECURITY.md | 6 + docs/ru/TESTING.md | 5 +- 11 files changed, 832 insertions(+), 10 deletions(-) create mode 100755 deploy/labs/runner-vm.sh create mode 100644 deploy/scripts/test_runner_vm.py diff --git a/deploy/Makefile b/deploy/Makefile index a137915..826a8d8 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -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=. +.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' diff --git a/deploy/README.en.md b/deploy/README.en.md index f94be04..79a19fb 100644 --- a/deploy/README.en.md +++ b/deploy/README.en.md @@ -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. diff --git a/deploy/README.md b/deploy/README.md index 1049d34..dff2ddd 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -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-набор). diff --git a/deploy/labs/runner-vm.sh b/deploy/labs/runner-vm.sh new file mode 100755 index 0000000..9591ce9 --- /dev/null +++ b/deploy/labs/runner-vm.sh @@ -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 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' /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' &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 diff --git a/deploy/scripts/test_runner_vm.py b/deploy/scripts/test_runner_vm.py new file mode 100644 index 0000000..6f44e2f --- /dev/null +++ b/deploy/scripts/test_runner_vm.py @@ -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() diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 8ac5fdd..df237f0 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -750,11 +750,16 @@ The `runner/Dockerfile` image holds the Go supervisor, nsjail, Python from `pyth `runner-dev-up` creates a local random token in `runner/.dev/api-token` (ignored by Git) when it is missing and starts the service on `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Call it with `Authorization: Bearer $(cat runner/.dev/api-token)` and `PUT /v1/runs/` from the `api/runner/` contract. -### Production (planned) +### Production: the runner VM -The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)), never on the core host and never with the dev file. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. Rolling out the VM, issuing the certificate, storing the token for the backend, and monitoring are not implemented yet. +The runner runs only in the LXD virtual machine `lincodex-runner` on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)): a separate guest kernel, never the core host, never the dev file, and never a privileged container in place of the VM. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. `deploy/labs/runner-vm.sh` builds, updates, and checks the VM on the app host. It runs as a member of the `docker` and `lxd` groups without sudo and does not touch the Docker stack, `ufw`, `wg0`, `awg-lincodex`, or the LXD network, ACL, and profile objects. Monitoring of the VM and connecting the backend to it are not implemented yet; practice stays disabled. -Before practice is enabled, the A16 suite runs on the VM: `make -C runner a16-bundle` on a developer machine, copy `runner/bin/a16-bundle.tar.gz` to the VM, then `sudo sh run-a16.sh` in the unpacked directory with the service's `RUNNER_*` variables. It needs nsjail, Python, and the Go tool directory at the configured paths, a delegated cgroup v2, and a work directory on a tmpfs with `exec`. A non-zero exit status or the verdict `fail` in the report blocks enabling practice. When the runner runs in a container, start the container with an init (`--init` or `init: true`) or under systemd, so that the rare process left after an OOM kill of nsjail is reaped. + make -C runner a16-bundle # on a machine with Go; copy runner/bin/a16-bundle.tar.gz to the host + make -C deploy runner-vm-up # app host: secrets, file system, VM (once), install, checks + make -C deploy runner-vm-a16 A16_BUNDLE= + make -C deploy runner-vm-check + +Before practice is enabled, the A16 suite runs on the VM with `make -C deploy runner-vm-a16`: the bundle runs in a transient systemd unit with the same sandbox settings as the service, and the JSON report lands in `~/lincodex-runner/reports/`. By hand, `sh run-a16.sh` as root in the unpacked bundle with the service's `RUNNER_*` variables does the same; it needs nsjail, Python, and the Go tool directory at the configured paths, a delegated cgroup v2, and a work directory on a tmpfs with `exec`. A non-zero exit status or the verdict `fail` in the report blocks enabling practice. When the runner runs in a container, start the container with an init (`--init` or `init: true`) or under systemd, so that the rare process left after an OOM kill of nsjail is reaped. | Variable | Default | Purpose | | --- | --- | --- | @@ -776,6 +781,59 @@ Before practice is enabled, the A16 suite runs on the VM: `make -C runner a16-bu | `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | `/tmp` size, file size, and open files | | `RUNNER_LOG_LEVEL` | `info` | JSON log level | +#### Steps of the VM script + +| Target | What it does | +| --- | --- | +| `runner-vm-secrets` | In `~/lincodex-runner/secrets` (`RUNNER_VM_STATE_DIR` moves it; directory 0700, files 0600): a private ECDSA P-256 CA for 5 years, a server certificate for `IP:10.80.0.10` with `serverAuth` for 397 days (the next run reissues it when it expires within 30 days), the token (`openssl rand -hex 32`), and the `Authorization` header file for curl. Existing files are kept. The CA key never leaves the host. | +| `runner-vm-rootfs` | `docker build` of `runner/Dockerfile` on the host and `docker export` of its file system to `~/lincodex-runner/runner-rootfs.tar.gz`. The image is not needed afterwards: `docker image rm lincodex-runner-vm:` and `docker builder prune` free the space. | +| `runner-vm-create` | `lxc init images:debian/12/cloud --vm` with only the `lincodex-runner` profile (no default profile, so no other NIC or disk) and `boot.autostart=true`. cloud-init gets a static `10.80.0.10/24` matched by the MAC address, without gateway, DNS, or DHCP. After the first boot cloud-init is disabled and `security.devlxd=false` turns off the guest API. | +| `runner-vm-install` | Masks SSH and the apt and maintenance timers and disables IPv6 in the guest; pushes the file system to `/opt/lincodex-runner/root` and the TLS pair and token to `/etc/lincodex-runner` (root, 0600); writes `lincodex-runner.service`, swaps the root, restarts the service, and waits for `/readyz`. | +| `runner-vm-a16` | Runs the A16 suite in the VM (see above). | +| `runner-vm-check` | Prints PASS or FAIL per check and fails on any FAIL: the instance type, devices, and limits; health, readiness, 401 without or with a wrong token, TLS 1.2 refused, and plain HTTP not served from the host side; a harmless Python and Go run accepted; readiness and 401 from a throwaway curl container on the app network; and in the guest the service, CPUs, memory, delegated cgroup, mounts, Docker socket, secret files, the service environment, an empty work directory and no run cgroup after the runs, no default route, IPv6 off, and blocked connections to the host, the app network, the LAN gateway, and the internet. | + +#### The service in the VM + +systemd runs the Go supervisor with `RootDirectory=/opt/lincodex-runner/root` (the image file system with nsjail, Python, and the Go tools), `Delegate=yes` and `RUNNER_CGROUP_ROOT` set to the unit's own cgroup, and a fresh 256 MiB tmpfs for `RUNNER_WORK_DIR` on every start (`exec`, `nosuid`, `nodev`). It adds `ProtectSystem=strict`, `PrivateTmp`, `NoNewPrivileges`, `MemoryMax=2560M`, `TasksMax=512`, `IPAddressDeny=any` with `IPAddressAllow` for the host side of the bridge and the app subnet, and `RUNNER_MAX_CONCURRENT_RUNS=1`. The secrets directory is bound read-only. systemd reaps a process orphaned by an OOM kill of nsjail, and `KillMode=control-group` stops every process with the service. The VM has no default route; the bridge ACL drops every connection it starts. The backend reaches `https://10.80.0.10:8443` from the app network: Docker masquerades that traffic to the bridge address, and the ACL matches the app subnet before that. The token and `ca.crt` for the backend are in the secrets directory; the stand `.env` does not use them yet. + +#### Verification on the app host + +Checked on 2026-10-11 with the runner at commit `dcf03cb861e2` plus two fixes. The amd64 seccomp fix: kafel names `umount2` as `umount`, and the name `umount2` made nsjail reject the whole policy, so every run ended in `infrastructure_failure`. The A16 fix: `go_thread_bomb` now starts a bounded 256 goroutines blocked in system calls, because its unbounded loop raced the memory limit against the process limit (7 of 20 runs failed); the unbounded goroutine loop moved to the memory case `go_goroutine_bomb`; and the weakened-limit check waits up to 2 s for killed sandbox processes to finish exiting. + +- `runner-vm-check` passes all 49 checks on a VM created from scratch by `runner-vm-up` (about 2 minutes with a cached image). +- A16 in the VM: 20 of 20 runs pass 32 of 32 cases with exit status 0 and `nothing_left_after_runs: true`. +- Resources: the guest sees 2 vCPUs and 2885 MiB and uses about 380 MiB at rest. QEMU on the host holds about 1 GiB after 20 A16 runs; it can grow up to the 3 GiB of guest RAM plus QEMU overhead. At rest the VM takes about 0.6% of one host core. Host memory in use went from 1.8 GiB to 2.9 GiB. The guest root uses 1.4 of 10 GiB. + +#### Removal + +`lxc delete --force lincodex-runner` removes the VM with its file system and its copy of the secrets. `rm -rf ~/lincodex-runner` removes the CA, the token, the reports, and the exported file system on the host. LXD keeps the downloaded Debian image until its cache expires (`lxc image list`). + +## Code runner client + +The backend calls the own code runner (see [the runner](ARCHITECTURE.md#code-runner)) through the `CodeRunner` port. It is off unless `CODE_RUNNER_URL` is set: the backend then selects a disabled runner, logs `code runner selected` with `enabled=false` and a warning, and reports every request as unavailable without running or grading anything. `.env.example` and the Compose file pass every variable below as empty, so a default stack never contacts a runner. Nothing in this build calls the port yet; the settings are validated at startup and the TLS client is built (no network call), so a wrong value fails fast. + +When `CODE_RUNNER_URL` is empty, no other `CODE_RUNNER_*` variable may be set: the backend refuses to start rather than ignore a token. Errors name the setting and never print its value; the startup log names neither the URL nor a secret. + +| Variable | Default | Validation | +| --- | --- | --- | +| `CODE_RUNNER_URL` | empty, runner off | `https` origin of the runner, for example `https://10.80.0.10:8443`: valid host and port, no credentials, path, query, or fragment. Plain HTTP is refused, including for the local dev runner, which serves HTTP; use a TLS runner and its CA. | +| `CODE_RUNNER_TOKEN` | none, required with the URL | The runner's service token (`RUNNER_API_TOKEN`): 32 to 256 printable ASCII characters without spaces. Secret. | +| `CODE_RUNNER_RUN_KEY` | none, required with the URL | Key of the HMAC that derives opaque run IDs, so the runner never sees attempt or submission identifiers: 32 to 256 printable ASCII characters, different from the token. Secret. Generate it with `openssl rand -hex 32`. Changing it makes retries of in-flight submissions start new runs, which the runner forgets after its retention time. | +| `CODE_RUNNER_CA_FILE` or `CODE_RUNNER_CA_PEM` | none, exactly one required with the URL | The CA that signed the runner certificate: a PEM file path inside the container, or the PEM text (`\n` may stand for line breaks). Only this CA is trusted; the system roots are not. Compose does not mount the file, so a deployment either mounts it or uses the inline form. | +| `CODE_RUNNER_SERVER_NAME` | the host of the URL | Name the certificate is verified against, for a runner addressed by an IP its certificate does not list. Verification stays on. | +| `CODE_RUNNER_REQUEST_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one request. A timeout is an infrastructure error, never a verdict. | + +The connection uses TLS 1.3 only and follows no redirects or environment proxies. The deployment of the runner VM, the certificate, and storing the token for the backend are described in the runner sections above and are not part of this build; the token and the run key belong in the server environment or a secret store and are never committed. + +Checking a real runner. The unit tests run against a local protocol stand-in. To run fixed harmless programs (Python and Go, an accepted answer, a wrong answer, a syntax error, and a wrong token) on a prepared runner, export the same variables the backend uses and run: + + export CODE_RUNNER_URL=https://10.80.0.10:8443 + export CODE_RUNNER_TOKEN=... # from the secret store + export CODE_RUNNER_CA_FILE=/path/to/runner-ca.pem + make -C backend test-code-runner-live + +`CODE_RUNNER_SERVER_NAME` is honored too. The target stops with an error when the three variables are unset, and the same tests are skipped by a plain `go test` because they run only when `CODE_RUNNER_LIVE_URL` is set. A pass proves that the client, the TLS settings, the token, and the runner agree on the protocol and that the runner grades the fixed programs as expected; it does not replace the A16 suite. + ## Services and images Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately. diff --git a/docs/en/SECURITY.md b/docs/en/SECURITY.md index 984d5f6..c9afdd6 100644 --- a/docs/en/SECURITY.md +++ b/docs/en/SECURITY.md @@ -47,3 +47,9 @@ For any further exception, scope it to the specific finding and affected input, CI runs `make -C security test check` for source checks and `make -C security images` for images, and includes both jobs in its required aggregate result. Reports are uploaded as artifacts with a 14-day retention period, including when checks fail. Gitleaks redacts secret values, but reports can still reveal repository paths and dependency details; restrict artifact access accordingly. The local Semgrep rules are a bounded frontend/ML rule set, not a complete application audit. Scanner results depend on the actual checkout, rule versions, vulnerability databases, build inputs, and time of execution. Checked-in workflows do not prove that a GitHub run occurred or that the current tree is free of findings. Record actual results when preparing a release; see [TESTING.md](TESTING.md) for other validation boundaries. + +## Code runner VM + +The code runner executes untrusted candidate code, so production runs it only in the LXD VM `lincodex-runner` (see [DEPLOY.md](DEPLOY.md#production-the-runner-vm)). The boundary has three layers: nsjail with seccomp, namespaces, cgroup v2 limits, and no network for the program; a separate guest kernel; and the bridge ACL, which lets only the app network and the host side open TCP 8443 and drops every connection the guest starts. The VM holds only its own TLS pair and API token. The CA key and the database, mail, storage, and identity secrets never enter it, and it has no shared folder, no Docker socket, and no guest API (`security.devlxd=false`). + +`make -C deploy check-runner-vm` checks the VM script without LXD. On the app host, `make -C deploy runner-vm-check` checks the running VM and `make -C deploy runner-vm-a16` runs the hostile-program suite in it. These checks do not cover vulnerabilities of the kernel, QEMU, KVM, nsjail, or LXD, side channels, or the host itself: the `lxd` group is equivalent to root on the host, and its members can open a root shell in the guest through the LXD agent. The token is a shared secret without automatic rotation: to replace it, remove `api-token` from the secrets directory, run `runner-vm-secrets` and `runner-vm-install`, and give the backend the new value. The VM has no monitoring yet. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 397a2fb..24ecef8 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -592,6 +592,9 @@ The tests do not run the Make targets against a real stack. A manual check on a | make -C runner test-a16 | The A16 suite only, with a report in `runner/.reports/`; `A16_ENV` passes `RUNNER_*` variables | | make -C runner a16-bundle | A bundle of the A16 suite for the runner host | | make -C deploy check-runner-dev | Dev switches stay out of production files | +| make -C deploy check-runner-vm | The runner VM script keeps the VM boundary: a VM with only its profile, no shared device, privileged or raw setting, sudo, or dev switch, the sandbox and budget settings of the unit, a static address without a route, and secrets outside the repository | +| make -C deploy runner-vm-check | On the app host: the live runner VM, see [DEPLOY.md](DEPLOY.md#steps-of-the-vm-script) | +| make -C deploy runner-vm-a16 | On the app host: the A16 suite in the runner VM with the service's sandbox settings | First, `test-sandbox` runs the reference solutions of `runner/testdata/judge/manifest.json` on three tasks with one public and three hidden groups: correct and incorrect Python and Go solutions get the expected outcome of every group (`exact` and `tokens`; `numbers` on fractional answers with an absolute and a relative tolerance; `custom` with a Python and a Go checker in nsjail); Go code with a compile error gives `compile_error` with a `main.go:` message and no test runs. The test also checks that a group stops at its first failed test, hidden tests carry no diagnostic, and the run directories and cgroups are removed. @@ -619,7 +622,7 @@ The report records the runner version (`git describe`), the kernel (`uname`), th Checking the suite itself: `TestA16WeakenedProcessLimitIsDetected` raises the process limit to 4096 in a test copy of the configuration and requires the processes cases to fail. The same by hand: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` exits with an error and a `fail` report on exactly the three processes cases. -On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A16_GOARCH=amd64` by default) builds `runner/bin/a16-bundle.tar.gz` with the test binary, the fixtures, and `run-a16.sh`; on the VM it is unpacked and started with `sudo sh run-a16.sh [report.json]` and the same `RUNNER_*` variables as the service. The script does not use the network and writes only the report and the work directory. +On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A16_GOARCH=amd64` by default) builds `runner/bin/a16-bundle.tar.gz` with the test binary, the fixtures, and `run-a16.sh`; on the VM it is unpacked and started with `sudo sh run-a16.sh [report.json]` and the same `RUNNER_*` variables as the service. The script does not use the network and writes only the report and the work directory. On the production VM, `make -C deploy runner-vm-a16` does this in a transient systemd unit with the sandbox settings of the service; the results of 2026-10-11 (20 of 20 runs pass with exit status 0) are in [DEPLOY.md](DEPLOY.md#verification-on-the-app-host). What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index d35591c..12f37bb 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -752,11 +752,16 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml `runner-dev-up` создает локальный случайный токен в `runner/.dev/api-token` (игнорируется Git), если его нет, и запускает сервис на `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Вызов: `Authorization: Bearer $(cat runner/.dev/api-token)` и `PUT /v1/runs/` по контракту `api/runner/`. -### Production (запланировано) +### Production: VM исполнителя -Исполнитель работает только в VM `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)), никогда на core-хосте и никогда с dev-файлом. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). Раскатка VM, выпуск сертификата, хранение токена на стороне backend и мониторинг еще не реализованы. +Исполнитель работает только в виртуальной машине LXD `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)): отдельное гостевое ядро, никогда core-хост, никогда dev-файл и никогда привилегированный контейнер вместо VM. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). `deploy/labs/runner-vm.sh` собирает, обновляет и проверяет VM на хосте приложения. Он работает от участника групп `docker` и `lxd` без sudo и не трогает Docker-стек, `ufw`, `wg0`, `awg-lincodex` и объекты LXD: сеть, ACL и профиль. Мониторинг VM и подключение к ней backend еще не реализованы; практика остается выключенной. -Перед включением практики на VM запускается набор A16: `make -C runner a16-bundle` на машине разработчика, перенос `runner/bin/a16-bundle.tar.gz` на VM, затем `sudo sh run-a16.sh` в распакованном каталоге с переменными `RUNNER_*` сервиса. Нужны nsjail, Python и каталог Go-инструментов по путям конфигурации, делегированная cgroup v2 и рабочий каталог на tmpfs с `exec`. Код выхода не 0 или вердикт `fail` в отчете блокируют включение практики. Если runner работает в контейнере, контейнер запускают с init (`--init` или `init: true`) или под systemd, чтобы редкий процесс, оставшийся после OOM-kill nsjail, был забран. + make -C runner a16-bundle # на машине с Go; перенести runner/bin/a16-bundle.tar.gz на хост + make -C deploy runner-vm-up # хост приложения: секреты, файловая система, VM (один раз), установка, проверки + make -C deploy runner-vm-a16 A16_BUNDLE=<путь к a16-bundle.tar.gz> + make -C deploy runner-vm-check + +Перед включением практики на VM запускается набор A16 командой `make -C deploy runner-vm-a16`: пакет работает во временном unit systemd с теми же настройками песочницы, что и у сервиса, а JSON-отчет попадает в `~/lincodex-runner/reports/`. Вручную то же делает `sh run-a16.sh` от root в распакованном пакете с переменными `RUNNER_*` сервиса; нужны nsjail, Python и каталог Go-инструментов по путям конфигурации, делегированная cgroup v2 и рабочий каталог на tmpfs с `exec`. Код выхода не 0 или вердикт `fail` в отчете блокируют включение практики. Если runner работает в контейнере, контейнер запускают с init (`--init` или `init: true`) или под systemd, чтобы редкий процесс, оставшийся после OOM-kill nsjail, был забран. | Переменная | По умолчанию | Назначение | | --- | --- | --- | @@ -778,6 +783,59 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml | `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | Размер `/tmp`, размер файла и открытые файлы | | `RUNNER_LOG_LEVEL` | `info` | Уровень JSON-логов | +#### Шаги скрипта VM + +| Цель | Что делает | +| --- | --- | +| `runner-vm-secrets` | В `~/lincodex-runner/secrets` (`RUNNER_VM_STATE_DIR` меняет каталог; каталог 0700, файлы 0600): частный CA на ECDSA P-256 на 5 лет, серверный сертификат для `IP:10.80.0.10` с `serverAuth` на 397 дней (следующий запуск перевыпускает его, если до истечения меньше 30 дней), токен (`openssl rand -hex 32`) и файл заголовка `Authorization` для curl. Существующие файлы сохраняются. Ключ CA не покидает хост. | +| `runner-vm-rootfs` | `docker build` из `runner/Dockerfile` на хосте и `docker export` его файловой системы в `~/lincodex-runner/runner-rootfs.tar.gz`. Сам образ дальше не нужен: `docker image rm lincodex-runner-vm:` и `docker builder prune` освобождают место. | +| `runner-vm-create` | `lxc init images:debian/12/cloud --vm` только с профилем `lincodex-runner` (без профиля default, поэтому других NIC и дисков нет) и `boot.autostart=true`. cloud-init получает статический `10.80.0.10/24` с привязкой к MAC-адресу, без шлюза, DNS и DHCP. После первой загрузки cloud-init отключается, а `security.devlxd=false` выключает гостевой API. | +| `runner-vm-install` | Маскирует SSH, таймеры apt и обслуживания и отключает IPv6 в госте; переносит файловую систему в `/opt/lincodex-runner/root`, TLS-пару и токен в `/etc/lincodex-runner` (root, 0600); пишет `lincodex-runner.service`, подменяет root, перезапускает сервис и ждет `/readyz`. | +| `runner-vm-a16` | Запускает набор A16 в VM (см. выше). | +| `runner-vm-check` | Печатает PASS или FAIL по каждой проверке и падает при любом FAIL: тип инстанса, устройства и лимиты; health, readiness, 401 без токена и с неверным токеном, отказ TLS 1.2 и отсутствие plain HTTP со стороны хоста; принятый безобидный прогон на Python и Go; readiness и 401 из одноразового контейнера с curl в сети приложения; в госте сервис, CPU, память, делегированная cgroup, точки монтирования, сокет Docker, файлы секретов, окружение сервиса, пустой рабочий каталог и отсутствие cgroup прогонов после прогонов, отсутствие маршрута по умолчанию, выключенный IPv6 и заблокированные соединения к хосту, сети приложения, шлюзу LAN и интернету. | + +#### Сервис в VM + +systemd запускает Go-супервизор с `RootDirectory=/opt/lincodex-runner/root` (файловая система образа с nsjail, Python и Go-инструментами), `Delegate=yes` и `RUNNER_CGROUP_ROOT`, указывающим на собственную cgroup unit, и новым tmpfs на 256 MiB для `RUNNER_WORK_DIR` при каждом старте (`exec`, `nosuid`, `nodev`). Добавлены `ProtectSystem=strict`, `PrivateTmp`, `NoNewPrivileges`, `MemoryMax=2560M`, `TasksMax=512`, `IPAddressDeny=any` с `IPAddressAllow` для стороны хоста на мосту и подсети приложения и `RUNNER_MAX_CONCURRENT_RUNS=1`. Каталог секретов подключен только для чтения. systemd забирает процесс, осиротевший после OOM-kill nsjail, а `KillMode=control-group` останавливает все процессы вместе с сервисом. У VM нет маршрута по умолчанию; ACL моста отбрасывает любое соединение, которое она начинает. Backend обращается к `https://10.80.0.10:8443` из сети приложения: Docker маскирует этот трафик адресом моста, а ACL сопоставляет подсеть приложения до этого. Токен и `ca.crt` для backend лежат в каталоге секретов; `.env` стенда их пока не использует. + +#### Проверка на хосте приложения + +Проверено 2026-10-11 на runner из коммита `dcf03cb861e2` с двумя исправлениями. Исправление seccomp для amd64: kafel называет `umount2` именем `umount`, а имя `umount2` заставляло nsjail отвергать всю политику, поэтому каждый прогон заканчивался `infrastructure_failure`. Исправление A16: `go_thread_bomb` теперь запускает ограниченные 256 горутин, заблокированных в системных вызовах, потому что его неограниченный цикл устраивал гонку лимита памяти и лимита процессов (7 из 20 прогонов падали); неограниченный цикл горутин перенесен в случай памяти `go_goroutine_bomb`; проверка с ослабленным лимитом ждет до 2 с, пока убитые процессы песочницы завершатся. + +- `runner-vm-check` проходит все 49 проверок на VM, созданной с нуля через `runner-vm-up` (около 2 минут с образом в кеше). +- A16 в VM: 20 из 20 прогонов проходят 32 из 32 случаев с кодом выхода 0 и `nothing_left_after_runs: true`. +- Ресурсы: гость видит 2 vCPU и 2885 MiB и в покое использует около 380 MiB. QEMU на хосте занимает около 1 GiB после 20 прогонов A16; он может вырасти до 3 GiB гостевой памяти плюс накладные расходы QEMU. В покое VM берет около 0,6% одного ядра хоста. Занятая память хоста выросла с 1,8 GiB до 2,9 GiB. Корень гостя занимает 1,4 из 10 GiB. + +#### Удаление + +`lxc delete --force lincodex-runner` удаляет VM вместе с ее файловой системой и копией секретов. `rm -rf ~/lincodex-runner` удаляет CA, токен, отчеты и экспортированную файловую систему на хосте. LXD хранит скачанный образ Debian до истечения кеша (`lxc image list`). + +## Клиент исполнителя кода + +Backend вызывает собственный исполнитель кода (см. [исполнитель](ARCHITECTURE.md#исполнитель-кода)) через порт `CodeRunner`. Он выключен, пока не задан `CODE_RUNNER_URL`: тогда backend выбирает отключенного исполнителя, пишет в лог `code runner selected` с `enabled=false` и предупреждение, а каждый запрос сообщает как недоступный, ничего не запуская и не оценивая. `.env.example` и Compose-файл передают все переменные ниже пустыми, поэтому стек по умолчанию никогда не обращается к исполнителю. В этой сборке порт пока никто не вызывает; настройки проверяются при запуске и TLS-клиент создается (без сетевого вызова), поэтому неверное значение обнаруживается сразу. + +Когда `CODE_RUNNER_URL` пуст, ни одна другая переменная `CODE_RUNNER_*` задаваться не должна: backend отказывается запускаться, а не молча игнорирует токен. Ошибки называют настройку и не печатают ее значение; в стартовом логе нет ни URL, ни секретов. + +| Переменная | По умолчанию | Проверка | +| --- | --- | --- | +| `CODE_RUNNER_URL` | пусто, исполнитель выключен | Origin исполнителя по `https`, например `https://10.80.0.10:8443`: корректные хост и порт, без учетных данных, пути, query и fragment. Plain HTTP отклоняется, в том числе для локального dev-исполнителя, который обслуживает HTTP; нужен исполнитель с TLS и его CA. | +| `CODE_RUNNER_TOKEN` | нет, обязателен вместе с URL | Сервисный токен исполнителя (`RUNNER_API_TOKEN`): от 32 до 256 печатных ASCII-символов без пробелов. Секрет. | +| `CODE_RUNNER_RUN_KEY` | нет, обязателен вместе с URL | Ключ HMAC, из которого выводятся непрозрачные ID прогонов, чтобы исполнитель не видел идентификаторов попыток и отправок: от 32 до 256 печатных ASCII-символов, не равен токену. Секрет. Создайте его командой `openssl rand -hex 32`. После смены повторы текущих отправок начинают новые прогоны, которые исполнитель забывает по истечении хранения. | +| `CODE_RUNNER_CA_FILE` или `CODE_RUNNER_CA_PEM` | нет, нужен ровно один вместе с URL | CA, подписавший сертификат исполнителя: путь к PEM-файлу внутри контейнера или текст PEM (`\n` может заменять переводы строк). Доверяется только этот CA, системные корни - нет. Compose не монтирует файл, поэтому развертывание либо монтирует его, либо использует встроенную форму. | +| `CODE_RUNNER_SERVER_NAME` | хост из URL | Имя, по которому проверяется сертификат, для исполнителя с адресом IP, которого нет в сертификате. Проверка остается включенной. | +| `CODE_RUNNER_REQUEST_TIMEOUT` | `10s` | Go-длительность от `1s` до `1m`; ограничивает один запрос. Таймаут - ошибка инфраструктуры, а не вердикт. | + +Соединение использует только TLS 1.3 и не следует редиректам и прокси из окружения. Развертывание VM исполнителя, сертификат и хранение токена для backend описаны в разделах об исполнителе выше и не входят в эту сборку; токен и ключ прогонов хранятся в окружении сервера или хранилище секретов и никогда не коммитятся. + +Проверка настоящего исполнителя. Модульные тесты работают с локальной заменой протокола. Чтобы запустить на подготовленном исполнителе фиксированные безвредные программы (Python и Go, верный ответ, неверный ответ, синтаксическая ошибка и неверный токен), задайте те же переменные, что использует backend, и выполните: + + export CODE_RUNNER_URL=https://10.80.0.10:8443 + export CODE_RUNNER_TOKEN=... # из хранилища секретов + export CODE_RUNNER_CA_FILE=/path/to/runner-ca.pem + make -C backend test-code-runner-live + +`CODE_RUNNER_SERVER_NAME` тоже учитывается. Цель завершается ошибкой, если три переменные не заданы, а те же тесты при обычном `go test` пропускаются, потому что запускаются только при заданном `CODE_RUNNER_LIVE_URL`. Успех доказывает, что клиент, настройки TLS, токен и исполнитель согласованы по протоколу и что исполнитель оценивает фиксированные программы ожидаемо; он не заменяет набор A16. + ## Сервисы и образы Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно. diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index 5d82a76..8fbc804 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -47,3 +47,9 @@ Gitleaks требует полный Git checkout. Отсутствие репо CI запускает `make -C security test check` для исходников и `make -C security images` для образов и включает обе проверки в обязательный общий результат. Отчеты загружаются как artifacts со сроком хранения 14 дней, в том числе при ошибке проверки. Gitleaks скрывает значения секретов, но отчеты могут раскрывать пути репозитория и сведения о зависимостях; доступ к artifacts должен это учитывать. Локальные правила Semgrep покрывают ограниченный набор случаев для frontend и ML, а не полный аудит приложения. Результаты сканеров зависят от checkout, версий правил, баз уязвимостей, входов сборки и времени запуска. Наличие workflow в репозитории не подтверждает запуск в GitHub или отсутствие находок в текущих файлах. При подготовке релиза фиксируйте фактические результаты; другие границы валидации описаны в [TESTING.md](TESTING.md). + +## VM исполнителя кода + +Исполнитель запускает недоверенный код кандидатов, поэтому в production он работает только в VM LXD `lincodex-runner` (см. [DEPLOY.md](DEPLOY.md#production-vm-исполнителя)). У границы три слоя: nsjail с seccomp, пространствами имен, лимитами cgroup v2 и без сети для программы; отдельное гостевое ядро; ACL моста, который разрешает открыть TCP 8443 только сети приложения и стороне хоста и отбрасывает любое соединение, начатое гостем. В VM есть только ее собственная TLS-пара и токен API. Ключ CA и секреты базы данных, почты, хранилища и identity в нее не попадают, общих папок, сокета Docker и гостевого API (`security.devlxd=false`) у нее нет. + +`make -C deploy check-runner-vm` проверяет скрипт VM без LXD. На хосте приложения `make -C deploy runner-vm-check` проверяет работающую VM, а `make -C deploy runner-vm-a16` запускает в ней набор враждебных программ. Эти проверки не покрывают уязвимости ядра, QEMU, KVM, nsjail и LXD, побочные каналы и сам хост: группа `lxd` равносильна root на хосте, и ее участники могут открыть root-shell в госте через агент LXD. Токен - общий секрет без автоматической ротации: чтобы заменить его, удалите `api-token` из каталога секретов, запустите `runner-vm-secrets` и `runner-vm-install` и передайте backend новое значение. Мониторинга у VM пока нет. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index a871bf0..80e7af3 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -592,6 +592,9 @@ Vitest работает в Node без DOM, поэтому ограничени | make -C runner test-a16 | Только набор A16 с отчетом в `runner/.reports/`; `A16_ENV` передает переменные `RUNNER_*` | | make -C runner a16-bundle | Пакет набора A16 для запуска на хосте исполнителя | | make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы | +| make -C deploy check-runner-vm | Скрипт VM исполнителя сохраняет границу VM: VM только со своим профилем, без общих устройств, привилегированных и raw-настроек, sudo и dev-переключателей, настройки песочницы и бюджета в unit, статический адрес без маршрута и секреты вне репозитория | +| make -C deploy runner-vm-check | На хосте приложения: работающая VM исполнителя, см. [DEPLOY.md](DEPLOY.md#шаги-скрипта-vm) | +| make -C deploy runner-vm-a16 | На хосте приложения: набор A16 в VM исполнителя с настройками песочницы сервиса | Сначала `test-sandbox` прогоняет эталонные решения `runner/testdata/judge/manifest.json` на трех задачах с одной публичной и тремя скрытыми группами: верные и неверные решения на Python и Go получают ожидаемый исход каждой группы (`exact` и `tokens`; `numbers` на дробных ответах с абсолютным и относительным допуском; `custom` с checker на Python и на Go в nsjail); Go-код с ошибкой компиляции дает `compile_error` с сообщением `main.go:` и ни одного запущенного теста. Тест также проверяет, что группа останавливается на первом проваленном тесте, у скрытых тестов нет диагностики, а каталоги и cgroup прогонов удалены. @@ -619,7 +622,7 @@ Vitest работает в Node без DOM, поэтому ограничени Проверка самого набора: `TestA16WeakenedProcessLimitIsDetected` поднимает лимит процессов до 4096 в тестовой копии конфигурации и требует, чтобы случаи категории processes провалились. Тот же эффект вручную: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` завершается ошибкой и отчетом `fail` ровно по трем случаям processes. -На хосте исполнителя набор запускается из пакета: `make -C runner a16-bundle` (по умолчанию `A16_GOARCH=amd64`) собирает `runner/bin/a16-bundle.tar.gz` с тестовым бинарником, fixtures и `run-a16.sh`; на VM его распаковывают и запускают `sudo sh run-a16.sh [report.json]` с теми же переменными `RUNNER_*`, что и у сервиса. Скрипт не обращается к сети и пишет только отчет и рабочий каталог. +На хосте исполнителя набор запускается из пакета: `make -C runner a16-bundle` (по умолчанию `A16_GOARCH=amd64`) собирает `runner/bin/a16-bundle.tar.gz` с тестовым бинарником, fixtures и `run-a16.sh`; на VM его распаковывают и запускают `sudo sh run-a16.sh [report.json]` с теми же переменными `RUNNER_*`, что и у сервиса. Скрипт не обращается к сети и пишет только отчет и рабочий каталог. На production VM то же делает `make -C deploy runner-vm-a16` во временном unit systemd с настройками песочницы сервиса; результаты 2026-10-11 (20 из 20 прогонов проходят с кодом выхода 0) приведены в [DEPLOY.md](DEPLOY.md#проверка-на-хосте-приложения). Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.