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

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

No files matched your search

+61 -3
View File
@@ -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/<uuid>` 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=<path to a16-bundle.tar.gz>
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:<version>` 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.
+6
View File
@@ -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.
+4 -1
View File
@@ -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.
+61 -3
View File
@@ -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/<uuid>` по контракту `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:<version>` и `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 прикладных зависимостей сохраняются отдельно.
+6
View File
@@ -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 пока нет.
+4 -1
View File
@@ -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; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.