feat(runner): add the own code runner contract, client and nsjail service

This commit is contained in:
shira committed 2026-10-11 08:23:42 +03:00
1 parent 5e1db37746
commit cdf6bcbb91
109 files changed
+24084 -28

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
.git
.idea
.vscode
.DS_Store
.env
.env.*
.dev/
bin/
coverage.*
**/*.test
**/*.out
+11
View File
@@ -0,0 +1,11 @@
/bin/
/.dev/
# Go build and test output
*.exe
*.test
*.out
*.prof
*.cover
*.pprof
coverage.*
+136
View File
@@ -0,0 +1,136 @@
version: "2"
run:
timeout: 5m
tests: true
# Lint the isolation tests too; they compile only with this tag on Linux.
build-tags:
- sandbox
linters:
default: standard
enable:
- asasalint
- asciicheck
- bidichk
- bodyclose
- contextcheck
- copyloopvar
- durationcheck
- embeddedstructfieldcheck
- errname
- errorlint
- exhaustive
- exptostd
- fatcontext
- gocheckcompilerdirectives
- gochecknoinits
- gochecksumtype
- gocritic
- gocyclo
- gosec
- goprintffuncname
- inamedparam
- iotamixing
- loggercheck
- makezero
- mirror
- misspell
- musttag
- nakedret
- nilerr
- nilnesserr
- noctx
- nolintlint
- prealloc
- predeclared
- reassign
- revive
- sloglint
- tagalign
- testableexamples
- testifylint
- thelper
- unconvert
- unparam
- wastedassign
- whitespace
settings:
gocyclo:
min-complexity: 15
govet:
enable-all: true
disable:
- fieldalignment
- shadow
revive:
rules:
- name: blank-imports
- name: context-as-argument
- name: context-keys-type
- name: error-return
- name: error-strings
- name: error-naming
- name: var-declaration
- name: range
- name: receiver-naming
- name: time-naming
- name: indent-error-flow
- name: errorf
- name: empty-block
- name: superfluous-else
- name: unused-parameter
- name: unreachable-code
- name: redefines-builtin-id
nolintlint:
allow-unused: false
require-explanation: true
require-specific: true
gosec:
excludes:
- G104
staticcheck:
checks:
- all
testifylint:
enable-all: true
disable:
- go-require
exclusions:
generated: strict
paths:
- internal/api/
presets:
- comments
- common-false-positives
rules:
# Error locations use actual Go identifiers, including exported type names.
- linters:
- staticcheck
text: 'ST1005: error strings should not be capitalized'
source: '(fmt\.Errorf|errors\.New)\("[A-Z][A-Za-z0-9]*\.[A-Za-z0-9]+ - '
- path: _test\.go
linters:
- gocyclo
- gosec
- errcheck
- dupl
- path: _test\.go
text: net/http/httptest\.NewRequest must not be called
linters:
- noctx
formatters:
enable:
- gofmt
- goimports
exclusions:
generated: strict
paths:
- internal/api/
issues:
max-issues-per-linter: 0
max-same-issues: 0
+45
View File
@@ -0,0 +1,45 @@
# Production image of the code runner. It runs only on the dedicated runner
# host or VM, never on the core application host; see docs/en/DEPLOY.md.
#
# Base images are build arguments so that a release build can pin each one to
# the digest it resolved; the defaults keep the agreed tags.
ARG GO_IMAGE=golang:1.26.9-alpine
ARG RUNTIME_IMAGE=python:alpine
FROM ${GO_IMAGE} AS build
# Never download another Go toolchain: a go.mod that asks for a newer Go
# fails the build instead of silently replacing 1.26.9.
ENV GOTOOLCHAIN=local
WORKDIR /src/runner
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/lincodex-runner ./cmd/runner
FROM ${RUNTIME_IMAGE}
# The runtime is the Python base plus nsjail. Package installers are removed,
# so a jailed program finds no pip, and nothing is installed at run time.
RUN apk upgrade --no-cache \
&& apk add --no-cache nsjail \
&& python -m pip uninstall --yes pip \
&& python -c "import ensurepip, shutil; shutil.rmtree(ensurepip.__path__[0])" \
&& install -d -m 0711 /var/lib/lincodex-runner/work
# The binary lives outside /usr and /lib, which are the only host paths
# mounted into a jail.
COPY --from=build /out/lincodex-runner /opt/lincodex-runner/lincodex-runner
# The supervisor needs root on its dedicated host to create namespaces, map
# the sandbox user, and write its delegated cgroup. Jailed programs run as
# uid 99999 without capabilities, with no_new_privs and a seccomp policy.
USER 0:0
EXPOSE 8443
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["/opt/lincodex-runner/lincodex-runner", "healthcheck"]
ENTRYPOINT ["/opt/lincodex-runner/lincodex-runner"]
+26
View File
@@ -0,0 +1,26 @@
# DEVELOPMENT AND CI ONLY: the isolation test image. It adds the compiled
# isolation tests and the hostile fixtures to a locally built runner image and
# is started by make -C runner test-sandbox with the privileges that nsjail
# needs inside Docker. It is never a release or production image.
ARG GO_IMAGE=golang:1.26.9-alpine
ARG RUNNER_IMAGE=lincodex-runner-dev:local
FROM ${GO_IMAGE} AS build
ENV GOTOOLCHAIN=local
WORKDIR /src/runner
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/isolation.test ./internal/isolationtest
FROM ${RUNNER_IMAGE}
COPY --from=build /out/isolation.test /opt/lincodex-runner-tests/isolation.test
COPY testdata/hostile /opt/lincodex-runner-tests/testdata/hostile
ENV RUNNER_HOSTILE_FIXTURES=/opt/lincodex-runner-tests/testdata/hostile
HEALTHCHECK NONE
ENTRYPOINT ["/opt/lincodex-runner-tests/isolation.test", "-test.v", "-test.count=1"]
+107
View File
@@ -0,0 +1,107 @@
SHELL := /usr/bin/env bash
.DEFAULT_GOAL := help
GO ?= go
GO_TOOL := $(GO) tool
DOCKER ?= docker
API_DIR := $(abspath ../api)
API_PREPARED ?= 0
# The runner and its sandbox are Linux-only, so lint analyzes Linux code. The
# linter binary is built for the host first; GOOS then selects only the
# analyzed packages.
LINT_GOOS ?= linux
GOLANGCI_LINT := bin/golangci-lint
RUNNER_IMAGE ?= lincodex-runner-dev:local
SANDBOX_TEST_IMAGE ?= lincodex-runner-sandbox-test:local
OGEN_ARGS := -config codegen/ogen.yml --package api --clean ../api/runner/openapi.bundle.yml
##@ Build
.PHONY: build
build: ## Build the runner binary for Linux
@mkdir -p bin
CGO_ENABLED=0 GOOS=linux $(GO) build -buildvcs=false -trimpath -o bin/lincodex-runner ./cmd/runner
.PHONY: deps install
deps: ## Download pinned Go module dependencies
$(GO) mod download
install: deps ## Install module-pinned Go tools without global changes
@$(GO) version
@$(GO_TOOL) ogen --version
@$(GO_TOOL) golangci-lint version
.PHONY: tidy
tidy: ## Tidy application and tool dependencies
$(GO) mod tidy
.PHONY: clean
clean: ## Remove local build and test artifacts
rm -rf bin coverage.out
##@ Code generation
.PHONY: generate gen
generate gen: ## Generate the ogen server from the code runner contract
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(GO_TOOL) ogen --target internal/api $(OGEN_ARGS)
.PHONY: check-generated
check-generated: ## Check the generated server against the bundled contract without rewriting it
@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-check.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
$(GO_TOOL) ogen --target "$$temporary_dir" $(OGEN_ARGS) >/dev/null 2>&1; \
diff -r internal/api "$$temporary_dir"
##@ Format, lint, and test
.PHONY: $(GOLANGCI_LINT)
$(GOLANGCI_LINT):
@mkdir -p bin
$(GO) build -o $(GOLANGCI_LINT) github.com/golangci/golangci-lint/v2/cmd/golangci-lint
.PHONY: fmt
fmt: $(GOLANGCI_LINT) ## Format Go sources
GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt ./...
.PHONY: fmt-check
fmt-check: $(GOLANGCI_LINT) ## Check Go formatting without modifying files
@unformatted=$$(gofmt -l $$(find . -name '*.go' -type f -not -path './bin/*')); \
if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi
@formatter_diff=$$(GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt --diff ./...); \
if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi
.PHONY: lint
lint: $(GOLANGCI_LINT) ## Run golangci-lint for Linux, including the isolation tests
GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) run ./...
.PHONY: test
test: ## Run unit tests with the race detector; they need no sandbox
$(GO) test -race -count=1 ./...
.PHONY: image
image: ## Build the runner image for local development
$(DOCKER) build --file Dockerfile --tag "$(RUNNER_IMAGE)" .
# DEVELOPMENT ONLY: --privileged gives nsjail namespaces and a writable
# cgroup v2 tree inside the Docker Desktop VM. Production runs the runner on
# its dedicated VM and never uses this target.
.PHONY: test-sandbox
test-sandbox: image ## Run the hostile-program isolation tests in a privileged dev container
$(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --tag "$(SANDBOX_TEST_IMAGE)" .
$(DOCKER) run --rm --privileged --cgroupns=private --network=none \
--tmpfs /var/lib/lincodex-runner/work:size=64m,mode=0711 \
"$(SANDBOX_TEST_IMAGE)"
.PHONY: check
check: ## Run formatting, build, unit, generated drift, and lint checks
$(MAKE) --no-print-directory fmt-check
$(MAKE) --no-print-directory build
$(MAKE) --no-print-directory test
$(MAKE) --no-print-directory check-generated
$(MAKE) --no-print-directory lint
##@ Help
.PHONY: help
help: ## Show available targets
@awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n make -C runner <target>\n"} /^[a-zA-Z0-9_-]+:.*##/ {printf " %-16s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST)
+17
View File
@@ -0,0 +1,17 @@
# Code runner
[Русский](README.md) | English
A separate Go service that runs untrusted candidate code in nsjail and checks it against public and hidden tests. It currently supports Python 3 and the `exact` and `tokens` checkers. The backend calls it through the internal `api/runner/` contract over TLS with a bearer token; no backend use case calls it yet.
- `cmd/runner/` is the entry point and the container `healthcheck`.
- `internal/sandbox/` holds nsjail, cgroup v2, seccomp, run directories, and stopping on limits.
- `internal/judge/` holds languages, the syntax check step, and test and group outcomes.
- `internal/checker/` holds the checker interface and the `exact` and `tokens` comparisons.
- `internal/jobs/` keeps runs in memory, makes them idempotent by run ID, and bounds concurrent runs.
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
- `internal/isolationtest/` and `testdata/hostile/` are the isolation tests and the shared hostile programs.
From the repository root, `make -C runner check` runs formatting, build, unit tests, the generated code check, and lint; `make -C runner test-sandbox` builds the image and runs the isolation tests in a privileged dev container. Local start: `make -C deploy runner-dev-up` (development only).
Production: the service runs only in the dedicated runner VM, never on the core host. More: [deployment](../docs/en/DEPLOY.md#code-runner), [architecture](../docs/en/ARCHITECTURE.md#code-runner), and [checks](../docs/en/TESTING.md#code-runner-tests).
+17
View File
@@ -0,0 +1,17 @@
# Исполнитель кода
Русский | [English](README.en.md)
Отдельный Go-сервис, который запускает недоверенный код кандидата в nsjail и проверяет его на публичных и скрытых тестах. Сейчас поддерживается Python 3; checker `exact` и `tokens`. Backend вызывает его по внутреннему контракту `api/runner/` с TLS и bearer-токеном; ни один usecase backend пока не использует его.
- `cmd/runner/` - точка входа и `healthcheck` для контейнера.
- `internal/sandbox/` - nsjail, cgroup v2, seccomp, рабочие каталоги и остановка по лимитам.
- `internal/judge/` - языки, шаг проверки синтаксиса, исходы тестов и групп.
- `internal/checker/` - интерфейс checker и сравнения `exact` и `tokens`.
- `internal/jobs/` - прогоны в памяти, идемпотентность по run ID и лимит параллельных прогонов.
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
- `internal/isolationtest/` и `testdata/hostile/` - тесты изоляции и общие враждебные программы.
Из корня: `make -C runner check` запускает форматирование, сборку, unit-тесты, проверку generated-кода и lint; `make -C runner test-sandbox` собирает образ и запускает тесты изоляции в привилегированном dev-контейнере. Локальный запуск: `make -C deploy runner-dev-up` (только для разработки).
Production: сервис работает только в отдельной VM исполнителя, никогда на core-хосте. Подробнее: [развертывание](../docs/ru/DEPLOY.md#исполнитель-кода), [архитектура](../docs/ru/ARCHITECTURE.md#исполнитель-кода) и [проверки](../docs/ru/TESTING.md#тесты-исполнителя-кода).
+19
View File
@@ -0,0 +1,19 @@
// Command runner serves the code runner API.
package main
import (
"fmt"
"os"
"lincodex/runner/internal/app"
)
func main() {
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
os.Exit(app.Healthcheck())
}
if err := app.Run(); err != nil {
fmt.Fprintln(os.Stderr, "runner:", err)
os.Exit(1)
}
}
+5
View File
@@ -0,0 +1,5 @@
generator:
features:
disable:
- paths/client
- webhooks/client
+243
View File
@@ -0,0 +1,243 @@
module lincodex/runner
go 1.26.9
tool (
github.com/golangci/golangci-lint/v2/cmd/golangci-lint
github.com/ogen-go/ogen/cmd/ogen
)
require (
github.com/go-faster/errors v0.8.0
github.com/go-faster/jx v1.2.0
github.com/google/uuid v1.6.0
github.com/ogen-go/ogen v1.24.0
go.opentelemetry.io/otel v1.45.0
go.opentelemetry.io/otel/metric v1.45.0
go.opentelemetry.io/otel/trace v1.45.0
)
require (
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect
4d63.com/gochecknoglobals v0.2.2 // indirect
charm.land/lipgloss/v2 v2.0.6 // indirect
codeberg.org/chavacava/garif v0.2.1 // indirect
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect
dev.gaijin.team/go/golib v0.8.1 // indirect
github.com/4meepo/tagalign v1.4.4 // indirect
github.com/Abirdcfly/dupword v0.1.8 // indirect
github.com/AdminBenni/iota-mixing v1.0.0 // indirect
github.com/AlwxSin/noinlineerr v1.0.6 // indirect
github.com/Antonboom/errname v1.1.2 // indirect
github.com/Antonboom/nilnil v1.1.2 // indirect
github.com/Antonboom/testifylint v1.6.4 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
github.com/Djarvur/go-err113 v0.1.1 // indirect
github.com/Masterminds/semver/v3 v3.5.0 // indirect
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
github.com/alexkohler/prealloc v1.1.0 // indirect
github.com/alfatraining/structtag v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect
github.com/alingse/nilnesserr v0.2.0 // indirect
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.3 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
github.com/bombsimon/wsl/v5 v5.9.0 // indirect
github.com/breml/bidichk v0.3.3 // indirect
github.com/breml/errchkjson v0.4.1 // indirect
github.com/butuzov/ireturn v0.4.1 // indirect
github.com/butuzov/mirror v1.3.3 // indirect
github.com/catenacyber/perfsprint v0.10.1 // indirect
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.11 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/ckaznocha/intrange v0.3.1 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/curioswitch/go-reassign v0.3.0 // indirect
github.com/daixiang0/gci v0.13.7 // indirect
github.com/dave/dst v0.27.3 // indirect
github.com/denis-tingaikin/go-header v0.5.0 // indirect
github.com/dlclark/regexp2 v1.12.0 // indirect
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
github.com/ettle/strcase v0.2.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/firefart/nonamedreturns v1.0.8 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/ghostiam/protogetter v1.0.1 // indirect
github.com/go-critic/go-critic v0.15.0 // indirect
github.com/go-faster/yaml v0.4.6 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-toolsmith/astcast v1.1.0 // indirect
github.com/go-toolsmith/astcopy v1.1.0 // indirect
github.com/go-toolsmith/astequal v1.2.0 // indirect
github.com/go-toolsmith/astfmt v1.1.0 // indirect
github.com/go-toolsmith/astp v1.1.0 // indirect
github.com/go-toolsmith/strparse v1.1.0 // indirect
github.com/go-toolsmith/typep v1.1.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godoc-lint/godoc-lint v0.11.4 // indirect
github.com/gofrs/flock v0.13.1 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golangci/asciicheck v0.5.0 // indirect
github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
github.com/golangci/go-printf-func-name v0.1.1 // indirect
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect
github.com/golangci/golangci-lint/v2 v2.14.0 // indirect
github.com/golangci/golines v0.15.0 // indirect
github.com/golangci/misspell v0.8.0 // indirect
github.com/golangci/plugin-module-register v0.1.2 // indirect
github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/gordonklaus/ineffassign v0.2.0 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
github.com/gostaticanalysis/comment v1.5.0 // indirect
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
github.com/gostaticanalysis/nilerr v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jgautheron/goconst v1.11.0 // indirect
github.com/jjti/go-spancheck v0.6.5 // indirect
github.com/julz/importas v0.2.0 // indirect
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
github.com/kisielk/errcheck v1.20.0 // indirect
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
github.com/kulti/thelper v0.7.1 // indirect
github.com/kunwardeep/paralleltest v1.0.15 // indirect
github.com/ldez/exptostd v0.4.5 // indirect
github.com/ldez/gomoddirectives v0.10.0 // indirect
github.com/ldez/grignotin v0.10.1 // indirect
github.com/ldez/structtags v0.6.1 // indirect
github.com/ldez/tagliatelle v0.8.0 // indirect
github.com/ldez/usetesting v0.5.0 // indirect
github.com/leonklingele/grouper v1.1.2 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/macabu/inamedparam v0.2.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
github.com/manuelarte/funcorder v0.6.0 // indirect
github.com/maratori/testableexamples v1.0.1 // indirect
github.com/maratori/testpackage v1.1.2 // indirect
github.com/matoous/godox v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-runewidth v0.0.24 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mgechev/revive v1.17.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moricho/tparallel v0.3.2 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/nishanths/exhaustive v0.13.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/quasilyte/go-ruleguard v0.4.5 // indirect
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
github.com/quasilyte/gogrep v0.5.0 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/raeperd/recvcheck v0.3.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.16.0 // indirect
github.com/ryancurrah/gomodguard v1.4.1 // indirect
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
github.com/securego/gosec/v2 v2.29.0 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/sirupsen/logrus v1.10.2 // indirect
github.com/sivchari/containedctx v1.0.3 // indirect
github.com/sonatard/noctx v0.5.1 // indirect
github.com/sourcegraph/go-diff v0.9.0 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/tetafro/godot v1.5.6 // indirect
github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect
github.com/timonwong/loggercheck v0.12.0 // indirect
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
github.com/ultraware/funlen v0.2.0 // indirect
github.com/ultraware/whitespace v0.2.0 // indirect
github.com/uudashr/gocognit v1.2.1 // indirect
github.com/uudashr/iface v1.5.1 // indirect
github.com/xen0n/gosmopolitan v1.3.0 // indirect
github.com/xo/terminfo v1.0.0 // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
github.com/yeya24/promlinter v0.3.0 // indirect
github.com/ykadowak/zerologlint v0.1.5 // indirect
github.com/yuin/goldmark v1.8.2 // indirect
gitlab.com/bosi/decorder v0.4.2 // indirect
go-simpler.org/musttag v0.14.0 // indirect
go-simpler.org/sloglint v0.12.0 // indirect
go.augendre.info/arangolint v0.4.0 // indirect
go.augendre.info/fatcontext v0.10.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.59.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/tools v0.50.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
honnef.co/go/tools v0.8.1 // indirect
mvdan.cc/gofumpt v0.12.0 // indirect
mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect
)
+1007
View File
File diff suppressed because it is too large. Load diff
+258
View File
@@ -0,0 +1,258 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"strings"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/ogenregex"
"github.com/ogen-go/ogen/otelogen"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
var regexMap = map[string]ogenregex.Regexp{
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[a-z0-9][a-z0-9_-]{0,31}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]{0,31}$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
}
var (
// Allocate option closure once.
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
)
type (
optionFunc[C any] func(*C)
otelOptionFunc func(*otelConfig)
)
type otelConfig struct {
TracerProvider trace.TracerProvider
Tracer trace.Tracer
MeterProvider metric.MeterProvider
Meter metric.Meter
Attributes []attribute.KeyValue
}
func (cfg *otelConfig) initOTEL() {
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
if cfg.MeterProvider == nil {
cfg.MeterProvider = otel.GetMeterProvider()
}
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
trace.WithInstrumentationVersion(otelogen.SemVersion()),
)
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
metric.WithInstrumentationVersion(otelogen.SemVersion()),
)
}
// ErrorHandler is error handler.
type ErrorHandler = ogenerrors.ErrorHandler
type serverConfig struct {
otelConfig
NotFound http.HandlerFunc
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
ErrorHandler ErrorHandler
Prefix string
Middleware Middleware
MaxMultipartMemory int64
}
// ServerOption is server config option.
type ServerOption interface {
applyServer(*serverConfig)
}
var _ ServerOption = (optionFunc[serverConfig])(nil)
func (o optionFunc[C]) applyServer(c *C) {
o(c)
}
var _ ServerOption = (otelOptionFunc)(nil)
func (o otelOptionFunc) applyServer(c *serverConfig) {
o(&c.otelConfig)
}
func newServerConfig(opts ...ServerOption) serverConfig {
cfg := serverConfig{
NotFound: http.NotFound,
MethodNotAllowed: nil,
ErrorHandler: ogenerrors.DefaultErrorHandler,
Middleware: nil,
MaxMultipartMemory: 32 << 20, // 32 MB
}
for _, opt := range opts {
opt.applyServer(&cfg)
}
cfg.initOTEL()
return cfg
}
type baseServer struct {
cfg serverConfig
requests metric.Int64Counter
errors metric.Int64Counter
duration metric.Float64Histogram
}
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
s.cfg.NotFound(w, r)
}
type notAllowedParams struct {
allowedMethods string
allowedHeaders map[string]string
acceptPost string
acceptPatch string
}
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
h := w.Header()
isOptions := r.Method == "OPTIONS"
if isOptions {
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
if params.allowedHeaders != nil {
m := r.Header.Get("Access-Control-Request-Method")
if m != "" {
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
if ok {
h.Set("Access-Control-Allow-Headers", allowedHeaders)
}
}
}
if params.acceptPost != "" {
h.Set("Accept-Post", params.acceptPost)
}
if params.acceptPatch != "" {
h.Set("Accept-Patch", params.acceptPatch)
}
}
if s.cfg.MethodNotAllowed != nil {
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
return
}
status := http.StatusNoContent
if !isOptions {
h.Set("Allow", params.allowedMethods)
status = http.StatusMethodNotAllowed
}
w.WriteHeader(status)
}
func (cfg serverConfig) baseServer() (s baseServer, err error) {
s = baseServer{cfg: cfg}
if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil {
return s, err
}
if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil {
return s, err
}
if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil {
return s, err
}
return s, nil
}
// Option is config option.
type Option interface {
ServerOption
}
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
//
// If none is specified, the global provider is used.
func WithTracerProvider(provider trace.TracerProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.TracerProvider = provider
}
})
}
// WithMeterProvider specifies a meter provider to use for creating a meter.
//
// If none is specified, the otel.GetMeterProvider() is used.
func WithMeterProvider(provider metric.MeterProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.MeterProvider = provider
}
})
}
// WithAttributes specifies default otel attributes.
func WithAttributes(attributes ...attribute.KeyValue) Option {
return otelOptionFunc(func(cfg *otelConfig) {
cfg.Attributes = attributes
})
}
// WithNotFound specifies Not Found handler to use.
func WithNotFound(notFound http.HandlerFunc) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if notFound != nil {
cfg.NotFound = notFound
}
})
}
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if methodNotAllowed != nil {
cfg.MethodNotAllowed = methodNotAllowed
}
})
}
// WithErrorHandler specifies error handler to use.
func WithErrorHandler(h ErrorHandler) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if h != nil {
cfg.ErrorHandler = h
}
})
}
// WithPathPrefix specifies server path prefix.
func WithPathPrefix(prefix string) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
cfg.Prefix = prefix
})
}
// WithMiddleware specifies middlewares to use.
func WithMiddleware(m ...Middleware) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
switch len(m) {
case 0:
cfg.Middleware = nil
case 1:
cfg.Middleware = m[0]
default:
cfg.Middleware = middleware.ChainMiddlewares(m...)
}
})
}
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
// File parts which can't be stored in memory will be stored on disk in temporary files.
func WithMaxMultipartMemory(max int64) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if max > 0 {
cfg.MaxMultipartMemory = max
}
})
}
+736
View File
@@ -0,0 +1,736 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"net/http"
"time"
"github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/otelogen"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
"go.opentelemetry.io/otel/trace"
)
type codeRecorder struct {
http.ResponseWriter
status int
}
func (c *codeRecorder) WriteHeader(status int) {
c.status = status
c.ResponseWriter.WriteHeader(status)
}
func (c *codeRecorder) Unwrap() http.ResponseWriter {
return c.ResponseWriter
}
// handleGetRunRequest handles GetRun operation.
//
// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its
// retention time or lost in a restart.
//
// GET /v1/runs/{run_id}
func (s *Server) handleGetRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRun"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/v1/runs/{run_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetRunOperation,
ID: "GetRun",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityBearerAuth(ctx, GetRunOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "BearerAuth",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:BearerAuth", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetRunParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response *RunStatus
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetRunOperation,
OperationSummary: "Read the state and, when finished, the per-group result of a run.",
OperationID: "GetRun",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "run_id",
In: "path",
}: params.RunID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetRunParams
Response = *RunStatus
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetRunParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetRun(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetRun(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetRunResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetRunnerHealthzRequest handles GetRunnerHealthz operation.
//
// Check whether the runner process is responding.
//
// GET /healthz
func (s *Server) handleGetRunnerHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRunnerHealthz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/healthz"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunnerHealthzOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
)
var rawBody []byte
var response *RunnerHealthResponse
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetRunnerHealthzOperation,
OperationSummary: "Check whether the runner process is responding.",
OperationID: "GetRunnerHealthz",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = *RunnerHealthResponse
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetRunnerHealthz(ctx)
return response, err
},
)
} else {
response, err = s.h.GetRunnerHealthz(ctx)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetRunnerHealthzResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetRunnerReadyzRequest handles GetRunnerReadyz operation.
//
// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at
// startup and the process is not draining. A busy runner is still ready; busy is reported by
// SubmitRun.
//
// GET /readyz
func (s *Server) handleGetRunnerReadyzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRunnerReadyz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/readyz"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunnerReadyzOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
)
var rawBody []byte
var response GetRunnerReadyzRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetRunnerReadyzOperation,
OperationSummary: "Check whether the sandbox is prepared to accept runs.",
OperationID: "GetRunnerReadyz",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = GetRunnerReadyzRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetRunnerReadyz(ctx)
return response, err
},
)
} else {
response, err = s.h.GetRunnerReadyz(ctx)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetRunnerReadyzResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleSubmitRunRequest handles SubmitRun operation.
//
// Idempotent by `run_id`:
//
// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`;
// - the same ID with the same payload answers 200 with the current state of that run, including the
// finished result, without running it again;
// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy`
// with Retry-After; nothing is stored, so the caller retries with the same ID.
//
// Payloads are compared by a SHA-256 fingerprint of the decoded request. The runner keeps runs only in
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
// in a run, test IDs are unique in a group, and the number of tests multiplied by
// `limits.time_limit_ms` does not exceed 300000.
//
// PUT /v1/runs/{run_id}
func (s *Server) handleSubmitRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("SubmitRun"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/v1/runs/{run_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), SubmitRunOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: SubmitRunOperation,
ID: "SubmitRun",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityBearerAuth(ctx, SubmitRunOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "BearerAuth",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:BearerAuth", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeSubmitRunParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeSubmitRunRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response SubmitRunRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: SubmitRunOperation,
OperationSummary: "Start a sandboxed run of one source against its test groups.",
OperationID: "SubmitRun",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "run_id",
In: "path",
}: params.RunID,
},
Raw: r,
}
type (
Request = *RunRequest
Params = SubmitRunParams
Response = SubmitRunRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackSubmitRunParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.SubmitRun(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.SubmitRun(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeSubmitRunResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
+10
View File
@@ -0,0 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package api
type GetRunnerReadyzRes interface {
getRunnerReadyzRes()
}
type SubmitRunRes interface {
submitRunRes()
}
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"go.opentelemetry.io/otel/attribute"
)
// Labeler is used to allow adding custom attributes to the server request metrics.
type Labeler struct {
attrs []attribute.KeyValue
}
// Add attributes to the Labeler.
func (l *Labeler) Add(attrs ...attribute.KeyValue) {
l.attrs = append(l.attrs, attrs...)
}
// AttributeSet returns the attributes added to the Labeler as an attribute.Set.
func (l *Labeler) AttributeSet() attribute.Set {
return attribute.NewSet(l.attrs...)
}
type labelerContextKey struct{}
// LabelerFromContext retrieves the Labeler from the provided context, if present.
//
// If no Labeler was found in the provided context a new, empty Labeler is returned and the second
// return value is false. In this case it is safe to use the Labeler but any attributes added to
// it will not be used.
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok {
return l, true
}
return &Labeler{}, false
}
func contextWithLabeler(ctx context.Context, l *Labeler) context.Context {
return context.WithValue(ctx, labelerContextKey{}, l)
}
+10
View File
@@ -0,0 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/ogen-go/ogen/middleware"
)
// Middleware is middleware type.
type Middleware = middleware.Middleware
+13
View File
@@ -0,0 +1,13 @@
// Code generated by ogen, DO NOT EDIT.
package api
// OperationName is the ogen operation name
type OperationName = string
const (
GetRunOperation OperationName = "GetRun"
GetRunnerHealthzOperation OperationName = "GetRunnerHealthz"
GetRunnerReadyzOperation OperationName = "GetRunnerReadyz"
SubmitRunOperation OperationName = "SubmitRun"
)
+150
View File
@@ -0,0 +1,150 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"net/url"
"github.com/go-faster/errors"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
)
// GetRunParams is parameters of GetRun operation.
type GetRunParams struct {
// Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and
// must not encode a candidate, attempt, or task identifier.
RunID uuid.UUID
}
func unpackGetRunParams(packed middleware.Parameters) (params GetRunParams) {
{
key := middleware.ParameterKey{
Name: "run_id",
In: "path",
}
params.RunID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetRunParams(args [1]string, argsEscaped bool, r *http.Request) (params GetRunParams, _ error) {
// Decode path: run_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "run_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.RunID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "run_id",
In: "path",
Err: err,
}
}
return params, nil
}
// SubmitRunParams is parameters of SubmitRun operation.
type SubmitRunParams struct {
// Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and
// must not encode a candidate, attempt, or task identifier.
RunID uuid.UUID
}
func unpackSubmitRunParams(packed middleware.Parameters) (params SubmitRunParams) {
{
key := middleware.ParameterKey{
Name: "run_id",
In: "path",
}
params.RunID = packed[key].(uuid.UUID)
}
return params
}
func decodeSubmitRunParams(args [1]string, argsEscaped bool, r *http.Request) (params SubmitRunParams, _ error) {
// Decode path: run_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "run_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.RunID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "run_id",
In: "path",
Err: err,
}
}
return params, nil
}
@@ -0,0 +1,94 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"bytes"
"io"
"mime"
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/validate"
)
func (s *Server) decodeSubmitRunRequest(r *http.Request) (
req *RunRequest,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request RunRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
@@ -0,0 +1,159 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/uri"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
func encodeGetRunResponse(response *RunStatus, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
}
func encodeGetRunnerHealthzResponse(response *RunnerHealthResponse, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
}
func encodeGetRunnerReadyzResponse(response GetRunnerReadyzRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *GetRunnerReadyzOK:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetRunnerReadyzServiceUnavailable:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(503)
span.SetStatus(codes.Error, http.StatusText(503))
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeSubmitRunResponse(response SubmitRunRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SubmitRunOK:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SubmitRunAccepted:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(202)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RunnerBusyHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.Int32ToString(response.RetryAfter))
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(503)
span.SetStatus(codes.Error, http.StatusText(503))
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/problem+json")
code := response.StatusCode
if code == 0 {
// Set default status code.
code = http.StatusOK
}
w.WriteHeader(code)
if code >= http.StatusInternalServerError {
span.SetStatus(codes.Error, http.StatusText(code))
}
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
if code >= http.StatusInternalServerError {
return errors.Wrapf(ht.ErrInternalServerErrorResponse, "code: %d, message: %s", code, http.StatusText(code))
}
return nil
}
+359
View File
@@ -0,0 +1,359 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"net/url"
"strings"
"github.com/ogen-go/ogen/uri"
)
var (
rn2AllowedHeaders = map[string]string{
"GET": "Authorization",
"PUT": "Authorization,Content-Type",
}
)
func (s *Server) cutPrefix(path string) (string, bool) {
prefix := s.cfg.Prefix
if prefix == "" {
return path, true
}
if !strings.HasPrefix(path, prefix) {
// Prefix doesn't match.
return "", false
}
// Cut prefix from the path.
return strings.TrimPrefix(path, prefix), true
}
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
// calling handler that matches the path or returning not found error.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
elem := r.URL.Path
elemIsEscaped := false
if rawPath := r.URL.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
elemIsEscaped = strings.ContainsRune(elem, '%')
}
}
elem, ok := s.cutPrefix(elem)
if !ok || len(elem) == 0 {
s.notFound(w, r)
return
}
args := [1]string{}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'h': // Prefix: "healthz"
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetRunnerHealthzRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'r': // Prefix: "readyz"
if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetRunnerReadyzRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'v': // Prefix: "v1/runs/"
if l := len("v1/runs/"); len(elem) >= l && elem[0:l] == "v1/runs/" {
elem = elem[l:]
} else {
break
}
// Param: "run_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetRunRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
case "PUT":
s.handleSubmitRunRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn2AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
}
s.notFound(w, r)
}
// Route is route object.
type Route struct {
name string
summary string
operationID string
operationGroup string
pathPattern string
count int
args [1]string
}
// Name returns ogen operation name.
//
// It is guaranteed to be unique and not empty.
func (r Route) Name() string {
return r.name
}
// Summary returns OpenAPI summary.
func (r Route) Summary() string {
return r.summary
}
// OperationID returns OpenAPI operationId.
func (r Route) OperationID() string {
return r.operationID
}
// OperationGroup returns the x-ogen-operation-group value.
func (r Route) OperationGroup() string {
return r.operationGroup
}
// PathPattern returns OpenAPI path.
func (r Route) PathPattern() string {
return r.pathPattern
}
// Args returns parsed arguments.
func (r Route) Args() []string {
return r.args[:r.count]
}
// FindRoute finds Route for given method and path.
//
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
func (s *Server) FindRoute(method, path string) (Route, bool) {
return s.FindPath(method, &url.URL{Path: path})
}
// FindPath finds Route for given method and URL.
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
var (
elem = u.Path
args = r.args
)
if rawPath := u.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
}
defer func() {
for i, arg := range r.args[:r.count] {
if unescaped, err := url.PathUnescape(arg); err == nil {
r.args[i] = unescaped
}
}
}()
}
elem, ok := s.cutPrefix(elem)
if !ok {
return r, false
}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'h': // Prefix: "healthz"
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetRunnerHealthzOperation
r.summary = "Check whether the runner process is responding."
r.operationID = "GetRunnerHealthz"
r.operationGroup = ""
r.pathPattern = "/healthz"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'r': // Prefix: "readyz"
if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetRunnerReadyzOperation
r.summary = "Check whether the sandbox is prepared to accept runs."
r.operationID = "GetRunnerReadyz"
r.operationGroup = ""
r.pathPattern = "/readyz"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'v': // Prefix: "v1/runs/"
if l := len("v1/runs/"); len(elem) >= l && elem[0:l] == "v1/runs/" {
elem = elem[l:]
} else {
break
}
// Param: "run_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetRunOperation
r.summary = "Read the state and, when finished, the per-group result of a run."
r.operationID = "GetRun"
r.operationGroup = ""
r.pathPattern = "/v1/runs/{run_id}"
r.args = args
r.count = 1
return r, true
case "PUT":
r.name = SubmitRunOperation
r.summary = "Start a sandboxed run of one source against its test groups."
r.operationID = "SubmitRun"
r.operationGroup = ""
r.pathPattern = "/v1/runs/{run_id}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
}
return r, false
}
File diff suppressed because it is too large. Load diff
+80
View File
@@ -0,0 +1,80 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"net/http"
"strings"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/ogenerrors"
)
// SecurityHandler is handler for security parameters.
type SecurityHandler interface {
// HandleBearerAuth handles bearerAuth security.
// Shared random service token sent as `Authorization: Bearer <token>` over TLS. The runner compares it
// in constant time and never logs it. Rotation replaces the secret on both sides; there are no
// per-user tokens.
HandleBearerAuth(ctx context.Context, operationName OperationName, t BearerAuth) (context.Context, error)
}
func findAuthorization(h http.Header, prefix string) (string, bool) {
v, ok := h["Authorization"]
if !ok {
return "", false
}
for _, vv := range v {
scheme, value, ok := strings.Cut(vv, " ")
if !ok || !strings.EqualFold(scheme, prefix) {
continue
}
return value, true
}
return "", false
}
// operationRolesBearerAuth is a private map storing roles per operation.
var operationRolesBearerAuth = map[string][]string{
GetRunOperation: []string{},
SubmitRunOperation: []string{},
}
// GetRolesForBearerAuth returns the required roles for the given operation.
//
// This is useful for authorization scenarios where you need to know which roles
// are required for an operation.
//
// Example:
//
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
//
// Returns nil if the operation has no role requirements or if the operation is unknown.
func GetRolesForBearerAuth(operation string) []string {
roles, ok := operationRolesBearerAuth[operation]
if !ok {
return nil
}
// Return a copy to prevent external modification
result := make([]string, len(roles))
copy(result, roles)
return result
}
func (s *Server) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
var t BearerAuth
token, ok := findAuthorization(req.Header, "Bearer")
if !ok {
return ctx, false, nil
}
t.Token = token
t.Roles = operationRolesBearerAuth[operationName]
rctx, err := s.sec.HandleBearerAuth(ctx, operationName, t)
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return rctx, true, err
}
+77
View File
@@ -0,0 +1,77 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
)
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// GetRun implements GetRun operation.
//
// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its
// retention time or lost in a restart.
//
// GET /v1/runs/{run_id}
GetRun(ctx context.Context, params GetRunParams) (*RunStatus, error)
// GetRunnerHealthz implements GetRunnerHealthz operation.
//
// Check whether the runner process is responding.
//
// GET /healthz
GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error)
// GetRunnerReadyz implements GetRunnerReadyz operation.
//
// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at
// startup and the process is not draining. A busy runner is still ready; busy is reported by
// SubmitRun.
//
// GET /readyz
GetRunnerReadyz(ctx context.Context) (GetRunnerReadyzRes, error)
// SubmitRun implements SubmitRun operation.
//
// Idempotent by `run_id`:
//
// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`;
// - the same ID with the same payload answers 200 with the current state of that run, including the
// finished result, without running it again;
// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy`
// with Retry-After; nothing is stored, so the caller retries with the same ID.
//
// Payloads are compared by a SHA-256 fingerprint of the decoded request. The runner keeps runs only in
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
// in a run, test IDs are unique in a group, and the number of tests multiplied by
// `limits.time_limit_ms` does not exceed 300000.
//
// PUT /v1/runs/{run_id}
SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (SubmitRunRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
NewError(ctx context.Context, err error) *ProblemStatusCode
}
// Server implements http server based on OpenAPI v3 specification and
// calls Handler to handle requests.
type Server struct {
h Handler
sec SecurityHandler
baseServer
}
// NewServer creates new Server.
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
s, err := newServerConfig(opts...).baseServer()
if err != nil {
return nil, err
}
return &Server{
h: h,
sec: sec,
baseServer: s,
}, nil
}
@@ -0,0 +1,75 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
ht "github.com/ogen-go/ogen/http"
)
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
type UnimplementedHandler struct{}
var _ Handler = UnimplementedHandler{}
// GetRun implements GetRun operation.
//
// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its
// retention time or lost in a restart.
//
// GET /v1/runs/{run_id}
func (UnimplementedHandler) GetRun(ctx context.Context, params GetRunParams) (r *RunStatus, _ error) {
return r, ht.ErrNotImplemented
}
// GetRunnerHealthz implements GetRunnerHealthz operation.
//
// Check whether the runner process is responding.
//
// GET /healthz
func (UnimplementedHandler) GetRunnerHealthz(ctx context.Context) (r *RunnerHealthResponse, _ error) {
return r, ht.ErrNotImplemented
}
// GetRunnerReadyz implements GetRunnerReadyz operation.
//
// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at
// startup and the process is not draining. A busy runner is still ready; busy is reported by
// SubmitRun.
//
// GET /readyz
func (UnimplementedHandler) GetRunnerReadyz(ctx context.Context) (r GetRunnerReadyzRes, _ error) {
return r, ht.ErrNotImplemented
}
// SubmitRun implements SubmitRun operation.
//
// Idempotent by `run_id`:
//
// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`;
// - the same ID with the same payload answers 200 with the current state of that run, including the
// finished result, without running it again;
// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy`
// with Retry-After; nothing is stored, so the caller retries with the same ID.
//
// Payloads are compared by a SHA-256 fingerprint of the decoded request. The runner keeps runs only in
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
// in a run, test IDs are unique in a group, and the number of tests multiplied by
// `limits.time_limit_ms` does not exceed 300000.
//
// PUT /v1/runs/{run_id}
func (UnimplementedHandler) SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (r SubmitRunRes, _ error) {
return r, ht.ErrNotImplemented
}
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
func (UnimplementedHandler) NewError(ctx context.Context, err error) (r *ProblemStatusCode) {
r = new(ProblemStatusCode)
return r
}
File diff suppressed because it is too large. Load diff
+189
View File
@@ -0,0 +1,189 @@
// Package app wires the runner and controls its lifecycle.
package app
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"lincodex/runner/internal/config"
"lincodex/runner/internal/jobs"
"lincodex/runner/internal/judge"
"lincodex/runner/internal/sandbox"
"lincodex/runner/internal/server"
)
// HTTP server bounds. Request bodies are bounded separately by
// RUNNER_MAX_REQUEST_BYTES.
const (
readHeaderTimeout = 5 * time.Second
readTimeout = 30 * time.Second
writeTimeout = 30 * time.Second
idleTimeout = 60 * time.Second
maxHeaderBytes = 16 << 10
healthcheckWait = 2 * time.Second
)
// Sandbox settings that belong to the runner image rather than to a
// deployment.
const (
stderrCaptureBytes = 16 << 10
pollInterval = 10 * time.Millisecond
)
// sandboxMounts are the read-only host paths the interpreter needs: the
// Python installation under /usr/local and the musl loader and libraries.
var sandboxMounts = []string{"/usr", "/lib"}
// sandboxEnv is the whole environment of a jailed program.
var sandboxEnv = []string{
"PATH=/usr/local/bin:/usr/bin:/bin",
"HOME=" + sandbox.ScratchPath,
"LANG=C.UTF-8",
"PYTHONIOENCODING=utf-8",
"PYTHONDONTWRITEBYTECODE=1",
}
// Run starts the runner and blocks until SIGINT or SIGTERM.
func Run() error {
cfg, err := config.Load()
if err != nil {
return err
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
executor, err := sandbox.New(SandboxConfig(cfg))
if err != nil {
return fmt.Errorf("app.Run - prepare sandbox: %w", err)
}
evaluator := judge.New(executor, logger, judge.Python3(cfg.PythonPath))
manager, err := jobs.NewManager(jobs.Config{
MaxConcurrent: cfg.MaxConcurrentRuns,
ResultTTL: cfg.ResultTTL,
MaxRetained: cfg.MaxRetainedRuns,
}, evaluator, logger)
if err != nil {
return err
}
handler := server.NewHandler(manager, evaluator.Supports, func() bool { return !manager.Draining() }, cfg.RetryAfter, logger)
httpHandler, err := server.New(handler, cfg.APIToken, cfg.MaxRequestBytes, logger)
if err != nil {
return err
}
httpServer := &http.Server{
Addr: cfg.ListenAddress,
Handler: httpHandler,
ReadHeaderTimeout: readHeaderTimeout,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
MaxHeaderBytes: maxHeaderBytes,
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13},
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn),
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
serveErr := make(chan error, 1)
go func() {
serveErr <- serve(httpServer, cfg, logger)
}()
logger.InfoContext(ctx, "runner started",
slog.String("address", cfg.ListenAddress),
slog.Bool("tls", !cfg.AllowPlaintextHTTP),
slog.Int("max_concurrent_runs", cfg.MaxConcurrentRuns),
)
select {
case err := <-serveErr:
return errors.Join(err, manager.Close(context.Background()))
case <-ctx.Done():
}
logger.InfoContext(ctx, "runner stopping")
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
return errors.Join(httpServer.Shutdown(shutdownCtx), manager.Close(shutdownCtx))
}
func serve(httpServer *http.Server, cfg config.Config, logger *slog.Logger) error {
var err error
if cfg.AllowPlaintextHTTP {
logger.Warn("serving plaintext HTTP; this switch is for local development only")
err = httpServer.ListenAndServe()
} else {
err = httpServer.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile)
}
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return fmt.Errorf("app.serve - listen: %w", err)
}
// SandboxConfig returns the sandbox settings of the runner for cfg.
func SandboxConfig(cfg config.Config) sandbox.Config {
return sandbox.Config{
NsjailPath: cfg.NsjailPath,
CgroupRoot: cfg.CgroupRoot,
WorkRoot: cfg.WorkDir,
SandboxUID: cfg.SandboxUID,
SandboxGID: cfg.SandboxUID,
MaxProcesses: cfg.MaxProcesses,
MemoryOverheadBytes: cfg.MemoryOverheadBytes,
TmpfsBytes: cfg.TmpfsBytes,
FileSizeBytes: cfg.FileSizeBytes,
OpenFiles: cfg.OpenFiles,
StderrCaptureBytes: stderrCaptureBytes,
ReadOnlyMounts: sandboxMounts,
Env: sandboxEnv,
PollInterval: pollInterval,
}
}
// Healthcheck requests /healthz of the local process and returns the exit
// status for a container health check. It sends no token.
func Healthcheck() int {
cfg, err := config.Load()
if err != nil {
return 1
}
_, port, err := net.SplitHostPort(cfg.ListenAddress)
if err != nil {
return 1
}
scheme := "https"
if cfg.AllowPlaintextHTTP {
scheme = "http"
}
client := &http.Client{
Timeout: healthcheckWait,
Transport: &http.Transport{
// The probe talks to its own process over loopback and sends no
// secret; the certificate names the private host, not 127.0.0.1.
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS13}, //nolint:gosec // Loopback liveness probe only.
},
}
ctx, cancel := context.WithTimeout(context.Background(), healthcheckWait)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, scheme+"://"+net.JoinHostPort("127.0.0.1", port)+"/healthz", http.NoBody)
if err != nil {
return 1
}
response, err := client.Do(request)
if err != nil {
return 1
}
_ = response.Body.Close() // Only the status matters.
if response.StatusCode != http.StatusOK {
return 1
}
return 0
}
+93
View File
@@ -0,0 +1,93 @@
// Package checker compares the output of a sandboxed program with the expected
// output of a test.
//
// A checker is selected by a Spec. Kinds that need parameters, such as a float
// tolerance, add fields to Spec; kinds that need to run code, such as a custom
// checker program, implement Checker with their own sandbox and use the
// context and the error result for cancellation and infrastructure failures.
package checker
import (
"bytes"
"context"
"fmt"
)
// Kind names a comparison rule of the runner contract.
type Kind string
const (
// Exact accepts texts that are equal after line-ending and trailing
// whitespace normalization.
Exact Kind = "exact"
// Tokens accepts texts with the same sequence of whitespace-separated
// tokens.
Tokens Kind = "tokens"
)
// Spec selects and parameterizes a checker.
type Spec struct {
Kind Kind `json:"kind"`
}
// Input is everything a checker may look at for one test.
type Input struct {
TestInput []byte
Expected []byte
Actual []byte
}
// Checker decides whether the actual output of a test is accepted.
type Checker interface {
// Check reports whether the output is accepted. An error means that the
// checker itself failed, not that the output is wrong.
Check(ctx context.Context, input Input) (bool, error)
}
// New returns the checker for spec.
func New(spec Spec) (Checker, error) {
switch spec.Kind {
case Exact:
return exactChecker{}, nil
case Tokens:
return tokensChecker{}, nil
default:
return nil, fmt.Errorf("checker.New - unknown kind %q", spec.Kind)
}
}
type exactChecker struct{}
func (exactChecker) Check(_ context.Context, input Input) (bool, error) {
return bytes.Equal(normalizeLines(input.Expected), normalizeLines(input.Actual)), nil
}
type tokensChecker struct{}
func (tokensChecker) Check(_ context.Context, input Input) (bool, error) {
expected := bytes.Fields(input.Expected)
actual := bytes.Fields(input.Actual)
if len(expected) != len(actual) {
return false, nil
}
for index := range expected {
if !bytes.Equal(expected[index], actual[index]) {
return false, nil
}
}
return true, nil
}
// normalizeLines replaces CRLF with LF, removes spaces and tabs at the end of
// every line, and removes trailing empty lines.
func normalizeLines(text []byte) []byte {
lines := bytes.Split(bytes.ReplaceAll(text, []byte("\r\n"), []byte("\n")), []byte("\n"))
for index, line := range lines {
lines[index] = bytes.TrimRight(line, " \t")
}
last := len(lines)
for last > 0 && len(lines[last-1]) == 0 {
last--
}
return bytes.Join(lines[:last], []byte("\n"))
}
+53
View File
@@ -0,0 +1,53 @@
package checker
import (
"testing"
)
func TestCheckersCompareOutput(t *testing.T) {
t.Parallel()
cases := []struct {
name string
kind Kind
expected string
actual string
accepted bool
}{
{"exact equal", Exact, "6\n", "6\n", true},
{"exact missing final newline", Exact, "6\n", "6", true},
{"exact CRLF and trailing spaces", Exact, "1 2\n3\n", "1 2 \r\n3\t\r\n\r\n", true},
{"exact inner spaces matter", Exact, "1 2\n", "1 2\n", false},
{"exact leading empty line matters", Exact, "1\n", "\n1\n", false},
{"exact different value", Exact, "6\n", "7\n", false},
{"exact empty output", Exact, "", "\n\n", true},
{"tokens ignore layout", Tokens, "1 2\n3\n", "1\n2 3", true},
{"tokens different count", Tokens, "1 2 3", "1 2", false},
{"tokens different token", Tokens, "1 2 3", "1 2 4", false},
{"tokens are case sensitive", Tokens, "Yes", "yes", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
check, err := New(Spec{Kind: tc.kind})
if err != nil {
t.Fatalf("New: %v", err)
}
accepted, err := check.Check(t.Context(), Input{Expected: []byte(tc.expected), Actual: []byte(tc.actual)})
if err != nil {
t.Fatalf("Check: %v", err)
}
if accepted != tc.accepted {
t.Fatalf("Check(%q, %q) = %v, want %v", tc.expected, tc.actual, accepted, tc.accepted)
}
})
}
}
func TestNewRejectsUnknownKind(t *testing.T) {
t.Parallel()
if _, err := New(Spec{Kind: "float"}); err == nil {
t.Fatal("New accepted an unknown checker kind")
}
}
+266
View File
@@ -0,0 +1,266 @@
// Package config reads the runner configuration from the environment.
package config
import (
"errors"
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
// Defaults of the runner settings.
const (
DefaultListenAddress = ":8443"
DefaultMaxConcurrentRuns = 1
DefaultMaxRequestBytes = 8 << 20
DefaultResultTTL = 15 * time.Minute
DefaultMaxRetainedRuns = 256
DefaultWorkDir = "/var/lib/lincodex-runner/work"
DefaultCgroupRoot = "/sys/fs/cgroup"
DefaultNsjailPath = "/usr/bin/nsjail"
DefaultPythonPath = "/usr/local/bin/python3"
DefaultSandboxUID = 99999
DefaultMaxProcesses = 16
DefaultMemoryOverheadBytes = 4 << 20
DefaultTmpfsBytes = 16 << 20
DefaultFileSizeBytes = 8 << 20
DefaultOpenFiles = 64
DefaultShutdownTimeout = 30 * time.Second
DefaultRetryAfter = 2 * time.Second
// MinTokenLength is the shortest accepted service token.
MinTokenLength = 32
)
// Config is the validated runner configuration.
type Config struct {
ListenAddress string
TLSCertFile string
TLSKeyFile string
// AllowPlaintextHTTP serves HTTP without TLS. Only the local dev
// Compose file sets it.
AllowPlaintextHTTP bool
APIToken string
MaxConcurrentRuns int
MaxRequestBytes int64
ResultTTL time.Duration
MaxRetainedRuns int
RetryAfter time.Duration
ShutdownTimeout time.Duration
WorkDir string
CgroupRoot string
NsjailPath string
PythonPath string
SandboxUID int
MaxProcesses int
MemoryOverheadBytes int64
TmpfsBytes int64
FileSizeBytes int64
OpenFiles int
LogLevel slog.Level
}
// Load reads the configuration from the process environment.
func Load() (Config, error) {
return parse(os.LookupEnv, os.ReadFile)
}
type (
lookupFunc func(string) (string, bool)
readFileFunc func(string) ([]byte, error)
)
func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) {
r := reader{lookup: lookup}
cfg := Config{
ListenAddress: r.text("RUNNER_LISTEN_ADDRESS", DefaultListenAddress),
TLSCertFile: r.text("RUNNER_TLS_CERT_FILE", ""),
TLSKeyFile: r.text("RUNNER_TLS_KEY_FILE", ""),
AllowPlaintextHTTP: r.boolean("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP"),
MaxConcurrentRuns: r.integer("RUNNER_MAX_CONCURRENT_RUNS", DefaultMaxConcurrentRuns),
MaxRequestBytes: r.int64("RUNNER_MAX_REQUEST_BYTES", DefaultMaxRequestBytes),
ResultTTL: r.duration("RUNNER_RESULT_TTL", DefaultResultTTL),
MaxRetainedRuns: r.integer("RUNNER_MAX_RETAINED_RUNS", DefaultMaxRetainedRuns),
RetryAfter: r.duration("RUNNER_RETRY_AFTER", DefaultRetryAfter),
ShutdownTimeout: r.duration("RUNNER_SHUTDOWN_TIMEOUT", DefaultShutdownTimeout),
WorkDir: r.text("RUNNER_WORK_DIR", DefaultWorkDir),
CgroupRoot: r.text("RUNNER_CGROUP_ROOT", DefaultCgroupRoot),
NsjailPath: r.text("RUNNER_NSJAIL_PATH", DefaultNsjailPath),
PythonPath: r.text("RUNNER_PYTHON_PATH", DefaultPythonPath),
SandboxUID: r.integer("RUNNER_SANDBOX_UID", DefaultSandboxUID),
MaxProcesses: r.integer("RUNNER_SANDBOX_MAX_PROCESSES", DefaultMaxProcesses),
MemoryOverheadBytes: r.int64("RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES", DefaultMemoryOverheadBytes),
TmpfsBytes: r.int64("RUNNER_SANDBOX_TMPFS_BYTES", DefaultTmpfsBytes),
FileSizeBytes: r.int64("RUNNER_SANDBOX_FILE_SIZE_BYTES", DefaultFileSizeBytes),
OpenFiles: r.integer("RUNNER_SANDBOX_OPEN_FILES", DefaultOpenFiles),
LogLevel: r.logLevel("RUNNER_LOG_LEVEL"),
}
cfg.APIToken = r.token(readFile)
// Report parse and validation errors together, so one start names
// every setting to fix.
if err := errors.Join(append(r.errs, cfg.validate())...); err != nil {
return Config{}, err
}
return cfg, nil
}
func (c Config) validate() error {
return errors.Join(c.validateTransport(), c.validateLimits(), c.validatePaths())
}
func (c Config) validateTransport() error {
tlsSet := c.TLSCertFile != "" || c.TLSKeyFile != ""
switch {
case tlsSet && (c.TLSCertFile == "" || c.TLSKeyFile == ""):
return errors.New("config.validate - RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE must be set together")
case tlsSet && c.AllowPlaintextHTTP:
return errors.New("config.validate - RUNNER_DEV_ALLOW_PLAINTEXT_HTTP conflicts with TLS settings")
case !tlsSet && !c.AllowPlaintextHTTP:
return errors.New("config.validate - TLS is required: set RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE")
}
return nil
}
func (c Config) validateLimits() error {
var errs []error
positive := map[string]int64{
"RUNNER_MAX_CONCURRENT_RUNS": int64(c.MaxConcurrentRuns),
"RUNNER_MAX_REQUEST_BYTES": c.MaxRequestBytes,
"RUNNER_MAX_RETAINED_RUNS": int64(c.MaxRetainedRuns),
"RUNNER_SANDBOX_MAX_PROCESSES": int64(c.MaxProcesses),
"RUNNER_SANDBOX_TMPFS_BYTES": c.TmpfsBytes,
"RUNNER_SANDBOX_FILE_SIZE_BYTES": c.FileSizeBytes,
"RUNNER_SANDBOX_OPEN_FILES": int64(c.OpenFiles),
"RUNNER_RESULT_TTL": int64(c.ResultTTL),
"RUNNER_RETRY_AFTER": int64(c.RetryAfter),
"RUNNER_SHUTDOWN_TIMEOUT": int64(c.ShutdownTimeout),
}
for name, value := range positive {
if value <= 0 {
errs = append(errs, fmt.Errorf("config.validate - %s must be positive", name))
}
}
if c.MaxRetainedRuns < c.MaxConcurrentRuns {
errs = append(errs, errors.New("config.validate - RUNNER_MAX_RETAINED_RUNS must not be below RUNNER_MAX_CONCURRENT_RUNS"))
}
if c.SandboxUID <= 0 {
errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_UID must not be root"))
}
if c.MemoryOverheadBytes < 0 {
errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES must not be negative"))
}
return errors.Join(errs...)
}
func (c Config) validatePaths() error {
var errs []error
for name, path := range map[string]string{
"RUNNER_WORK_DIR": c.WorkDir,
"RUNNER_CGROUP_ROOT": c.CgroupRoot,
"RUNNER_NSJAIL_PATH": c.NsjailPath,
"RUNNER_PYTHON_PATH": c.PythonPath,
} {
if !strings.HasPrefix(path, "/") {
errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name))
}
}
return errors.Join(errs...)
}
// reader collects parse errors so that one start reports every bad value.
type reader struct {
lookup lookupFunc
errs []error
}
func (r *reader) text(name, fallback string) string {
value, ok := r.lookup(name)
if !ok || value == "" {
return fallback
}
return value
}
func (r *reader) boolean(name string) bool {
value, ok := r.lookup(name)
if !ok || value == "" {
return false
}
parsed, err := strconv.ParseBool(value)
if err != nil {
r.errs = append(r.errs, fmt.Errorf("config.reader.boolean - %s is not a boolean", name))
}
return parsed
}
func (r *reader) integer(name string, fallback int) int {
return int(r.int64(name, int64(fallback)))
}
func (r *reader) int64(name string, fallback int64) int64 {
value, ok := r.lookup(name)
if !ok || value == "" {
return fallback
}
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil {
r.errs = append(r.errs, fmt.Errorf("config.reader.int64 - %s is not an integer", name))
}
return parsed
}
func (r *reader) duration(name string, fallback time.Duration) time.Duration {
value, ok := r.lookup(name)
if !ok || value == "" {
return fallback
}
parsed, err := time.ParseDuration(value)
if err != nil {
r.errs = append(r.errs, fmt.Errorf("config.reader.duration - %s is not a duration", name))
}
return parsed
}
func (r *reader) logLevel(name string) slog.Level {
value, ok := r.lookup(name)
if !ok || value == "" {
return slog.LevelInfo
}
var level slog.Level
if err := level.UnmarshalText([]byte(value)); err != nil {
r.errs = append(r.errs, fmt.Errorf("config.reader.logLevel - %s is not a log level", name))
}
return level
}
// token reads the service token from RUNNER_API_TOKEN_FILE or, failing
// that, RUNNER_API_TOKEN. The value never appears in an error.
func (r *reader) token(readFile readFileFunc) string {
file := r.text("RUNNER_API_TOKEN_FILE", "")
direct := r.text("RUNNER_API_TOKEN", "")
var token string
switch {
case file != "" && direct != "":
r.errs = append(r.errs, errors.New("config.reader.token - set RUNNER_API_TOKEN_FILE or RUNNER_API_TOKEN, not both"))
return ""
case file != "":
content, err := readFile(file)
if err != nil {
r.errs = append(r.errs, fmt.Errorf("config.reader.token - read RUNNER_API_TOKEN_FILE: %w", err))
return ""
}
token = strings.TrimSpace(string(content))
default:
token = direct
}
if len(token) < MinTokenLength {
r.errs = append(r.errs, fmt.Errorf("config.reader.token - the service token must have at least %d characters", MinTokenLength))
return ""
}
return token
}
+116
View File
@@ -0,0 +1,116 @@
package config
import (
"io/fs"
"strings"
"testing"
"time"
)
const testToken = "test-token-0123456789abcdefghijklmnop"
func env(values map[string]string) lookupFunc {
return func(name string) (string, bool) {
value, ok := values[name]
return value, ok
}
}
func noFiles(string) ([]byte, error) {
return nil, fs.ErrNotExist
}
func TestParseDefaultsWithTLS(t *testing.T) {
t.Parallel()
cfg, err := parse(env(map[string]string{
"RUNNER_TLS_CERT_FILE": "/run/secrets/tls.crt",
"RUNNER_TLS_KEY_FILE": "/run/secrets/tls.key",
"RUNNER_API_TOKEN": testToken,
}), noFiles)
if err != nil {
t.Fatalf("parse: %v", err)
}
if cfg.MaxConcurrentRuns != DefaultMaxConcurrentRuns || cfg.ResultTTL != DefaultResultTTL || cfg.AllowPlaintextHTTP {
t.Fatalf("unexpected defaults: %+v", cfg)
}
}
func TestParseRequiresTLSUnlessTheDevSwitchIsSet(t *testing.T) {
t.Parallel()
_, err := parse(env(map[string]string{"RUNNER_API_TOKEN": testToken}), noFiles)
if err == nil || !strings.Contains(err.Error(), "TLS is required") {
t.Fatalf("parse without TLS = %v, want a TLS error", err)
}
cfg, err := parse(env(map[string]string{
"RUNNER_API_TOKEN": testToken,
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
}), noFiles)
if err != nil || !cfg.AllowPlaintextHTTP {
t.Fatalf("parse with the dev switch = %+v, %v", cfg, err)
}
}
func TestParseReadsTheTokenFileAndHidesTheValue(t *testing.T) {
t.Parallel()
files := func(path string) ([]byte, error) {
if path == "/run/secrets/token" {
return []byte(testToken + "\n"), nil
}
return nil, fs.ErrNotExist
}
cfg, err := parse(env(map[string]string{
"RUNNER_API_TOKEN_FILE": "/run/secrets/token",
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1",
}), files)
if err != nil || cfg.APIToken != testToken {
t.Fatalf("parse token file = %q, %v", cfg.APIToken, err)
}
short := "short-secret"
_, err = parse(env(map[string]string{
"RUNNER_API_TOKEN": short,
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1",
}), noFiles)
if err == nil || strings.Contains(err.Error(), short) {
t.Fatalf("parse short token = %v, want an error without the value", err)
}
}
func TestParseReportsEveryInvalidValue(t *testing.T) {
t.Parallel()
_, err := parse(env(map[string]string{
"RUNNER_API_TOKEN": testToken,
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
"RUNNER_MAX_CONCURRENT_RUNS": "many",
"RUNNER_RESULT_TTL": "soon",
"RUNNER_SANDBOX_UID": "0",
"RUNNER_WORK_DIR": "relative/work",
}), noFiles)
if err == nil {
t.Fatal("parse accepted invalid values")
}
for _, name := range []string{"RUNNER_MAX_CONCURRENT_RUNS", "RUNNER_RESULT_TTL", "RUNNER_SANDBOX_UID", "RUNNER_WORK_DIR"} {
if !strings.Contains(err.Error(), name) {
t.Errorf("error %q does not name %s", err, name)
}
}
}
func TestParseRejectsConflictingTLSAndPlaintext(t *testing.T) {
t.Parallel()
_, err := parse(env(map[string]string{
"RUNNER_API_TOKEN": testToken,
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
"RUNNER_TLS_CERT_FILE": "/tls.crt",
"RUNNER_TLS_KEY_FILE": "/tls.key",
"RUNNER_SHUTDOWN_TIMEOUT": time.Second.String(),
}), noFiles)
if err == nil || !strings.Contains(err.Error(), "conflicts") {
t.Fatalf("parse = %v, want a conflict error", err)
}
}
+6
View File
@@ -0,0 +1,6 @@
// Package isolationtest holds the sandbox isolation tests. They need Linux
// with nsjail and a writable cgroup v2 hierarchy, so they are built only with
// the sandbox tag and run in the dev-only test container
// (make -C runner test-sandbox). The fixtures under testdata/hostile are
// shared with later isolation suites.
package isolationtest
@@ -0,0 +1,195 @@
//go:build sandbox && linux
package isolationtest
import (
"bufio"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"lincodex/runner/internal/app"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/config"
"lincodex/runner/internal/judge"
"lincodex/runner/internal/sandbox"
)
const (
fixturesEnv = "RUNNER_HOSTILE_FIXTURES"
defaultFixtures = "../../testdata/hostile"
// seriesRepeats runs the whole manifest this many times before the final
// cleanup check.
seriesRepeats = 2
)
type manifest struct {
Schema string `json:"schema"`
DefaultLimits limits `json:"default_limits"`
Cases []struct {
Name string `json:"name"`
Language string `json:"language"`
Source string `json:"source"`
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
Limits *limits `json:"limits"`
Expect struct {
Outcome judge.Outcome `json:"outcome"`
Limit sandbox.Termination `json:"limit"`
} `json:"expect"`
} `json:"cases"`
}
type limits struct {
TimeLimitMs int64 `json:"time_limit_ms"`
MemoryLimitMB int64 `json:"memory_limit_mb"`
OutputLimitKB int64 `json:"output_limit_kb"`
}
func fixturesDir() string {
if dir := os.Getenv(fixturesEnv); dir != "" {
return dir
}
return defaultFixtures
}
func loadManifest(t *testing.T) manifest {
t.Helper()
content, err := os.ReadFile(filepath.Join(fixturesDir(), "manifest.json"))
if err != nil {
t.Fatalf("read manifest: %v", err)
}
var loaded manifest
if err := json.Unmarshal(content, &loaded); err != nil {
t.Fatalf("decode manifest: %v", err)
}
if loaded.Schema != "lincodex.runner-hostile-fixtures/v1" || len(loaded.Cases) == 0 {
t.Fatalf("unexpected manifest %q with %d cases", loaded.Schema, len(loaded.Cases))
}
return loaded
}
// newRunner builds the sandbox from the production configuration path.
func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) {
t.Helper()
t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength))
t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true")
cfg, err := config.Load()
if err != nil {
t.Fatalf("config: %v", err)
}
executor, err := sandbox.New(app.SandboxConfig(cfg))
if err != nil {
t.Fatalf("sandbox: %v", err)
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
return executor, judge.New(executor, logger, judge.Python3(cfg.PythonPath))
}
func TestHostileProgramsAreStoppedByTheRightLimit(t *testing.T) {
loaded := loadManifest(t)
executor, evaluator := newRunner(t)
for round := range seriesRepeats {
for _, tc := range loaded.Cases {
source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source))
if err != nil {
t.Fatalf("read %s: %v", tc.Source, err)
}
caseLimits := loaded.DefaultLimits
if tc.Limits != nil {
caseLimits = *tc.Limits
}
request := judge.Request{
Language: tc.Language,
Source: string(source),
Limits: judge.Limits{
TimeLimit: time.Duration(caseLimits.TimeLimitMs) * time.Millisecond,
MemoryBytes: caseLimits.MemoryLimitMB << 20,
OutputBytes: caseLimits.OutputLimitKB << 10,
},
Groups: []judge.Group{{
ID: "public",
Visibility: judge.Public,
Checker: checker.Spec{Kind: checker.Exact},
Tests: []judge.Test{{ID: "t1", Input: tc.Input, ExpectedOutput: tc.ExpectedOutput}},
}},
}
result := evaluator.Run(t.Context(), request)
if result.Outcome != tc.Expect.Outcome {
t.Errorf("round %d %s: outcome %s, want %s (%s)", round, tc.Name, result.Outcome, tc.Expect.Outcome, describe(result))
continue
}
if tc.Expect.Outcome == judge.CompileError {
if result.Compile == nil || result.Compile.Diagnostic == "" {
t.Errorf("round %d %s: compile error without a diagnostic", round, tc.Name)
}
continue
}
test := result.Groups[0].Tests[0]
if test.Limit != tc.Expect.Limit {
t.Errorf("round %d %s: limit %q, want %q (%s)", round, tc.Name, test.Limit, tc.Expect.Limit, describe(result))
}
if test.CPUTime <= 0 || test.WallTime <= 0 || test.MemoryKB <= 0 {
t.Errorf("round %d %s: usage not recorded: cpu %v wall %v memory %d KiB", round, tc.Name, test.CPUTime, test.WallTime, test.MemoryKB)
}
t.Logf("round %d %-16s %-22s limit=%-9q cpu=%v wall=%v memory=%dKiB", round, tc.Name, test.Outcome, test.Limit, test.CPUTime, test.WallTime, test.MemoryKB)
assertNothingLeft(t, executor, tc.Name)
}
}
assertNothingLeft(t, executor, "series")
}
func describe(result judge.Result) string {
return fmt.Sprintf("%+v", result)
}
// assertNothingLeft checks that the work directory and the run cgroups are
// gone and that no process of the sandbox user is alive.
func assertNothingLeft(t *testing.T, executor *sandbox.Executor, label string) {
t.Helper()
boxes, cgroups, err := executor.Leftovers()
if err != nil {
t.Fatalf("%s: leftovers: %v", label, err)
}
if len(boxes) != 0 || len(cgroups) != 0 {
t.Fatalf("%s: left boxes %q and cgroups %q", label, boxes, cgroups)
}
if pids := sandboxUserProcesses(t, config.DefaultSandboxUID); len(pids) != 0 {
t.Fatalf("%s: sandbox user processes still alive: %v", label, pids)
}
}
func sandboxUserProcesses(t *testing.T, uid int) []string {
t.Helper()
entries, err := os.ReadDir("/proc")
if err != nil {
t.Fatalf("list /proc: %v", err)
}
wanted := "\t" + strconv.Itoa(uid) + "\t"
var pids []string
for _, entry := range entries {
if !entry.IsDir() || strings.Trim(entry.Name(), "0123456789") != "" {
continue
}
file, err := os.Open(filepath.Join("/proc", entry.Name(), "status"))
if err != nil {
continue // The process exited meanwhile.
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "Uid:") && strings.Contains(line+"\t", wanted) {
pids = append(pids, entry.Name())
}
}
_ = file.Close()
}
return pids
}
+240
View File
@@ -0,0 +1,240 @@
// Package jobs keeps runs in memory, enforces the number of concurrent
// sandbox runs, and makes submissions idempotent by run ID.
package jobs
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"lincodex/runner/internal/judge"
)
// State of a run.
type State string
const (
Running State = "running"
Finished State = "finished"
)
var (
// ErrBusy means that every slot is taken or the manager is draining.
ErrBusy = errors.New("every sandbox slot is busy")
// ErrPayloadMismatch means that the run ID exists with another payload.
ErrPayloadMismatch = errors.New("run ID reused with a different payload")
// ErrNotFound means that the manager does not hold the run.
ErrNotFound = errors.New("run not found")
)
// Runner evaluates one request.
type Runner interface {
Run(ctx context.Context, request judge.Request) judge.Result
}
// Snapshot is a copy of a run's state.
type Snapshot struct {
ID uuid.UUID
State State
Result *judge.Result
}
// Config bounds the manager.
type Config struct {
MaxConcurrent int
// ResultTTL is how long a finished run stays readable.
ResultTTL time.Duration
// MaxRetained bounds stored runs, running ones included.
MaxRetained int
}
type job struct {
fingerprint [sha256.Size]byte
state State
result *judge.Result
finishedAt time.Time
}
// Manager owns the runs. Request payloads live only while a run executes;
// a stored run keeps its fingerprint and result.
type Manager struct {
cfg Config
runner Runner
logger *slog.Logger
now func() time.Time
ctx context.Context
cancel context.CancelFunc
running sync.WaitGroup
mu sync.Mutex
jobs map[uuid.UUID]*job
active int
draining bool
}
// NewManager returns a manager. Runs use a context that Close cancels.
func NewManager(cfg Config, runner Runner, logger *slog.Logger) (*Manager, error) {
if cfg.MaxConcurrent <= 0 || cfg.MaxRetained < cfg.MaxConcurrent || cfg.ResultTTL <= 0 {
return nil, errors.New("jobs.NewManager - invalid limits")
}
ctx, cancel := context.WithCancel(context.Background())
return &Manager{
cfg: cfg,
runner: runner,
logger: logger,
now: time.Now,
ctx: ctx,
cancel: cancel,
jobs: make(map[uuid.UUID]*job),
}, nil
}
// Fingerprint is the SHA-256 of the canonical JSON encoding of a request.
// Struct fields encode in declaration order and the request has no maps, so
// equal requests always give equal fingerprints.
func Fingerprint(request judge.Request) ([sha256.Size]byte, error) {
encoded, err := json.Marshal(request)
if err != nil {
return [sha256.Size]byte{}, fmt.Errorf("jobs.Fingerprint - encode: %w", err)
}
return sha256.Sum256(encoded), nil
}
// Submit starts a run or returns the existing run with the same ID and
// payload. created is true when a new run started.
func (m *Manager) Submit(id uuid.UUID, request judge.Request) (snapshot Snapshot, created bool, err error) {
fingerprint, err := Fingerprint(request)
if err != nil {
return Snapshot{}, false, err
}
m.mu.Lock()
defer m.mu.Unlock()
m.forgetExpiredLocked()
if existing, ok := m.jobs[id]; ok {
if existing.fingerprint != fingerprint {
return Snapshot{}, false, ErrPayloadMismatch
}
return existing.snapshot(id), false, nil
}
if m.draining || m.active >= m.cfg.MaxConcurrent {
return Snapshot{}, false, ErrBusy
}
if len(m.jobs) >= m.cfg.MaxRetained && !m.forgetOldestFinishedLocked() {
return Snapshot{}, false, ErrBusy
}
current := &job{fingerprint: fingerprint, state: Running}
m.jobs[id] = current
m.active++
m.running.Go(func() { m.execute(id, current, request) })
return current.snapshot(id), true, nil
}
// Get returns the state of a run.
func (m *Manager) Get(id uuid.UUID) (Snapshot, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.forgetExpiredLocked()
existing, ok := m.jobs[id]
if !ok {
return Snapshot{}, ErrNotFound
}
return existing.snapshot(id), nil
}
// Draining reports whether the manager refuses new runs.
func (m *Manager) Draining() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.draining
}
// Close refuses new runs, waits for running ones until ctx ends, and then
// cancels them, which kills their sandboxes.
func (m *Manager) Close(ctx context.Context) error {
m.mu.Lock()
m.draining = true
m.mu.Unlock()
done := make(chan struct{})
go func() {
m.running.Wait()
close(done)
}()
select {
case <-done:
m.cancel()
return nil
case <-ctx.Done():
m.cancel()
<-done
return fmt.Errorf("jobs.Manager.Close - canceled running runs: %w", ctx.Err())
}
}
func (m *Manager) execute(id uuid.UUID, current *job, request judge.Request) {
m.logger.InfoContext(m.ctx, "run started",
slog.String("run_id", id.String()),
slog.String("language", request.Language),
slog.Int("groups", len(request.Groups)),
slog.Int("tests", countTests(request)),
)
result := m.runner.Run(m.ctx, request)
m.mu.Lock()
current.state = Finished
current.result = &result
current.finishedAt = m.now()
m.active--
m.mu.Unlock()
m.logger.InfoContext(m.ctx, "run finished",
slog.String("run_id", id.String()),
slog.String("outcome", string(result.Outcome)),
slog.Int64("duration_ms", result.Duration.Milliseconds()),
)
}
func (m *Manager) forgetExpiredLocked() {
now := m.now()
for id, existing := range m.jobs {
if existing.state == Finished && now.Sub(existing.finishedAt) > m.cfg.ResultTTL {
delete(m.jobs, id)
}
}
}
func (m *Manager) forgetOldestFinishedLocked() bool {
var oldestID uuid.UUID
var oldest *job
for id, existing := range m.jobs {
if existing.state != Finished {
continue
}
if oldest == nil || existing.finishedAt.Before(oldest.finishedAt) {
oldestID, oldest = id, existing
}
}
if oldest == nil {
return false
}
delete(m.jobs, oldestID)
return true
}
func (j *job) snapshot(id uuid.UUID) Snapshot {
return Snapshot{ID: id, State: j.state, Result: j.result}
}
func countTests(request judge.Request) int {
total := 0
for _, group := range request.Groups {
total += len(group.Tests)
}
return total
}
+223
View File
@@ -0,0 +1,223 @@
package jobs
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/runner/internal/judge"
)
// gatedRunner blocks every run until release is closed or the run context
// ends, and counts the runs it saw.
type gatedRunner struct {
release chan struct{}
mu sync.Mutex
runs int
}
func newGatedRunner() *gatedRunner {
return &gatedRunner{release: make(chan struct{})}
}
func (r *gatedRunner) Run(ctx context.Context, _ judge.Request) judge.Result {
r.mu.Lock()
r.runs++
r.mu.Unlock()
select {
case <-r.release:
return judge.Result{Outcome: judge.Accepted}
case <-ctx.Done():
return judge.Result{Outcome: judge.InfrastructureFailure}
}
}
func (r *gatedRunner) count() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.runs
}
func newTestManager(t *testing.T, runner Runner, cfg Config) *Manager {
t.Helper()
manager, err := NewManager(cfg, runner, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewManager: %v", err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = manager.Close(ctx)
})
return manager
}
func request(source string) judge.Request {
return judge.Request{Language: "python3", Source: source, Limits: judge.Limits{TimeLimit: time.Second}}
}
func waitFinished(t *testing.T, manager *Manager, id uuid.UUID) Snapshot {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
snapshot, err := manager.Get(id)
if err != nil {
t.Fatalf("Get: %v", err)
}
if snapshot.State == Finished {
return snapshot
}
time.Sleep(time.Millisecond)
}
t.Fatal("run did not finish")
return Snapshot{}
}
func TestSubmitIsIdempotentByRunIDAndPayload(t *testing.T) {
t.Parallel()
runner := newGatedRunner()
manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8})
id := uuid.New()
first, created, err := manager.Submit(id, request("print(1)"))
if err != nil || !created || first.State != Running {
t.Fatalf("first Submit = %+v, %v, %v", first, created, err)
}
again, created, err := manager.Submit(id, request("print(1)"))
if err != nil || created || again.State != Running {
t.Fatalf("repeated Submit = %+v, %v, %v; want the same running run", again, created, err)
}
if _, _, err := manager.Submit(id, request("print(2)")); !errors.Is(err, ErrPayloadMismatch) {
t.Fatalf("Submit with another payload = %v, want ErrPayloadMismatch", err)
}
close(runner.release)
finished := waitFinished(t, manager, id)
replay, created, err := manager.Submit(id, request("print(1)"))
if err != nil || created || replay.State != Finished || replay.Result != finished.Result {
t.Fatalf("Submit after finish = %+v, %v, %v; want the stored result", replay, created, err)
}
if runner.count() != 1 {
t.Fatalf("runner ran %d times, want 1", runner.count())
}
}
func TestSubmitAnswersBusyWhenEverySlotIsTaken(t *testing.T) {
t.Parallel()
runner := newGatedRunner()
manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8})
busyID := uuid.New()
if _, _, err := manager.Submit(uuid.New(), request("a")); err != nil {
t.Fatalf("Submit: %v", err)
}
if _, _, err := manager.Submit(busyID, request("b")); !errors.Is(err, ErrBusy) {
t.Fatalf("second Submit = %v, want ErrBusy", err)
}
if _, err := manager.Get(busyID); !errors.Is(err, ErrNotFound) {
t.Fatalf("Get of a refused run = %v, want ErrNotFound", err)
}
close(runner.release)
deadline := time.Now().Add(5 * time.Second)
for {
_, _, err := manager.Submit(busyID, request("b"))
if err == nil {
break
}
if !errors.Is(err, ErrBusy) || time.Now().After(deadline) {
t.Fatalf("Submit after the slot freed = %v", err)
}
time.Sleep(time.Millisecond)
}
}
func TestFinishedRunsExpireAfterTheirTTL(t *testing.T) {
t.Parallel()
runner := newGatedRunner()
close(runner.release)
manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 1})
clock := time.Now()
var clockMu sync.Mutex
manager.now = func() time.Time {
clockMu.Lock()
defer clockMu.Unlock()
return clock
}
id := uuid.New()
if _, _, err := manager.Submit(id, request("a")); err != nil {
t.Fatalf("Submit: %v", err)
}
waitFinished(t, manager, id)
// A full store forgets the oldest finished run for a new one.
other := uuid.New()
if _, _, err := manager.Submit(other, request("b")); err != nil {
t.Fatalf("Submit into a full store: %v", err)
}
if _, err := manager.Get(id); !errors.Is(err, ErrNotFound) {
t.Fatalf("Get of the evicted run = %v, want ErrNotFound", err)
}
waitFinished(t, manager, other)
clockMu.Lock()
clock = clock.Add(2 * time.Minute)
clockMu.Unlock()
if _, err := manager.Get(other); !errors.Is(err, ErrNotFound) {
t.Fatalf("Get after the TTL = %v, want ErrNotFound", err)
}
}
func TestCloseRefusesNewRunsAndCancelsRunningOnes(t *testing.T) {
t.Parallel()
runner := newGatedRunner()
manager := newTestManager(t, runner, Config{MaxConcurrent: 2, ResultTTL: time.Minute, MaxRetained: 8})
id := uuid.New()
if _, _, err := manager.Submit(id, request("a")); err != nil {
t.Fatalf("Submit: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
if err := manager.Close(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Close = %v, want the deadline after canceling the run", err)
}
snapshot, err := manager.Get(id)
if err != nil || snapshot.State != Finished || snapshot.Result.Outcome != judge.InfrastructureFailure {
t.Fatalf("canceled run = %+v, %v", snapshot, err)
}
if _, _, err := manager.Submit(uuid.New(), request("b")); !errors.Is(err, ErrBusy) {
t.Fatalf("Submit while draining = %v, want ErrBusy", err)
}
}
func TestFingerprintDependsOnEveryField(t *testing.T) {
t.Parallel()
base := judge.Request{Language: "python3", Source: "x", Groups: []judge.Group{{ID: "g", Tests: []judge.Test{{ID: "t", Input: "1", ExpectedOutput: "1"}}}}}
changed := base
changed.Groups = []judge.Group{{ID: "g", Tests: []judge.Test{{ID: "t", Input: "1", ExpectedOutput: "2"}}}}
first, err := Fingerprint(base)
if err != nil {
t.Fatalf("Fingerprint: %v", err)
}
second, err := Fingerprint(changed)
if err != nil {
t.Fatalf("Fingerprint: %v", err)
}
same, err := Fingerprint(base)
if err != nil {
t.Fatalf("Fingerprint: %v", err)
}
if first == second || first != same {
t.Fatal("fingerprints must differ for different payloads and match for equal ones")
}
}
+347
View File
@@ -0,0 +1,347 @@
// Package judge evaluates one source against its test groups in the sandbox
// and turns sandbox results into contract outcomes.
package judge
import (
"bytes"
"context"
"fmt"
"log/slog"
"strings"
"time"
"unicode/utf8"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/sandbox"
)
// Outcome is the result of a test, a group, a compile step, or a run.
type Outcome string
const (
Accepted Outcome = "accepted"
WrongAnswer Outcome = "wrong_answer"
CompileError Outcome = "compile_error"
TimeLimitExceeded Outcome = "time_limit_exceeded"
MemoryLimitExceeded Outcome = "memory_limit_exceeded"
OutputLimitExceeded Outcome = "output_limit_exceeded"
RuntimeError Outcome = "runtime_error"
InfrastructureFailure Outcome = "infrastructure_failure"
)
// Visibility tells whether results may carry program diagnostics.
type Visibility string
const (
Public Visibility = "public"
Hidden Visibility = "hidden"
)
// Contract limits of a test result.
const (
maxCompileDiagnostic = 4096
maxTestDiagnostic = 2048
)
// Request is one run. It holds no identifiers of people or product records.
// The JSON tags define the encoding of the idempotency fingerprint.
type Request struct {
Language string `json:"language"`
Source string `json:"source"`
Limits Limits `json:"limits"`
Groups []Group `json:"groups"`
}
// Limits apply to every test of a run.
type Limits struct {
TimeLimit time.Duration `json:"time_limit"`
MemoryBytes int64 `json:"memory_bytes"`
OutputBytes int64 `json:"output_bytes"`
}
// Group is a set of tests with one checker.
type Group struct {
ID string `json:"id"`
Visibility Visibility `json:"visibility"`
Checker checker.Spec `json:"checker"`
Tests []Test `json:"tests"`
}
// Test is one input and its expected output.
type Test struct {
ID string `json:"id"`
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
}
// Result is the evaluation of a run.
type Result struct {
Outcome Outcome
Compile *CompileResult
Groups []GroupResult
Duration time.Duration
}
// CompileResult is the outcome of the compile or syntax check step.
type CompileResult struct {
Outcome Outcome
Diagnostic string
}
// GroupResult is the evaluation of one group.
type GroupResult struct {
ID string
Visibility Visibility
Outcome Outcome
Passed int
Total int
MaxCPUTime time.Duration
MaxMemoryKB int64
Tests []TestResult
}
// TestResult is the evaluation of one test.
type TestResult struct {
ID string
Outcome Outcome
CPUTime time.Duration
WallTime time.Duration
MemoryKB int64
ExitCode *int
Signal *int
Limit sandbox.Termination
Diagnostic string
}
// Executor is the sandbox used by the judge.
type Executor interface {
NewBox(fileName string, content []byte) (*sandbox.Box, error)
Run(ctx context.Context, spec sandbox.Spec, limits sandbox.Limits) (sandbox.Result, error)
}
// Judge evaluates requests with one executor and a set of languages.
type Judge struct {
executor Executor
languages map[string]Language
logger *slog.Logger
}
// New returns a judge for the given languages.
func New(executor Executor, logger *slog.Logger, languages ...Language) *Judge {
byID := make(map[string]Language, len(languages))
for _, language := range languages {
byID[language.ID] = language
}
return &Judge{executor: executor, languages: byID, logger: logger}
}
// Supports reports whether the judge knows the language.
func (j *Judge) Supports(language string) bool {
_, ok := j.languages[language]
return ok
}
// Run evaluates a request. Failures of the runner become
// infrastructure_failure; they never look like an outcome of the program.
func (j *Judge) Run(ctx context.Context, request Request) Result {
started := time.Now()
result := j.evaluate(ctx, request)
result.Duration = time.Since(started)
return result
}
func (j *Judge) evaluate(ctx context.Context, request Request) Result {
language, ok := j.languages[request.Language]
if !ok {
j.logger.ErrorContext(ctx, "run has an unsupported language")
return failedRun(request, InfrastructureFailure, nil)
}
box, err := j.executor.NewBox(language.SourceFile, []byte(request.Source))
if err != nil {
j.logger.ErrorContext(ctx, "cannot create the run directory", slog.Any("error", err))
return failedRun(request, InfrastructureFailure, nil)
}
defer func() {
if err := box.Remove(); err != nil {
j.logger.ErrorContext(ctx, "cannot remove the run directory", slog.Any("error", err))
}
}()
compile, ok := j.compile(ctx, language, box)
if !ok {
return failedRun(request, compile.Outcome, compile)
}
result := Result{Outcome: Accepted, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))}
for _, group := range request.Groups {
groupResult := j.evaluateGroup(ctx, language, box, request.Limits, group)
if groupResult.Outcome == InfrastructureFailure {
return failedRun(request, InfrastructureFailure, compile)
}
if result.Outcome == Accepted && groupResult.Outcome != Accepted {
result.Outcome = groupResult.Outcome
}
result.Groups = append(result.Groups, groupResult)
}
return result
}
// compile runs the language's compile step. ok is false when no test may run.
func (j *Judge) compile(ctx context.Context, language Language, box *sandbox.Box) (*CompileResult, bool) {
if len(language.Compile) == 0 {
return nil, true
}
run, err := j.executor.Run(ctx, sandbox.Spec{Argv: language.Compile, BoxDir: box.Dir()}, language.CompileLimits)
if err != nil {
j.logger.ErrorContext(ctx, "compile step failed in the sandbox", slog.Any("error", err))
return &CompileResult{Outcome: InfrastructureFailure}, false
}
if run.Termination == sandbox.TerminationNone && run.ExitCode == 0 && run.Signal == 0 {
return &CompileResult{Outcome: Accepted}, true
}
diagnostic := compileDiagnostic(run)
return &CompileResult{Outcome: CompileError, Diagnostic: diagnostic}, false
}
func compileDiagnostic(run sandbox.Result) string {
if run.Termination != sandbox.TerminationNone {
return "The compile step exceeded its " + strings.ReplaceAll(string(run.Termination), "_", " ") + " limit."
}
return excerpt(run.Stderr, maxCompileDiagnostic)
}
func (j *Judge) evaluateGroup(ctx context.Context, language Language, box *sandbox.Box, limits Limits, group Group) GroupResult {
result := GroupResult{
ID: group.ID,
Visibility: group.Visibility,
Outcome: Accepted,
Total: len(group.Tests),
Tests: make([]TestResult, 0, len(group.Tests)),
}
check, err := checker.New(group.Checker)
if err != nil {
j.logger.ErrorContext(ctx, "group has an unknown checker", slog.Any("error", err))
result.Outcome = InfrastructureFailure
return result
}
for _, test := range group.Tests {
testResult, err := j.evaluateTest(ctx, language, box, limits, group.Visibility, check, test)
if err != nil {
j.logger.ErrorContext(ctx, "test failed in the sandbox", slog.Any("error", err))
result.Outcome = InfrastructureFailure
return result
}
result.Tests = append(result.Tests, testResult)
result.MaxCPUTime = max(result.MaxCPUTime, testResult.CPUTime)
result.MaxMemoryKB = max(result.MaxMemoryKB, testResult.MemoryKB)
if testResult.Outcome != Accepted {
result.Outcome = testResult.Outcome
return result
}
result.Passed++
}
return result
}
func (j *Judge) evaluateTest(
ctx context.Context,
language Language,
box *sandbox.Box,
limits Limits,
visibility Visibility,
check checker.Checker,
test Test,
) (TestResult, error) {
run, err := j.executor.Run(ctx, sandbox.Spec{
Argv: language.Run,
Stdin: []byte(test.Input),
BoxDir: box.Dir(),
}, sandbox.Limits{
CPUTime: limits.TimeLimit,
WallTime: wallTimeLimit(limits.TimeLimit),
MemoryBytes: limits.MemoryBytes,
OutputBytes: limits.OutputBytes,
})
if err != nil {
return TestResult{}, err
}
result := TestResult{
ID: test.ID,
Outcome: outcomeOf(run),
CPUTime: run.CPUTime,
WallTime: run.WallTime,
MemoryKB: run.PeakMemoryKB,
Limit: run.Termination,
}
if run.Signal != 0 {
result.Signal = &run.Signal
} else {
result.ExitCode = &run.ExitCode
}
if result.Outcome == Accepted {
accepted, err := check.Check(ctx, checker.Input{
TestInput: []byte(test.Input),
Expected: []byte(test.ExpectedOutput),
Actual: run.Stdout,
})
if err != nil {
return TestResult{}, fmt.Errorf("judge.Judge.evaluateTest - checker: %w", err)
}
if !accepted {
result.Outcome = WrongAnswer
}
}
if visibility == Public && result.Outcome != Accepted && result.Outcome != WrongAnswer {
result.Diagnostic = excerpt(run.Stderr, maxTestDiagnostic)
}
return result, nil
}
// wallTimeLimit allows blocking and startup on top of the CPU limit.
func wallTimeLimit(cpu time.Duration) time.Duration {
const startupAllowance = 500 * time.Millisecond
return 2*cpu + startupAllowance
}
// outcomeOf maps how a program ended to an outcome before checking output.
func outcomeOf(run sandbox.Result) Outcome {
switch run.Termination {
case sandbox.TerminationMemory:
return MemoryLimitExceeded
case sandbox.TerminationOutput:
return OutputLimitExceeded
case sandbox.TerminationCPUTime, sandbox.TerminationWallTime:
return TimeLimitExceeded
case sandbox.TerminationProcesses:
return RuntimeError
case sandbox.TerminationNone:
}
if run.Signal != 0 || run.ExitCode != 0 {
return RuntimeError
}
return Accepted
}
// failedRun gives every group the outcome of a run that stopped early.
func failedRun(request Request, outcome Outcome, compile *CompileResult) Result {
result := Result{Outcome: outcome, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))}
for _, group := range request.Groups {
result.Groups = append(result.Groups, GroupResult{
ID: group.ID,
Visibility: group.Visibility,
Outcome: outcome,
Total: len(group.Tests),
Tests: []TestResult{},
})
}
return result
}
// excerpt returns the last limit bytes of text as valid UTF-8.
func excerpt(text []byte, limit int) string {
text = bytes.ToValidUTF8(text, []byte("�"))
for len(text) > limit {
_, size := utf8.DecodeRune(text)
text = text[size:]
}
return string(text)
}
+212
View File
@@ -0,0 +1,212 @@
package judge
import (
"bytes"
"context"
"errors"
"log/slog"
"os"
"slices"
"testing"
"time"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/sandbox"
)
// scriptedExecutor answers runs from a script keyed by the stdin of a test;
// the compile step has no stdin.
type scriptedExecutor struct {
root string
results map[string]sandbox.Result
errs map[string]error
runs []string
boxes []string
}
func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box, error) {
box, err := sandbox.CreateBox(e.root, fileName, content)
if err == nil {
e.boxes = append(e.boxes, box.Dir())
}
return box, err
}
func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.Limits) (sandbox.Result, error) {
key := string(spec.Stdin)
e.runs = append(e.runs, key)
if err := e.errs[key]; err != nil {
return sandbox.Result{}, err
}
if result, ok := e.results[key]; ok {
return result, nil
}
return sandbox.Result{}, nil
}
func newScripted(t *testing.T) *scriptedExecutor {
t.Helper()
return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}}
}
func output(text string) sandbox.Result {
return sandbox.Result{Stdout: []byte(text), CPUTime: 20 * time.Millisecond, WallTime: 30 * time.Millisecond, PeakMemoryKB: 9000}
}
func discardLogger() *slog.Logger {
return slog.New(slog.DiscardHandler)
}
func twoGroupRequest() Request {
return Request{
Language: "python3",
Source: "print(sum(map(int, input().split())))",
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
Groups: []Group{
{ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{
{ID: "t1", Input: "1 2", ExpectedOutput: "3\n"},
{ID: "t2", Input: "2 2", ExpectedOutput: "4\n"},
}},
{ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Tokens}, Tests: []Test{
{ID: "t1", Input: "5 5", ExpectedOutput: "10"},
{ID: "t2", Input: "6 6", ExpectedOutput: "12"},
}},
},
}
}
func TestRunAcceptsCorrectOutputAndRecordsUsage(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["1 2"] = output("3\n")
executor.results["2 2"] = output("4")
executor.results["5 5"] = output("10\n")
executor.results["6 6"] = output(" 12 ")
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
if result.Outcome != Accepted || result.Compile == nil || result.Compile.Outcome != Accepted {
t.Fatalf("result = %+v, want accepted with a passed compile step", result)
}
for _, group := range result.Groups {
if group.Outcome != Accepted || group.Passed != 2 || group.Total != 2 {
t.Fatalf("group %+v, want 2 of 2 accepted", group)
}
if group.MaxCPUTime != 20*time.Millisecond || group.MaxMemoryKB != 9000 {
t.Fatalf("group usage %v %d, want the recorded usage", group.MaxCPUTime, group.MaxMemoryKB)
}
}
assertBoxesRemoved(t, executor)
}
func TestRunStopsAGroupAtItsFirstFailureAndKeepsDiagnosticsPublicOnly(t *testing.T) {
t.Parallel()
executor := newScripted(t)
crash := sandbox.Result{ExitCode: 1, Stderr: []byte("Traceback: ValueError")}
executor.results["1 2"] = crash
executor.results["5 5"] = crash
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
if result.Outcome != RuntimeError {
t.Fatalf("outcome = %s, want runtime_error", result.Outcome)
}
public, hidden := result.Groups[0], result.Groups[1]
if len(public.Tests) != 1 || public.Passed != 0 || public.Tests[0].Diagnostic != "Traceback: ValueError" {
t.Fatalf("public group %+v, want one failed test with its diagnostic", public)
}
if len(hidden.Tests) != 1 || hidden.Tests[0].Diagnostic != "" {
t.Fatalf("hidden group %+v, want one failed test without a diagnostic", hidden)
}
if slices.Contains(executor.runs, "2 2") || slices.Contains(executor.runs, "6 6") {
t.Fatalf("runs %q include tests after a failure", executor.runs)
}
}
func TestRunMapsSandboxTerminationsToOutcomes(t *testing.T) {
t.Parallel()
cases := []struct {
name string
result sandbox.Result
outcome Outcome
}{
{"cpu time", sandbox.Result{Termination: sandbox.TerminationCPUTime, Signal: 9}, TimeLimitExceeded},
{"wall time", sandbox.Result{Termination: sandbox.TerminationWallTime, Signal: 9}, TimeLimitExceeded},
{"memory", sandbox.Result{Termination: sandbox.TerminationMemory, Signal: 9}, MemoryLimitExceeded},
{"output", sandbox.Result{Termination: sandbox.TerminationOutput, Signal: 9, Stdout: []byte("3\n")}, OutputLimitExceeded},
{"processes", sandbox.Result{Termination: sandbox.TerminationProcesses, ExitCode: 1}, RuntimeError},
{"signal", sandbox.Result{Signal: 31, ExitCode: -1}, RuntimeError},
{"wrong answer", output("4\n"), WrongAnswer},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["1 2"] = tc.result
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
got := result.Groups[0].Tests[0]
if got.Outcome != tc.outcome || got.Limit != tc.result.Termination {
t.Fatalf("test result %+v, want %s with limit %q", got, tc.outcome, tc.result.Termination)
}
})
}
}
func TestRunReportsCompileErrorsWithoutRunningTests(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results[""] = sandbox.Result{ExitCode: 1, Stderr: []byte("SyntaxError: invalid syntax\n")}
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
if result.Outcome != CompileError || result.Compile.Diagnostic != "SyntaxError: invalid syntax\n" {
t.Fatalf("result = %+v, want compile_error with the diagnostic", result)
}
if len(executor.runs) != 1 {
t.Fatalf("runs = %q, want only the compile step", executor.runs)
}
for _, group := range result.Groups {
if group.Outcome != CompileError || len(group.Tests) != 0 || group.Total != 2 {
t.Fatalf("group %+v, want compile_error without tests", group)
}
}
assertBoxesRemoved(t, executor)
}
func TestRunTurnsSandboxFailuresIntoInfrastructureFailure(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["1 2"] = output("3\n")
executor.errs["2 2"] = errors.New("nsjail failed")
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
if result.Outcome != InfrastructureFailure {
t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome)
}
for _, group := range result.Groups {
if group.Outcome != InfrastructureFailure || len(group.Tests) != 0 {
t.Fatalf("group %+v, want infrastructure_failure without partial tests", group)
}
}
assertBoxesRemoved(t, executor)
}
func TestExcerptKeepsTheTailAsValidUTF8(t *testing.T) {
t.Parallel()
text := append(bytes.Repeat([]byte("ж"), 10), 0xff, 'x')
if got := excerpt(text, 7); got != "ж\uFFFDx" {
t.Fatalf("excerpt = %q, want the last whole runes within 7 bytes", got)
}
}
func assertBoxesRemoved(t *testing.T, executor *scriptedExecutor) {
t.Helper()
for _, dir := range executor.boxes {
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("box %s still exists: %v", dir, err)
}
}
}
+62
View File
@@ -0,0 +1,62 @@
package judge
import (
"time"
"lincodex/runner/internal/sandbox"
)
// Language describes how the sandbox checks and runs a source file.
type Language struct {
ID string
// SourceFile is the file name of the source inside sandbox.BoxPath.
SourceFile string
// Compile is the optional compile or syntax check command.
Compile []string
// CompileLimits bound the compile step; they do not depend on the run.
CompileLimits sandbox.Limits
// Run is the command of every test; the test input is its stdin.
Run []string
}
// pythonSyntaxCheck compiles the source without running it and prints only
// the exception line, so that a syntax error is a compile_error with a short
// message. compile() never executes the program.
const pythonSyntaxCheck = `import sys, traceback
path = sys.argv[1]
try:
with open(path, "rb") as stream:
compile(stream.read(), "main.py", "exec", dont_inherit=True)
except (SyntaxError, ValueError) as error:
sys.stderr.write("".join(traceback.format_exception_only(type(error), error)))
sys.exit(1)
`
// Limits of the Python syntax check. A 64 KiB source compiles far below
// them; a pathological source fails with compile_error.
const (
pythonCompileCPU = 5 * time.Second
pythonCompileWall = 10 * time.Second
pythonCompileMemory = 256 << 20
pythonCompileOutput = 64 << 10
)
// Python3 returns the Python 3 language for the interpreter at path. The
// interpreter runs in isolated mode (-I: no environment variables, no user
// site directory, no script directory on sys.path) and never writes
// bytecode (-B).
func Python3(interpreter string) Language {
source := sandbox.BoxPath + "/main.py"
return Language{
ID: "python3",
SourceFile: "main.py",
Compile: []string{interpreter, "-I", "-B", "-c", pythonSyntaxCheck, source},
CompileLimits: sandbox.Limits{
CPUTime: pythonCompileCPU,
WallTime: pythonCompileWall,
MemoryBytes: pythonCompileMemory,
OutputBytes: pythonCompileOutput,
},
Run: []string{interpreter, "-I", "-B", source},
}
}
+353
View File
@@ -0,0 +1,353 @@
package sandbox
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"syscall"
"time"
)
const (
supervisorCgroup = "supervisor"
jailsCgroup = "jails"
// cpuQuota allows one CPU per run: quota and period in microseconds.
cpuQuota = "100000 100000"
// cgroupDrainTimeout bounds the wait for a killed cgroup to empty.
cgroupDrainTimeout = 5 * time.Second
cgroupDrainPoll = 5 * time.Millisecond
// moveAttempts bounds retries while processes appear in the root cgroup.
moveAttempts = 10
cgroupFileMode = 0o644
cgroupDirMode = 0o755
bytesPerKB = 1 << 10
)
var requiredControllers = []string{"cpu", "memory", "pids"}
// cgroupTree is the cgroup hierarchy owned by the runner:
//
// <root>/supervisor the runner process itself
// <root>/jails/<run> one cgroup per sandboxed run
//
// cgroup v2 forbids processes in a cgroup that delegates controllers to its
// children, so the runner first moves itself out of the root.
type cgroupTree struct {
root string
jails string
}
// prepareCgroups creates the hierarchy below root, enables the controllers,
// and removes run cgroups left by an earlier process.
func prepareCgroups(root string) (*cgroupTree, error) {
controllers, err := os.ReadFile(filepath.Join(root, "cgroup.controllers"))
if err != nil {
return nil, fmt.Errorf("sandbox.prepareCgroups - read controllers: %w", err)
}
available := strings.Fields(string(controllers))
for _, controller := range requiredControllers {
if !slices.Contains(available, controller) {
return nil, fmt.Errorf("sandbox.prepareCgroups - controller %s is not delegated", controller)
}
}
supervisor := filepath.Join(root, supervisorCgroup)
if err := mkdirCgroup(supervisor); err != nil {
return nil, err
}
if err := moveProcesses(root, supervisor); err != nil {
return nil, err
}
enable := "+" + strings.Join(requiredControllers, " +")
if err := writeCgroupFile(root, "cgroup.subtree_control", enable); err != nil {
return nil, err
}
tree := &cgroupTree{root: root, jails: filepath.Join(root, jailsCgroup)}
if err := mkdirCgroup(tree.jails); err != nil {
return nil, err
}
if err := writeCgroupFile(tree.jails, "cgroup.subtree_control", enable); err != nil {
return nil, err
}
if err := tree.removeLeftovers(); err != nil {
return nil, err
}
return tree, nil
}
func mkdirCgroup(path string) error {
if err := os.Mkdir(path, cgroupDirMode); err != nil && !errors.Is(err, fs.ErrExist) {
return fmt.Errorf("sandbox.mkdirCgroup - create %s: %w", filepath.Base(path), err)
}
return nil
}
// moveProcesses moves every process of the from cgroup into the to cgroup.
func moveProcesses(from, to string) error {
for range moveAttempts {
pids, err := readPIDs(from)
if err != nil {
return err
}
if len(pids) == 0 {
return nil
}
for _, pid := range pids {
err := writeCgroupFile(to, "cgroup.procs", strconv.Itoa(pid))
if err != nil && !errors.Is(err, syscall.ESRCH) {
return err
}
}
}
return errors.New("sandbox.moveProcesses - processes keep appearing in the root cgroup")
}
func readPIDs(cgroup string) ([]int, error) {
content, err := os.ReadFile(filepath.Join(cgroup, "cgroup.procs"))
if err != nil {
return nil, fmt.Errorf("sandbox.readPIDs - read procs: %w", err)
}
var pids []int
for field := range strings.FieldsSeq(string(content)) {
pid, err := strconv.Atoi(field)
if err != nil {
return nil, fmt.Errorf("sandbox.readPIDs - parse pid: %w", err)
}
pids = append(pids, pid)
}
return pids, nil
}
// removeLeftovers kills and removes run cgroups of an earlier process.
func (t *cgroupTree) removeLeftovers() error {
entries, err := os.ReadDir(t.jails)
if err != nil {
return fmt.Errorf("sandbox.cgroupTree.removeLeftovers - list: %w", err)
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
run := &runCgroup{path: filepath.Join(t.jails, entry.Name())}
if err := run.remove(context.Background()); err != nil {
return err
}
}
return nil
}
// leftoverRuns returns the names of run cgroups that still exist.
func (t *cgroupTree) leftoverRuns() ([]string, error) {
entries, err := os.ReadDir(t.jails)
if err != nil {
return nil, fmt.Errorf("sandbox.cgroupTree.leftoverRuns - list: %w", err)
}
var names []string
for _, entry := range entries {
if entry.IsDir() {
names = append(names, entry.Name())
}
}
return names, nil
}
// cgroupLimits are the controller values of one run cgroup.
type cgroupLimits struct {
memoryBytes int64
processes int
}
// runCgroup is the cgroup of one run. dir is an open descriptor of the
// directory for CLONE_INTO_CGROUP.
type runCgroup struct {
path string
dir *os.File
}
func (t *cgroupTree) create(ctx context.Context, name string, limits cgroupLimits) (*runCgroup, error) {
cleanupCtx := context.WithoutCancel(ctx)
path := filepath.Join(t.jails, name)
if err := os.Mkdir(path, cgroupDirMode); err != nil {
return nil, fmt.Errorf("sandbox.cgroupTree.create - create: %w", err)
}
run := &runCgroup{path: path}
settings := []struct{ file, value string }{
{"memory.max", strconv.FormatInt(limits.memoryBytes, 10)},
{"memory.swap.max", "0"},
{"pids.max", strconv.Itoa(limits.processes)},
{"cpu.max", cpuQuota},
}
for _, setting := range settings {
err := writeCgroupFile(path, setting.file, setting.value)
if errors.Is(err, fs.ErrNotExist) && setting.file == "memory.swap.max" {
// A kernel without swap accounting has no swap to limit.
continue
}
if err != nil {
return nil, errors.Join(err, run.remove(cleanupCtx))
}
}
dir, err := os.Open(path)
if err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.cgroupTree.create - open: %w", err), run.remove(cleanupCtx))
}
run.dir = dir
return run, nil
}
// cgroupStats are the counters the supervisor reads during and after a run.
type cgroupStats struct {
cpuUsage time.Duration
oomKills int64
pidsLimits int64
}
func (c *runCgroup) stats() (cgroupStats, error) {
var stats cgroupStats
cpu, err := readKeyedFile(c.path, "cpu.stat")
if err != nil {
return stats, err
}
stats.cpuUsage = time.Duration(cpu["usage_usec"]) * time.Microsecond
memory, err := readKeyedFile(c.path, "memory.events")
if err != nil {
return stats, err
}
stats.oomKills = memory["oom_kill"] + memory["oom_group_kill"]
pids, err := readKeyedFile(c.path, "pids.events")
if err != nil {
return stats, err
}
stats.pidsLimits = pids["max"]
return stats, nil
}
// kill stops every process of the cgroup.
func (c *runCgroup) kill() error {
err := writeCgroupFile(c.path, "cgroup.kill", "1")
if !errors.Is(err, fs.ErrNotExist) {
return err
}
// Kernels before 5.14 have no cgroup.kill; signal each process instead.
pids, err := readPIDs(c.path)
if err != nil {
return err
}
for _, pid := range pids {
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return fmt.Errorf("sandbox.runCgroup.kill - signal: %w", err)
}
}
return nil
}
// killExcept kills every process of the cgroup except keep. Killing the
// jailed processes but not nsjail lets nsjail reap its child and report how it
// ended; once the namespace's first process dies, the kernel kills the rest
// of the PID namespace.
func (c *runCgroup) killExcept(keep int) error {
pids, err := readPIDs(c.path)
if err != nil {
return err
}
for _, pid := range pids {
if pid == keep {
continue
}
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return fmt.Errorf("sandbox.runCgroup.killExcept - signal: %w", err)
}
}
return nil
}
// remove kills what is left, waits until the cgroup is empty, and deletes it.
func (c *runCgroup) remove(ctx context.Context) error {
if c.dir != nil {
_ = c.dir.Close() // The descriptor only served CLONE_INTO_CGROUP.
c.dir = nil
}
if err := c.kill(); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
ctx, cancel := context.WithTimeout(ctx, cgroupDrainTimeout)
defer cancel()
for {
err := os.Remove(c.path)
if err == nil || errors.Is(err, fs.ErrNotExist) {
return nil
}
if !errors.Is(err, syscall.EBUSY) {
return fmt.Errorf("sandbox.runCgroup.remove - remove: %w", err)
}
select {
case <-ctx.Done():
return fmt.Errorf("sandbox.runCgroup.remove - processes did not exit: %w", ctx.Err())
case <-time.After(cgroupDrainPoll):
}
}
}
func writeCgroupFile(dir, name, value string) error {
path := filepath.Join(dir, name)
// O_TRUNC is not allowed on cgroup files; each write is one operation.
file, err := os.OpenFile(path, os.O_WRONLY, cgroupFileMode)
if err != nil {
return fmt.Errorf("sandbox.writeCgroupFile - open %s: %w", name, err)
}
_, writeErr := file.WriteString(value)
closeErr := file.Close()
if writeErr != nil {
return fmt.Errorf("sandbox.writeCgroupFile - write %s: %w", name, writeErr)
}
if closeErr != nil {
return fmt.Errorf("sandbox.writeCgroupFile - close %s: %w", name, closeErr)
}
return nil
}
// readKeyedFile parses a flat "key value" cgroup file.
func readKeyedFile(dir, name string) (map[string]int64, error) {
content, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return nil, fmt.Errorf("sandbox.readKeyedFile - read %s: %w", name, err)
}
values := make(map[string]int64)
scanner := bufio.NewScanner(bytes.NewReader(content))
for scanner.Scan() {
key, value, found := strings.Cut(scanner.Text(), " ")
if !found {
continue
}
number, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
if err != nil {
continue
}
values[key] = number
}
return values, nil
}
// peakMemoryKB returns memory.peak in KiB, or 0 when the kernel has no
// such file. It is the exact high-water mark of every process of the run,
// nsjail included, plus file cache charged to the run. Unlike ru_maxrss it
// never includes the runner itself: Go starts nsjail through vfork, so the
// rusage of nsjail inherits the runner's resident set at exec.
func (c *runCgroup) peakMemoryKB() int64 {
content, err := os.ReadFile(filepath.Join(c.path, "memory.peak"))
if err != nil {
return 0
}
peak, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64)
if err != nil {
return 0
}
return peak / bytesPerKB
}
+384
View File
@@ -0,0 +1,384 @@
package sandbox
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"os/exec"
"sync"
"time"
)
const (
// nsjailProcesses is the supervising nsjail process inside the run
// cgroup; it is added to the process limit of the program.
nsjailProcesses = 1
// maxNsjailLog bounds the nsjail log kept for one run.
maxNsjailLog = 64 << 10
runNameBytes = 8
readChunk = 32 << 10
)
// terminationCanceled marks a run stopped because its context ended.
const terminationCanceled Termination = "canceled"
// Executor runs commands in nsjail. It is safe for concurrent use.
type Executor struct {
cfg Config
cgroups *cgroupTree
policy string
}
// New checks the host and prepares the cgroup hierarchy and the work root.
func New(cfg Config) (*Executor, error) {
if err := platformSupported(); err != nil {
return nil, err
}
if err := validateConfig(cfg); err != nil {
return nil, err
}
info, err := os.Stat(cfg.NsjailPath)
if err != nil {
return nil, fmt.Errorf("sandbox.New - stat nsjail: %w", err)
}
if info.IsDir() || info.Mode().Perm()&0o111 == 0 {
return nil, errors.New("sandbox.New - nsjail is not an executable file")
}
if err := emptyWorkRoot(cfg.WorkRoot); err != nil {
return nil, err
}
tree, err := prepareCgroups(cfg.CgroupRoot)
if err != nil {
return nil, err
}
return &Executor{cfg: cfg, cgroups: tree, policy: seccompPolicy()}, nil
}
func validateConfig(cfg Config) error {
switch {
case cfg.SandboxUID <= 0 || cfg.SandboxGID <= 0:
return errors.New("sandbox.validateConfig - the sandbox user must not be root")
case cfg.MaxProcesses <= 0:
return errors.New("sandbox.validateConfig - the process limit must be positive")
case cfg.TmpfsBytes <= 0 || cfg.FileSizeBytes <= 0 || cfg.OpenFiles <= 0:
return errors.New("sandbox.validateConfig - tmpfs, file size, and open file limits must be positive")
case cfg.StderrCaptureBytes <= 0 || cfg.PollInterval <= 0:
return errors.New("sandbox.validateConfig - stderr capture and poll interval must be positive")
case cfg.MemoryOverheadBytes < 0:
return errors.New("sandbox.validateConfig - the memory overhead must not be negative")
}
return nil
}
// NewBox creates the read-only file directory of a run.
func (e *Executor) NewBox(fileName string, content []byte) (*Box, error) {
return CreateBox(e.cfg.WorkRoot, fileName, content)
}
// Leftovers lists boxes and run cgroups that still exist. After every run
// has finished both lists are empty.
func (e *Executor) Leftovers() (boxes, cgroups []string, err error) {
entries, err := os.ReadDir(e.cfg.WorkRoot)
if err != nil {
return nil, nil, fmt.Errorf("sandbox.Executor.Leftovers - list work root: %w", err)
}
for _, entry := range entries {
boxes = append(boxes, entry.Name())
}
cgroups, err = e.cgroups.leftoverRuns()
return boxes, cgroups, err
}
// Run executes spec under limits. It returns an error only when the sandbox
// itself failed or ctx ended; every outcome caused by the program, including
// a limit, is a Result.
func (e *Executor) Run(ctx context.Context, spec Spec, limits Limits) (result Result, err error) {
cgroup, err := e.cgroups.create(ctx, newRunName(), cgroupLimits{
memoryBytes: limits.MemoryBytes + e.cfg.MemoryOverheadBytes,
processes: e.cfg.MaxProcesses + nsjailProcesses,
})
if err != nil {
return Result{}, err
}
defer func() {
// A cgroup that cannot be removed may still hold processes, so the
// run is not trustworthy.
if removeErr := cgroup.remove(context.WithoutCancel(ctx)); removeErr != nil {
err = errors.Join(err, removeErr)
}
}()
pipes, err := openPipes()
if err != nil {
return Result{}, err
}
defer pipes.closeAll()
// The watchdog stops a canceled run by killing its whole cgroup;
// CommandContext would kill only nsjail. The binary path comes from
// configuration and the arguments are built above.
cmd := exec.Command(e.cfg.NsjailPath, nsjailArgs(e.cfg, spec, limits, e.policy)...) //nolint:noctx,gosec // See the comment above.
// The runner environment, including any secret, never reaches nsjail.
cmd.Env = []string{}
cmd.Stdin = bytes.NewReader(spec.Stdin)
cmd.Stdout = pipes.stdoutWrite
cmd.Stderr = pipes.stderrWrite
cmd.ExtraFiles = []*os.File{pipes.logWrite}
attachToCgroup(cmd, cgroup)
started := time.Now()
if err := cmd.Start(); err != nil {
return Result{}, fmt.Errorf("sandbox.Executor.Run - start nsjail: %w", err)
}
pipes.closeWriteEnds()
stopper := &stopper{cgroup: cgroup, nsjailPID: cmd.Process.Pid}
var readers sync.WaitGroup
var stdout, stderr, nsjailLog []byte
readers.Go(func() {
stdout = readLimited(pipes.stdoutRead, limits.OutputBytes, func() { stopper.stop(TerminationOutput) })
})
readers.Go(func() { stderr = readTail(pipes.stderrRead, e.cfg.StderrCaptureBytes) })
readers.Go(func() { nsjailLog = readLimited(pipes.logRead, maxNsjailLog, func() {}) })
watchdogDone := make(chan struct{})
var watchdog sync.WaitGroup
watchdog.Go(func() { e.watch(ctx, cgroup, limits, stopper, watchdogDone) })
readers.Wait()
waitErr := cmd.Wait()
wallTime := time.Since(started)
close(watchdogDone)
watchdog.Wait()
var exitErr *exec.ExitError
if waitErr != nil && !errors.As(waitErr, &exitErr) {
return Result{}, fmt.Errorf("sandbox.Executor.Run - wait for nsjail: %w", waitErr)
}
stats, err := cgroup.stats()
if err != nil {
return Result{}, err
}
reason := stopper.reason()
if reason == terminationCanceled {
return Result{}, fmt.Errorf("sandbox.Executor.Run - run stopped: %w", context.Cause(ctx))
}
if reason == TerminationNone {
reason = terminationFromStats(stats, limits)
}
result = Result{
Stdout: stdout,
Stderr: stderr,
CPUTime: stats.cpuUsage,
WallTime: wallTime,
PeakMemoryKB: cgroup.peakMemoryKB(),
Termination: reason,
}
if result.PeakMemoryKB == 0 {
// Kernels before 5.19 have no memory.peak.
result.PeakMemoryKB = peakMemoryKB(cmd.ProcessState)
}
return result, applyExitStatus(&result, parseNsjailLog(nsjailLog), cmd.ProcessState)
}
// terminationFromStats finds a limit that stopped the run between two polls
// or that the program reached without being stopped.
func terminationFromStats(stats cgroupStats, limits Limits) Termination {
switch {
case stats.oomKills > 0:
return TerminationMemory
case stats.pidsLimits > 0:
return TerminationProcesses
case stats.cpuUsage > limits.CPUTime:
return TerminationCPUTime
default:
return TerminationNone
}
}
// applyExitStatus fills the exit code and signal from the nsjail log.
func applyExitStatus(result *Result, report nsjailReport, state *os.ProcessState) error {
stoppedBySupervisor := result.Termination != TerminationNone
switch {
case report.failure != "" && !stoppedBySupervisor:
return fmt.Errorf("sandbox.applyExitStatus - nsjail failed: %s", report.failure)
case report.reported:
result.ExitCode = report.exitCode
result.Signal = report.signal
case stoppedBySupervisor:
// nsjail was killed together with the program.
result.ExitCode = -1
result.Signal = signalKill
default:
return fmt.Errorf("sandbox.applyExitStatus - nsjail ended without a report: %s", state.String())
}
return nil
}
// watch enforces the CPU and wall-clock limits and stops a run as soon as
// the cgroup reports an OOM kill or a refused fork.
func (e *Executor) watch(ctx context.Context, cgroup *runCgroup, limits Limits, stopper *stopper, done <-chan struct{}) {
ticker := time.NewTicker(e.cfg.PollInterval)
defer ticker.Stop()
wall := time.NewTimer(limits.WallTime)
defer wall.Stop()
for {
select {
case <-done:
return
case <-ctx.Done():
stopper.stop(terminationCanceled)
case <-wall.C:
stopper.stop(TerminationWallTime)
case <-ticker.C:
stopper.enforceGrace()
stats, err := cgroup.stats()
if err != nil {
// The cgroup is gone only after the run ended.
continue
}
if reason := terminationFromStats(stats, limits); reason != TerminationNone {
stopper.stop(reason)
}
}
}
}
// stopper records the first reason a run was stopped and kills the jailed
// processes. nsjail stays alive to reap its child, so no orphan is left to
// the init process; if nsjail does not exit within stopGrace, the watchdog
// kills the whole cgroup.
type stopper struct {
cgroup *runCgroup
nsjailPID int
mu sync.Mutex
first Termination
stoppedAt time.Time
}
// stopGrace is how long nsjail may take to reap a killed program.
const stopGrace = time.Second
func (s *stopper) stop(reason Termination) {
s.mu.Lock()
defer s.mu.Unlock()
if s.first == TerminationNone {
s.first = reason
s.stoppedAt = time.Now()
}
// Killing again is harmless and covers processes forked meanwhile.
_ = s.cgroup.killExcept(s.nsjailPID) // A failure surfaces when the cgroup is removed.
}
// enforceGrace kills nsjail too when it outlives the grace period.
func (s *stopper) enforceGrace() {
s.mu.Lock()
defer s.mu.Unlock()
if s.first != TerminationNone && time.Since(s.stoppedAt) > stopGrace {
_ = s.cgroup.kill() // A failure surfaces when the cgroup is removed.
}
}
func (s *stopper) reason() Termination {
s.mu.Lock()
defer s.mu.Unlock()
return s.first
}
// readLimited reads r to the end and keeps at most limit bytes; onExceeded
// runs once when more arrives. Reading continues so the writer never blocks.
func readLimited(r io.Reader, limit int64, onExceeded func()) []byte {
var kept bytes.Buffer
var exceeded bool
chunk := make([]byte, readChunk)
for {
n, err := r.Read(chunk)
if n > 0 {
room := limit - int64(kept.Len())
if int64(n) > room {
kept.Write(chunk[:max(room, 0)])
if !exceeded {
exceeded = true
onExceeded()
}
} else {
kept.Write(chunk[:n])
}
}
if err != nil {
return kept.Bytes()
}
}
}
// readTail reads r to the end and keeps its last limit bytes.
func readTail(r io.Reader, limit int) []byte {
var kept []byte
chunk := make([]byte, readChunk)
for {
n, err := r.Read(chunk)
kept = append(kept, chunk[:n]...)
if len(kept) > 2*limit {
kept = append([]byte(nil), kept[len(kept)-limit:]...)
}
if err != nil {
if len(kept) > limit {
kept = kept[len(kept)-limit:]
}
return kept
}
}
}
type runPipes struct {
stdoutRead, stdoutWrite *os.File
stderrRead, stderrWrite *os.File
logRead, logWrite *os.File
}
func openPipes() (*runPipes, error) {
pipes := &runPipes{}
var err error
if pipes.stdoutRead, pipes.stdoutWrite, err = os.Pipe(); err != nil {
return nil, fmt.Errorf("sandbox.openPipes - stdout: %w", err)
}
if pipes.stderrRead, pipes.stderrWrite, err = os.Pipe(); err != nil {
pipes.closeAll()
return nil, fmt.Errorf("sandbox.openPipes - stderr: %w", err)
}
if pipes.logRead, pipes.logWrite, err = os.Pipe(); err != nil {
pipes.closeAll()
return nil, fmt.Errorf("sandbox.openPipes - log: %w", err)
}
return pipes, nil
}
func (p *runPipes) closeWriteEnds() {
for _, file := range []**os.File{&p.stdoutWrite, &p.stderrWrite, &p.logWrite} {
if *file != nil {
_ = (*file).Close() // The child holds its own copy.
*file = nil
}
}
}
func (p *runPipes) closeAll() {
p.closeWriteEnds()
for _, file := range []**os.File{&p.stdoutRead, &p.stderrRead, &p.logRead} {
if *file != nil {
_ = (*file).Close() // Reading has finished.
*file = nil
}
}
}
func newRunName() string {
name := make([]byte, runNameBytes)
_, _ = rand.Read(name) // crypto/rand.Read never fails on supported platforms.
return "run-" + hex.EncodeToString(name)
}
+132
View File
@@ -0,0 +1,132 @@
package sandbox
import (
"bufio"
"bytes"
"math"
"regexp"
"strconv"
"time"
)
const (
// nsjailLogFD is the descriptor of the nsjail log pipe in the child.
nsjailLogFD = 3
// addressSpaceLimitMB stays far above the cgroup memory limit, so that
// memory pressure ends in a cgroup OOM kill (memory_limit_exceeded)
// instead of an allocation failure inside the program; it still stops
// absurd reservations.
addressSpaceLimitMB = 4096
// nsjailTimeBackstop is added to the wall-clock limit for nsjail's own
// time limit, which only matters if the supervisor fails to stop a run.
nsjailTimeBackstop = 2 * time.Second
// cpuRlimitBackstop is added to the CPU limit for RLIMIT_CPU; the
// supervisor's cgroup watchdog normally stops a run first.
cpuRlimitBackstop = time.Second
sandboxHostname = "sandbox"
bytesPerMB = 1 << 20
)
// nsjailArgs returns the nsjail command line for one run. Every isolation
// switch is explicit so that a change in nsjail defaults cannot weaken it.
func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []string {
args := []string{
"--mode", "o",
"--log_fd", strconv.Itoa(nsjailLogFD),
"--hostname", sandboxHostname,
"--cwd", ScratchPath,
// Inside and outside the user namespace the program is the same
// unprivileged ID, never root.
"--user", idMapping(cfg.SandboxUID),
"--group", idMapping(cfg.SandboxGID),
"--time_limit", strconv.Itoa(ceilSeconds(limits.WallTime + nsjailTimeBackstop)),
"--rlimit_as", strconv.Itoa(addressSpaceLimitMB),
"--rlimit_cpu", strconv.Itoa(ceilSeconds(limits.CPUTime + cpuRlimitBackstop)),
"--rlimit_fsize", strconv.Itoa(ceilMB(cfg.FileSizeBytes)),
"--rlimit_nofile", strconv.Itoa(cfg.OpenFiles),
"--rlimit_core", "0",
"--disable_proc",
// A new network namespace is nsjail's default; the empty namespace
// also has no loopback interface.
"--iface_no_lo",
"--seccomp_string", seccompPolicy,
}
for _, mount := range cfg.ReadOnlyMounts {
args = append(args, "--bindmount_ro", mount)
}
args = append(args,
"--bindmount_ro", spec.BoxDir+":"+BoxPath,
"--bindmount", "/dev/null",
"--bindmount_ro", "/dev/urandom",
"--mount", "none:"+ScratchPath+":tmpfs:size="+strconv.FormatInt(cfg.TmpfsBytes, 10),
)
for _, variable := range cfg.Env {
args = append(args, "--env", variable)
}
args = append(args, "--")
return append(args, spec.Argv...)
}
func idMapping(id int) string {
value := strconv.Itoa(id)
return value + ":" + value + ":1"
}
func ceilSeconds(duration time.Duration) int {
return int(math.Ceil(duration.Seconds()))
}
func ceilMB(size int64) int {
return max(1, int((size+bytesPerMB-1)/bytesPerMB))
}
var (
childExited = regexp.MustCompile(`\) exited with status: (\d+)`)
childSignaled = regexp.MustCompile(`\) terminated with signal: [^(]*\((\d+)\)`)
)
// nsjailReport is what the nsjail log says about the jailed command.
type nsjailReport struct {
exitCode int
signal int
// reported is true when the log names how the command ended.
reported bool
// failure is the first error line of nsjail itself, without timestamps.
failure string
}
const maxFailureExcerpt = 200
// parseNsjailLog reads the nsjail log. A launch failure is reported by error
// ([E]) or fatal ([F]) lines; the log never contains program input or output.
func parseNsjailLog(log []byte) nsjailReport {
var report nsjailReport
scanner := bufio.NewScanner(bytes.NewReader(log))
for scanner.Scan() {
line := scanner.Bytes()
if report.failure == "" && (bytes.HasPrefix(line, []byte("[E]")) || bytes.HasPrefix(line, []byte("[F]"))) {
report.failure = failureExcerpt(line)
}
if match := childExited.FindSubmatch(line); match != nil {
report.exitCode, _ = strconv.Atoi(string(match[1]))
report.reported = true
}
if match := childSignaled.FindSubmatch(line); match != nil {
report.signal, _ = strconv.Atoi(string(match[1]))
report.exitCode = -1
report.reported = true
}
}
return report
}
func failureExcerpt(line []byte) string {
// Drop the "[E][timestamp][pid] " prefix; keep the function and message.
if index := bytes.LastIndexByte(line, ']'); index >= 0 && index+1 < len(line) {
line = bytes.TrimSpace(line[index+1:])
}
if len(line) > maxFailureExcerpt {
line = line[:maxFailureExcerpt]
}
return string(bytes.ToValidUTF8(line, []byte("?")))
}
+38
View File
@@ -0,0 +1,38 @@
//go:build linux
package sandbox
import (
"os"
"os/exec"
"syscall"
)
const signalKill = int(syscall.SIGKILL)
func platformSupported() error {
return nil
}
// attachToCgroup starts nsjail directly inside the run cgroup, so no
// instruction of nsjail or of the program runs outside its limits, and kills
// nsjail if the runner dies.
func attachToCgroup(cmd *exec.Cmd, cgroup *runCgroup) {
cmd.SysProcAttr = &syscall.SysProcAttr{
UseCgroupFD: true,
CgroupFD: int(cgroup.dir.Fd()),
Setpgid: true,
Pdeathsig: syscall.SIGKILL,
}
}
// peakMemoryKB returns ru_maxrss of nsjail in KiB, the fallback when the
// kernel has no memory.peak. It overstates small programs because it
// includes the runner's resident set at exec.
func peakMemoryKB(state *os.ProcessState) int64 {
usage, ok := state.SysUsage().(*syscall.Rusage)
if !ok {
return 0
}
return usage.Maxrss
}
+21
View File
@@ -0,0 +1,21 @@
//go:build !linux
package sandbox
import (
"os"
"os/exec"
)
// signalKill is the Linux SIGKILL number reported by stopped runs.
const signalKill = 9
func platformSupported() error {
return ErrUnsupportedPlatform
}
func attachToCgroup(*exec.Cmd, *runCgroup) {}
func peakMemoryKB(*os.ProcessState) int64 {
return 0
}
+103
View File
@@ -0,0 +1,103 @@
// Package sandbox runs one untrusted command inside nsjail.
//
// Every run gets its own cgroup v2 directory with CPU, memory, swap, and
// process limits. The supervisor creates that cgroup itself and starts nsjail
// directly inside it (CLONE_INTO_CGROUP), so the limits cover nsjail and every
// jailed process, the supervisor can read exact OOM, process-limit, and CPU
// counters, and cgroup.kill removes the whole tree. nsjail adds the namespaces
// (no network, own PID, mount, IPC, UTS, user, and cgroup namespaces), the
// read-only file system with a tmpfs work directory, the unprivileged user,
// rlimits, and the seccomp policy.
package sandbox
import (
"errors"
"time"
)
// Termination names the limit that stopped a run.
type Termination string
const (
// TerminationNone means that the program stopped by itself.
TerminationNone Termination = ""
// TerminationCPUTime means the CPU time limit.
TerminationCPUTime Termination = "cpu_time"
// TerminationWallTime means the wall-clock limit.
TerminationWallTime Termination = "wall_time"
// TerminationMemory means the cgroup memory limit.
TerminationMemory Termination = "memory"
// TerminationOutput means the standard output limit.
TerminationOutput Termination = "output"
// TerminationProcesses means the cgroup process limit.
TerminationProcesses Termination = "processes"
)
// Jail paths seen by the jailed program.
const (
// BoxPath is the read-only directory with the files of a run.
BoxPath = "/box"
// ScratchPath is the writable tmpfs and the working directory.
ScratchPath = "/tmp"
)
// ErrUnsupportedPlatform reports that the sandbox needs Linux.
var ErrUnsupportedPlatform = errors.New("sandbox requires Linux with cgroup v2")
// Limits bound one run.
type Limits struct {
CPUTime time.Duration
WallTime time.Duration
MemoryBytes int64
OutputBytes int64
}
// Spec is one command to run in the jail.
type Spec struct {
// Argv is the command inside the jail; Argv[0] is an absolute path.
Argv []string
// Stdin is written to the standard input of the command.
Stdin []byte
// BoxDir is the host directory mounted read-only at BoxPath.
BoxDir string
}
// Result describes a finished run. It never contains host paths.
type Result struct {
Stdout []byte
// Stderr holds at most Config.StderrCaptureBytes of standard error.
Stderr []byte
// ExitCode is the exit status of the command, or -1 when a signal stopped it.
ExitCode int
// Signal is the signal that stopped the command, or 0.
Signal int
CPUTime time.Duration
WallTime time.Duration
PeakMemoryKB int64
Termination Termination
}
// Config holds the host-side sandbox settings shared by every run.
type Config struct {
NsjailPath string
// CgroupRoot is a cgroup v2 directory delegated to the runner.
CgroupRoot string
// WorkRoot holds one directory per run; it is emptied at startup.
WorkRoot string
SandboxUID int
SandboxGID int
// MaxProcesses bounds processes and threads of a run, nsjail excluded.
MaxProcesses int
// MemoryOverheadBytes is added to the memory limit for nsjail itself.
MemoryOverheadBytes int64
TmpfsBytes int64
FileSizeBytes int64
OpenFiles int
StderrCaptureBytes int
// ReadOnlyMounts are host paths mounted read-only at the same place.
ReadOnlyMounts []string
// Env is the complete environment of the jailed command.
Env []string
// PollInterval is how often the supervisor checks the cgroup counters.
PollInterval time.Duration
}
+212
View File
@@ -0,0 +1,212 @@
package sandbox
import (
"bytes"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
func testConfig() Config {
return Config{
NsjailPath: "/usr/bin/nsjail",
SandboxUID: 99999,
SandboxGID: 99999,
MaxProcesses: 16,
TmpfsBytes: 16 << 20,
FileSizeBytes: 8 << 20,
OpenFiles: 64,
StderrCaptureBytes: 1024,
ReadOnlyMounts: []string{"/usr", "/lib"},
Env: []string{"LANG=C.UTF-8"},
PollInterval: time.Millisecond,
}
}
// flagValue returns the value after the first occurrence of flag.
func flagValue(t *testing.T, args []string, flag string) string {
t.Helper()
index := slices.Index(args, flag)
if index < 0 || index+1 >= len(args) {
t.Fatalf("flag %s is missing in %q", flag, args)
}
return args[index+1]
}
func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) {
t.Parallel()
spec := Spec{Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"}, BoxDir: "/work/run-1"}
limits := Limits{CPUTime: 1500 * time.Millisecond, WallTime: 3500 * time.Millisecond, MemoryBytes: 64 << 20, OutputBytes: 1 << 16}
args := nsjailArgs(testConfig(), spec, limits, "POLICY")
for _, forbidden := range []string{
"--disable_clone_newnet", "-N", "--disable_clone_newuser", "--disable_clone_newns", "--disable_clone_newpid",
"--keep_caps", "--cap", "--disable_no_new_privs", "--rw", "--keep_env", "--chroot", "--proc_rw", "--use_pasta",
} {
if slices.Contains(args, forbidden) {
t.Errorf("args contain %s: %q", forbidden, args)
}
}
checks := map[string]string{
"--mode": "o",
"--user": "99999:99999:1",
"--group": "99999:99999:1",
"--cwd": ScratchPath,
"--rlimit_cpu": "3",
"--rlimit_fsize": "8",
"--rlimit_nofile": "64",
"--rlimit_core": "0",
"--time_limit": "6",
"--seccomp_string": "POLICY",
"--mount": "none:/tmp:tmpfs:size=16777216",
}
for flag, want := range checks {
if got := flagValue(t, args, flag); got != want {
t.Errorf("%s = %q, want %q", flag, got, want)
}
}
for _, required := range []string{"--disable_proc", "--iface_no_lo"} {
if !slices.Contains(args, required) {
t.Errorf("args miss %s", required)
}
}
if !slices.Contains(args, "/work/run-1:/box") {
t.Errorf("the box is not mounted at /box: %q", args)
}
separator := slices.Index(args, "--")
if separator < 0 || !slices.Equal(args[separator+1:], spec.Argv) {
t.Errorf("command after -- = %q, want %q", args[separator+1:], spec.Argv)
}
for _, writable := range writableMounts(args) {
if writable != "/dev/null" {
t.Errorf("unexpected writable bind mount %q", writable)
}
}
}
func writableMounts(args []string) []string {
var mounts []string
for index, arg := range args {
if arg == "--bindmount" && index+1 < len(args) {
mounts = append(mounts, args[index+1])
}
}
return mounts
}
func TestSeccompPolicyKillsNamespaceAndDebugSyscalls(t *testing.T) {
t.Parallel()
policy := seccompPolicy()
for _, fragment := range []string{"ptrace", "unshare", "setns", "mount", "bpf", "io_uring_setup", "clone(flags)", "ERRNO(38) { clone3 }", "socket(domain)", "USE runner DEFAULT ALLOW"} {
if !strings.Contains(policy, fragment) {
t.Errorf("policy misses %q", fragment)
}
}
}
func TestParseNsjailLog(t *testing.T) {
t.Parallel()
exited := parseNsjailLog([]byte("[I][2026] Executing '/usr/local/bin/python3'\n[I][2026] pid=12 ([STANDALONE MODE]) exited with status: 3, (PIDs left: 0)\n"))
if !exited.reported || exited.exitCode != 3 || exited.signal != 0 || exited.failure != "" {
t.Fatalf("exited report = %+v", exited)
}
signaled := parseNsjailLog([]byte("[W][2026][11] seccompViolation():291 pid=12 committed a syscall/seccomp violation\n[I][2026] pid=12 ([STANDALONE MODE]) terminated with signal: Bad system call (31), (PIDs left: 0)\n"))
if !signaled.reported || signaled.signal != 31 || signaled.exitCode != -1 || signaled.failure != "" {
t.Fatalf("signaled report = %+v", signaled)
}
failed := parseNsjailLog([]byte("[E][2026-10-10T23:37:27+0000][1] initNsInternal():361 chdir('/tmp'): No such file or directory\n[F][2026][1] runChild():506 Launching child process failed\n"))
if failed.failure != "initNsInternal():361 chdir('/tmp'): No such file or directory" {
t.Fatalf("failure = %q", failed.failure)
}
}
func TestApplyExitStatusSeparatesSandboxFailures(t *testing.T) {
t.Parallel()
var result Result
if err := applyExitStatus(&result, nsjailReport{failure: "execve failed", reported: true, signal: 9}, nil); err == nil {
t.Fatal("a launch failure must be an error")
}
stopped := Result{Termination: TerminationWallTime}
if err := applyExitStatus(&stopped, nsjailReport{}, nil); err != nil || stopped.Signal != signalKill {
t.Fatalf("stopped run = %+v, %v; want SIGKILL without an error", stopped, err)
}
}
func TestReadersBoundWhatTheyKeep(t *testing.T) {
t.Parallel()
exceeded := 0
kept := readLimited(bytes.NewReader(bytes.Repeat([]byte("a"), 100_000)), 10, func() { exceeded++ })
if len(kept) != 10 || exceeded != 1 {
t.Fatalf("readLimited kept %d bytes and reported %d times", len(kept), exceeded)
}
tail := readTail(strings.NewReader(strings.Repeat("x", 100_000)+"END"), 8)
if string(tail) != "xxxxxEND" {
t.Fatalf("readTail = %q", tail)
}
}
func TestCgroupStatsAndTermination(t *testing.T) {
t.Parallel()
dir := t.TempDir()
files := map[string]string{
"cpu.stat": "usage_usec 1500000\nuser_usec 1400000\n",
"memory.events": "low 0\nhigh 0\nmax 4\noom 1\noom_kill 1\noom_group_kill 0\n",
"pids.events": "max 0\n",
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
stats, err := (&runCgroup{path: dir}).stats()
if err != nil {
t.Fatalf("stats: %v", err)
}
if stats.cpuUsage != 1500*time.Millisecond || stats.oomKills != 1 || stats.pidsLimits != 0 {
t.Fatalf("stats = %+v", stats)
}
limits := Limits{CPUTime: time.Second}
if got := terminationFromStats(stats, limits); got != TerminationMemory {
t.Fatalf("termination = %q, want memory before CPU time", got)
}
if got := terminationFromStats(cgroupStats{pidsLimits: 1}, limits); got != TerminationProcesses {
t.Fatalf("termination = %q, want processes", got)
}
if got := terminationFromStats(cgroupStats{cpuUsage: 2 * time.Second}, limits); got != TerminationCPUTime {
t.Fatalf("termination = %q, want cpu_time", got)
}
}
func TestBoxIsReadOnlyAndRemovable(t *testing.T) {
t.Parallel()
root := t.TempDir()
box, err := CreateBox(root, "main.py", []byte("print(1)"))
if err != nil {
t.Fatalf("CreateBox: %v", err)
}
info, err := os.Stat(filepath.Join(box.Dir(), "main.py"))
if err != nil || info.Mode().Perm() != boxFileMode {
t.Fatalf("source file mode = %v, %v", info.Mode(), err)
}
if err := box.Remove(); err != nil {
t.Fatalf("Remove: %v", err)
}
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Fatalf("root after Remove = %v, %v", entries, err)
}
for _, name := range []string{"", "../main.py", ".hidden", "dir/main.py"} {
if _, err := CreateBox(root, name, nil); err == nil {
t.Errorf("CreateBox accepted file name %q", name)
}
}
}
+62
View File
@@ -0,0 +1,62 @@
package sandbox
import (
"runtime"
"strconv"
"strings"
)
// Linux constants used by the seccomp policy.
const (
afUnix = 1
// cloneNamespaceFlags is CLONE_NEWNS | CLONE_NEWCGROUP | CLONE_NEWUTS |
// CLONE_NEWIPC | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET.
cloneNamespaceFlags = "0x7e020000"
errnoENOSYS = "38"
errnoEAFNOSUPPORT = "97"
)
// killedSyscalls end the whole process with SIGSYS. An ordinary program
// never needs them; they open kernel attack surface or would let the program
// observe or change the jail: debugging other processes, mounts and
// namespaces, keyrings, eBPF, perf, userfaultfd, io_uring, kernel modules,
// and host clock, name, and swap administration.
var killedSyscalls = []string{
"acct", "add_key", "adjtimex", "bpf", "chroot", "clock_settime",
"delete_module", "finit_module", "fsconfig", "fsmount", "fsopen", "fspick",
"init_module", "io_uring_enter", "io_uring_register", "io_uring_setup",
"kexec_file_load", "kexec_load", "keyctl", "mount", "mount_setattr",
"move_mount", "name_to_handle_at", "open_by_handle_at", "open_tree",
"perf_event_open", "pivot_root", "process_vm_readv", "process_vm_writev",
"ptrace", "quotactl", "reboot", "request_key", "sethostname",
"setdomainname", "setns", "settimeofday", "swapoff", "swapon", "syslog",
"unshare", "userfaultfd",
}
// seccompPolicy returns the kafel policy for the build architecture.
//
// It is a deny list on top of the namespaces, the dropped capabilities, and
// no_new_privs: the program keeps the syscalls an interpreter or a compiled
// program needs, while namespace creation through clone is killed, clone3 is
// reported as missing so that libc falls back to the filtered clone, and
// sockets other than AF_UNIX fail with EAFNOSUPPORT.
func seccompPolicy() string {
killed := append([]string{umountSyscall()}, killedSyscalls...)
var policy strings.Builder
policy.WriteString("POLICY runner {\n")
policy.WriteString(" KILL_PROCESS {\n ")
policy.WriteString(strings.Join(killed, ",\n "))
policy.WriteString(",\n clone(flags) { (flags & " + cloneNamespaceFlags + ") != 0 }\n },\n")
policy.WriteString(" ERRNO(" + errnoENOSYS + ") { clone3 },\n")
policy.WriteString(" ERRNO(" + errnoEAFNOSUPPORT + ") { socket(domain) { domain != " + strconv.Itoa(afUnix) + " } }\n")
policy.WriteString("}\nUSE runner DEFAULT ALLOW\n")
return policy.String()
}
// umountSyscall returns the kafel name of umount2 for the architecture.
func umountSyscall() string {
if runtime.GOARCH == "arm64" {
return "umount"
}
return "umount2"
}
+84
View File
@@ -0,0 +1,84 @@
package sandbox
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
const (
// The jailed user only reads and traverses the box; it owns nothing.
boxDirMode = 0o555
boxFileMode = 0o444
// ownerOnlyMode lets the supervisor delete the box again.
ownerOnlyMode = 0o700
// workRootMode lets nsjail traverse to a box without listing the root:
// inside its user namespace host root's DAC override does not apply.
workRootMode = 0o711
boxPrefix = "run-"
)
// Box is the host directory with the files of one run. It is mounted
// read-only into every jail of the run and removed with Remove.
type Box struct {
dir string
}
// Dir returns the host path of the box.
func (b *Box) Dir() string {
return b.dir
}
// CreateBox creates a box under root with one file.
func CreateBox(root, fileName string, content []byte) (*Box, error) {
if fileName == "" || fileName != filepath.Base(fileName) || strings.HasPrefix(fileName, ".") {
return nil, fmt.Errorf("sandbox.CreateBox - invalid file name %q", fileName)
}
dir, err := os.MkdirTemp(root, boxPrefix)
if err != nil {
return nil, fmt.Errorf("sandbox.CreateBox - create: %w", err)
}
box := &Box{dir: dir}
if err := os.WriteFile(filepath.Join(dir, fileName), content, boxFileMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - write: %w", err), box.Remove())
}
if err := os.Chmod(dir, boxDirMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - chmod: %w", err), box.Remove())
}
return box, nil
}
// Remove deletes the box and its files.
func (b *Box) Remove() error {
if err := os.Chmod(b.dir, ownerOnlyMode); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("sandbox.Box.Remove - chmod: %w", err)
}
if err := os.RemoveAll(b.dir); err != nil {
return fmt.Errorf("sandbox.Box.Remove - remove: %w", err)
}
return nil
}
// emptyWorkRoot removes every entry of root, for example boxes of a process
// that crashed, and creates root when it is missing.
func emptyWorkRoot(root string) error {
if err := os.MkdirAll(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - create: %w", err)
}
if err := os.Chmod(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - chmod: %w", err)
}
entries, err := os.ReadDir(root)
if err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - list: %w", err)
}
for _, entry := range entries {
box := &Box{dir: filepath.Join(root, entry.Name())}
if err := box.Remove(); err != nil {
return err
}
}
return nil
}
+237
View File
@@ -0,0 +1,237 @@
// Package server implements the runner HTTP API on the generated ogen server.
package server
import (
"context"
"errors"
"fmt"
"log/slog"
"math"
"net/http"
"strconv"
"time"
"github.com/google/uuid"
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
"lincodex/runner/internal/api"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/jobs"
"lincodex/runner/internal/judge"
)
// maxRunCPUBudget bounds tests multiplied by the per-test CPU limit, so one
// run cannot hold a sandbox slot for longer than a few minutes.
const maxRunCPUBudget = 300 * time.Second
// Bytes per unit of the contract limits.
const (
bytesPerKB = 1 << 10
bytesPerMB = 1 << 20
)
// Store keeps runs; jobs.Manager implements it.
type Store interface {
Submit(id uuid.UUID, request judge.Request) (jobs.Snapshot, bool, error)
Get(id uuid.UUID) (jobs.Snapshot, error)
}
// Handler implements the generated api.Handler.
type Handler struct {
store Store
supports func(language string) bool
ready func() bool
retryAfter time.Duration
logger *slog.Logger
}
var _ api.Handler = (*Handler)(nil)
// NewHandler returns the API handler.
func NewHandler(store Store, supports func(string) bool, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler {
return &Handler{store: store, supports: supports, ready: ready, retryAfter: retryAfter, logger: logger}
}
// GetRunnerHealthz reports that the process responds.
func (h *Handler) GetRunnerHealthz(context.Context) (*api.RunnerHealthResponse, error) {
return &api.RunnerHealthResponse{Status: api.RunnerHealthResponseStatusOk}, nil
}
// GetRunnerReadyz reports whether the sandbox accepts runs.
func (h *Handler) GetRunnerReadyz(context.Context) (api.GetRunnerReadyzRes, error) {
if h.ready() {
return &api.GetRunnerReadyzOK{Status: api.RunnerReadinessResponseStatusReady}, nil
}
return &api.GetRunnerReadyzServiceUnavailable{Status: api.RunnerReadinessResponseStatusNotReady}, nil
}
// SubmitRun starts a run or returns the run with the same ID and payload.
func (h *Handler) SubmitRun(_ context.Context, req *api.RunRequest, params api.SubmitRunParams) (api.SubmitRunRes, error) {
request, fieldErrors := h.toJudgeRequest(req)
if len(fieldErrors) > 0 {
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", fieldErrors...)
}
snapshot, created, err := h.store.Submit(params.RunID, request)
switch {
case errors.Is(err, jobs.ErrBusy):
retryAfter := int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32))
return &api.RunnerBusyHeaders{
RetryAfter: retryAfter,
Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, "Every sandbox slot is busy. Retry later with the same run ID."),
}, nil
case errors.Is(err, jobs.ErrPayloadMismatch):
return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A run with this ID exists with a different payload.")
case err != nil:
return nil, fmt.Errorf("server.Handler.SubmitRun - submit: %w", err)
}
status := toRunStatus(snapshot)
if created {
accepted := api.SubmitRunAccepted(status)
return &accepted, nil
}
existing := api.SubmitRunOK(status)
return &existing, nil
}
// GetRun returns the state and result of a run.
func (h *Handler) GetRun(_ context.Context, params api.GetRunParams) (*api.RunStatus, error) {
snapshot, err := h.store.Get(params.RunID)
if errors.Is(err, jobs.ErrNotFound) {
return nil, problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The runner holds no run with this ID.")
}
if err != nil {
return nil, fmt.Errorf("server.Handler.GetRun - get: %w", err)
}
status := toRunStatus(snapshot)
return &status, nil
}
// NewError maps errors of handlers and of the security check to problems.
func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
var securityErr *ogenerrors.SecurityError
if errors.As(err, &securityErr) {
return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.")
}
h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err)))
return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
}
// toJudgeRequest converts the request and checks the rules the schema
// cannot express. Field errors never echo submitted values.
func (h *Handler) toJudgeRequest(req *api.RunRequest) (judge.Request, []api.ProblemFieldError) {
var fieldErrors []api.ProblemFieldError
if !h.supports(string(req.Language)) {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/language"))
}
timeLimit := time.Duration(req.Limits.TimeLimitMs) * time.Millisecond
request := judge.Request{
Language: string(req.Language),
Source: req.Source,
Limits: judge.Limits{
TimeLimit: timeLimit,
MemoryBytes: int64(req.Limits.MemoryLimitMB) * bytesPerMB,
OutputBytes: int64(req.Limits.OutputLimitKB) * bytesPerKB,
},
Groups: make([]judge.Group, 0, len(req.Groups)),
}
groupIDs := make(map[api.TestKey]bool, len(req.Groups))
tests := 0
for groupIndex, group := range req.Groups {
groupPointer := "/groups/" + strconv.Itoa(groupIndex)
if groupIDs[group.ID] {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/id"))
}
groupIDs[group.ID] = true
converted := judge.Group{
ID: string(group.ID),
Visibility: judge.Visibility(group.Visibility),
Checker: checker.Spec{Kind: checker.Kind(group.Checker.Kind)},
Tests: make([]judge.Test, 0, len(group.Tests)),
}
testIDs := make(map[api.TestKey]bool, len(group.Tests))
for testIndex, test := range group.Tests {
if testIDs[test.ID] {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/tests/"+strconv.Itoa(testIndex)+"/id"))
}
testIDs[test.ID] = true
converted.Tests = append(converted.Tests, judge.Test{ID: string(test.ID), Input: test.Input, ExpectedOutput: test.ExpectedOutput})
}
tests += len(group.Tests)
request.Groups = append(request.Groups, converted)
}
if time.Duration(tests)*timeLimit > maxRunCPUBudget {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/limits/time_limit_ms"))
}
return request, fieldErrors
}
func toRunStatus(snapshot jobs.Snapshot) api.RunStatus {
status := api.RunStatus{RunID: snapshot.ID, State: api.RunStateRunning}
if snapshot.State != jobs.Finished || snapshot.Result == nil {
return status
}
status.State = api.RunStateFinished
status.Result = api.NewOptRunResult(toRunResult(*snapshot.Result))
return status
}
func toRunResult(result judge.Result) api.RunResult {
converted := api.RunResult{
Outcome: api.RunOutcome(result.Outcome),
Groups: make([]api.GroupResult, 0, len(result.Groups)),
DurationMs: result.Duration.Milliseconds(),
}
if result.Compile != nil {
compile := api.CompileResult{Outcome: api.RunOutcome(result.Compile.Outcome)}
if result.Compile.Diagnostic != "" {
compile.Diagnostic = api.NewOptString(result.Compile.Diagnostic)
}
converted.Compile = api.NewOptCompileResult(compile)
}
for _, group := range result.Groups {
converted.Groups = append(converted.Groups, toGroupResult(group))
}
return converted
}
func toGroupResult(group judge.GroupResult) api.GroupResult {
converted := api.GroupResult{
ID: api.TestKey(group.ID),
Visibility: api.TestVisibility(group.Visibility),
Outcome: api.RunOutcome(group.Outcome),
PassedTests: int32(group.Passed), //nolint:gosec // The contract allows at most 50 tests per group.
TotalTests: int32(group.Total), //nolint:gosec // The contract allows at most 50 tests per group.
Tests: make([]api.TestResult, 0, len(group.Tests)),
}
if len(group.Tests) > 0 {
converted.MaxTimeMs = api.NewOptInt64(group.MaxCPUTime.Milliseconds())
converted.MaxMemoryKB = api.NewOptInt64(group.MaxMemoryKB)
}
for _, test := range group.Tests {
converted.Tests = append(converted.Tests, toTestResult(test))
}
return converted
}
func toTestResult(test judge.TestResult) api.TestResult {
converted := api.TestResult{
ID: api.TestKey(test.ID),
Outcome: api.RunOutcome(test.Outcome),
TimeMs: test.CPUTime.Milliseconds(),
WallTimeMs: test.WallTime.Milliseconds(),
MemoryKB: test.MemoryKB,
}
if test.ExitCode != nil {
converted.ExitCode = api.NewOptInt32(int32(*test.ExitCode)) //nolint:gosec // Exit statuses are below 256.
}
if test.Signal != nil {
converted.Signal = api.NewOptInt32(int32(*test.Signal)) //nolint:gosec // Signal numbers are below 65.
}
if test.Limit != "" {
converted.Limit = api.NewOptTerminationLimit(api.TerminationLimit(test.Limit))
}
if test.Diagnostic != "" {
converted.Diagnostic = api.NewOptString(test.Diagnostic)
}
return converted
}
+95
View File
@@ -0,0 +1,95 @@
package server
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"github.com/go-faster/jx"
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/validate"
"lincodex/runner/internal/api"
)
const problemTypePrefix = "urn:lincodex:problem:"
// problemTitles are the fixed titles of the runner problem codes.
var problemTitles = map[api.ProblemCode]string{
api.ProblemCodeValidationFailed: "Request validation failed",
api.ProblemCodeUnauthenticated: "Authentication required",
api.ProblemCodeNotFound: "Not found",
api.ProblemCodeMethodNotAllowed: "Method not allowed",
api.ProblemCodePayloadTooLarge: "Payload too large",
api.ProblemCodeUnsupportedMediaType: "Unsupported media type",
api.ProblemCodeIdempotencyKeyReused: "Run ID reused with a different payload",
api.ProblemCodeInternal: "Internal server error",
api.ProblemCodeRunnerBusy: "Runner busy",
}
const invalidFieldMessage = "The value does not match the contract."
func newProblem(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) api.Problem {
problem := api.Problem{
Type: problemTypePrefix + string(code),
Title: problemTitles[code],
Status: int32(status), //nolint:gosec // HTTP status codes fit in int32.
Code: code,
Errors: fieldErrors,
}
if detail != "" {
problem.Detail = api.NewOptString(detail)
}
return problem
}
func problemError(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) *api.ProblemStatusCode {
return &api.ProblemStatusCode{StatusCode: status, Response: newProblem(status, code, detail, fieldErrors...)}
}
func invalidField(in api.ProblemFieldLocation, pointer string) api.ProblemFieldError {
return api.ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: invalidFieldMessage}
}
// writeProblem writes a problem outside the generated handlers.
func writeProblem(w http.ResponseWriter, problem api.Problem) {
encoder := jx.GetEncoder()
defer jx.PutEncoder(encoder)
problem.Encode(encoder)
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(int(problem.Status))
_, _ = w.Write(encoder.Bytes()) // The client may have gone away.
}
// errorHandler answers request decoding errors of the generated server.
func errorHandler(logger *slog.Logger) ogenerrors.ErrorHandler {
return func(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) {
writeProblem(w, decodeProblem(ctx, logger, err))
}
}
func decodeProblem(ctx context.Context, logger *slog.Logger, err error) api.Problem {
var tooLarge *http.MaxBytesError
var contentType *validate.InvalidContentTypeError
var paramsErr *ogenerrors.DecodeParamsError
var requestErr *ogenerrors.DecodeRequestError
switch {
case errors.As(err, &tooLarge):
return newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.")
case errors.As(err, &contentType):
return newProblem(http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, "Send the body as application/json.")
case errors.As(err, &paramsErr):
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
invalidField(api.ProblemFieldLocationPath, "/run_id"))
case errors.As(err, &requestErr):
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
invalidField(api.ProblemFieldLocationBody, ""))
default:
// The error text may describe internals; only its type is logged.
logger.ErrorContext(ctx, "request handling failed", slog.String("error_type", fmt.Sprintf("%T", err)))
return newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
}
}
+108
View File
@@ -0,0 +1,108 @@
package server
import (
"context"
"crypto/sha256"
"crypto/subtle"
"errors"
"fmt"
"log/slog"
"net/http"
"time"
"lincodex/runner/internal/api"
)
var errInvalidToken = errors.New("invalid bearer token")
// tokenAuth checks the shared service token. Comparing SHA-256 digests in
// constant time hides both the content and the length of the token.
type tokenAuth struct {
digest [sha256.Size]byte
}
func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) {
digest := sha256.Sum256([]byte(token.Token))
if subtle.ConstantTimeCompare(digest[:], a.digest[:]) != 1 {
return ctx, errInvalidToken
}
return ctx, nil
}
// New returns the HTTP handler of the runner API.
func New(handler *Handler, token string, maxRequestBytes int64, logger *slog.Logger) (http.Handler, error) {
if token == "" {
return nil, errors.New("server.New - empty service token")
}
generated, err := api.NewServer(handler, tokenAuth{digest: sha256.Sum256([]byte(token))},
api.WithErrorHandler(errorHandler(logger)),
api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) {
writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist."))
}),
api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) {
w.Header().Set("Allow", allowed)
writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method."))
}),
)
if err != nil {
return nil, fmt.Errorf("server.New - generated server: %w", err)
}
return accessLog(generated, logger, recoverPanics(logger, limitBody(maxRequestBytes, generated))), nil
}
// limitBody refuses bodies above the limit before they are read.
func limitBody(limit int64, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > limit {
writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit."))
return
}
r.Body = http.MaxBytesReader(w, r.Body, limit)
next.ServeHTTP(w, r)
})
}
func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
defer func() {
if recovered := recover(); recovered != nil {
// The panic value may hold request data; only its type is logged.
logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered)))
writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request."))
}
}()
next.ServeHTTP(w, r)
})
}
// accessLog writes one line per request with the operation, status, and
// duration. Bodies, headers, and query strings are never logged.
func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(recorder, r)
operation := "unknown"
if route, ok := router.FindPath(r.Method, r.URL); ok {
operation = route.OperationID()
}
logger.InfoContext(r.Context(), "request",
slog.String("method", r.Method),
slog.String("operation", operation),
slog.Int("status", recorder.status),
slog.Int64("duration_ms", time.Since(started).Milliseconds()),
)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
+278
View File
@@ -0,0 +1,278 @@
package server
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/runner/internal/jobs"
"lincodex/runner/internal/judge"
)
const (
testToken = "test-token-0123456789abcdefghijklmnop"
// Markers that must never reach a log line.
secretSource = "print('source-marker-7f3a')"
secretInput = "input-marker-91c2"
maxBody = 64 << 10
)
// blockingRunner holds runs until release is closed.
type blockingRunner struct {
release chan struct{}
}
func (r blockingRunner) Run(ctx context.Context, _ judge.Request) judge.Result {
select {
case <-r.release:
case <-ctx.Done():
}
exit := 0
return judge.Result{
Outcome: judge.Accepted,
Groups: []judge.GroupResult{{
ID: "public", Visibility: judge.Public, Outcome: judge.Accepted, Passed: 1, Total: 1,
MaxCPUTime: 25 * time.Millisecond, MaxMemoryKB: 9000,
Tests: []judge.TestResult{{ID: "t1", Outcome: judge.Accepted, CPUTime: 25 * time.Millisecond, WallTime: 40 * time.Millisecond, MemoryKB: 9000, ExitCode: &exit}},
}},
Duration: 50 * time.Millisecond,
}
}
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
type testServer struct {
url string
logs *syncBuffer
// release lets every held run finish; it may be called more than once.
release func()
}
func startServer(t *testing.T) *testServer {
t.Helper()
logs := &syncBuffer{}
logger := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
release := make(chan struct{})
manager, err := jobs.NewManager(jobs.Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}, blockingRunner{release: release}, logger)
if err != nil {
t.Fatalf("NewManager: %v", err)
}
supports := func(language string) bool { return language == "python3" }
handler := NewHandler(manager, supports, func() bool { return !manager.Draining() }, 3*time.Second, logger)
httpHandler, err := New(handler, testToken, maxBody, logger)
if err != nil {
t.Fatalf("New: %v", err)
}
server := httptest.NewServer(httpHandler)
var releaseOnce sync.Once
releaseRuns := func() { releaseOnce.Do(func() { close(release) }) }
t.Cleanup(func() {
releaseRuns()
server.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = manager.Close(ctx)
})
return &testServer{url: server.URL, logs: logs, release: releaseRuns}
}
func runBody(source string) map[string]any {
return map[string]any{
"language": "python3",
"source": source,
"limits": map[string]any{"time_limit_ms": 1000, "memory_limit_mb": 64, "output_limit_kb": 64},
"groups": []any{map[string]any{
"id": "public", "visibility": "public", "checker": map[string]any{"kind": "exact"},
"tests": []any{map[string]any{"id": "t1", "input": secretInput, "expected_output": "3\n"}},
}},
}
}
// reply is a response with its decoded JSON body; the body is already closed.
type reply struct {
StatusCode int
Header http.Header
}
func (s *testServer) do(t *testing.T, method, path, token string, body any) (reply, map[string]any) {
t.Helper()
var reader io.Reader = http.NoBody
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("encode body: %v", err)
}
reader = bytes.NewReader(encoded)
}
request, err := http.NewRequestWithContext(t.Context(), method, s.url+path, reader)
if err != nil {
t.Fatalf("new request: %v", err)
}
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("do request: %v", err)
}
defer response.Body.Close()
var decoded map[string]any
raw, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("decode %s: %v", raw, err)
}
}
return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded
}
func runPath(id uuid.UUID) string {
return "/v1/runs/" + id.String()
}
func TestRunOperationsRequireTheBearerToken(t *testing.T) {
t.Parallel()
server := startServer(t)
id := uuid.New()
for _, token := range []string{"", "wrong-token-0123456789abcdefghijklmnop", testToken + "x"} {
response, body := server.do(t, http.MethodPut, runPath(id), token, runBody(secretSource))
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
t.Fatalf("PUT with token %q = %d %v, want 401 unauthenticated", token, response.StatusCode, body)
}
response, _ = server.do(t, http.MethodGet, runPath(id), token, nil)
if response.StatusCode != http.StatusUnauthorized {
t.Fatalf("GET with token %q = %d, want 401", token, response.StatusCode)
}
}
response, body := server.do(t, http.MethodGet, "/healthz", "", nil)
if response.StatusCode != http.StatusOK || body["status"] != "ok" {
t.Fatalf("healthz = %d %v", response.StatusCode, body)
}
response, body = server.do(t, http.MethodGet, "/readyz", "", nil)
if response.StatusCode != http.StatusOK || body["status"] != "ready" {
t.Fatalf("readyz = %d %v", response.StatusCode, body)
}
}
func TestSubmitRunIsIdempotentAndAnswersBusy(t *testing.T) {
t.Parallel()
server := startServer(t)
id := uuid.New()
response, body := server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource))
if response.StatusCode != http.StatusAccepted || body["state"] != "running" || body["run_id"] != id.String() {
t.Fatalf("first PUT = %d %v, want 202 running", response.StatusCode, body)
}
response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource))
if response.StatusCode != http.StatusOK || body["state"] != "running" {
t.Fatalf("repeated PUT = %d %v, want 200 running", response.StatusCode, body)
}
response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody("print(2)"))
if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" {
t.Fatalf("PUT with another payload = %d %v, want 422", response.StatusCode, body)
}
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, runBody(secretSource))
if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "runner_busy" || response.Header.Get("Retry-After") != "3" {
t.Fatalf("PUT while busy = %d %v %q, want 503 runner_busy with Retry-After 3", response.StatusCode, body, response.Header.Get("Retry-After"))
}
server.release()
deadline := time.Now().Add(5 * time.Second)
for {
response, body = server.do(t, http.MethodGet, runPath(id), testToken, nil)
if body["state"] == "finished" || time.Now().After(deadline) {
break
}
time.Sleep(5 * time.Millisecond)
}
result, ok := body["result"].(map[string]any)
if response.StatusCode != http.StatusOK || !ok || result["outcome"] != "accepted" {
t.Fatalf("GET finished run = %d %v", response.StatusCode, body)
}
group := result["groups"].([]any)[0].(map[string]any)
test := group["tests"].([]any)[0].(map[string]any)
if group["passed_tests"] != float64(1) || test["time_ms"] != float64(25) || test["memory_kb"] != float64(9000) {
t.Fatalf("group result = %v, want the recorded time and memory", group)
}
logs := server.logs.String()
if strings.Contains(logs, "source-marker") || strings.Contains(logs, secretInput) || strings.Contains(logs, testToken) {
t.Fatalf("logs contain request data: %s", logs)
}
}
func TestSubmitRunValidatesTheRequest(t *testing.T) {
t.Parallel()
server := startServer(t)
duplicate := runBody(secretSource)
group := duplicate["groups"].([]any)[0]
duplicate["groups"] = []any{group, group}
response, body := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, duplicate)
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
t.Fatalf("duplicate group IDs = %d %v, want 400", response.StatusCode, body)
}
pointer := body["errors"].([]any)[0].(map[string]any)["pointer"]
if pointer != "/groups/1/id" {
t.Fatalf("pointer = %v, want /groups/1/id", pointer)
}
unknown := runBody(secretSource)
unknown["candidate_id"] = "c-1"
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, unknown)
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
t.Fatalf("unknown field = %d %v, want 400", response.StatusCode, body)
}
tooLarge := runBody(strings.Repeat("x", maxBody))
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, tooLarge)
if response.StatusCode != http.StatusRequestEntityTooLarge || body["code"] != "payload_too_large" {
t.Fatalf("large body = %d %v, want 413", response.StatusCode, body)
}
response, body = server.do(t, http.MethodPut, "/v1/runs/not-a-uuid", testToken, runBody(secretSource))
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
t.Fatalf("invalid run ID = %d %v, want 400", response.StatusCode, body)
}
response, body = server.do(t, http.MethodGet, runPath(uuid.New()), testToken, nil)
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
t.Fatalf("unknown run = %d %v, want 404", response.StatusCode, body)
}
response, body = server.do(t, http.MethodGet, "/v1/unknown", testToken, nil)
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
t.Fatalf("unknown route = %d %v, want 404", response.StatusCode, body)
}
}
+91
View File
@@ -0,0 +1,91 @@
{
"schema": "lincodex.runner-hostile-fixtures/v1",
"description": "Programs that a sandbox run must stop or contain. Each case runs as one public group with one test; expect.limit is the termination limit, or empty when the program ends by itself.",
"default_limits": {
"time_limit_ms": 1000,
"memory_limit_mb": 64,
"output_limit_kb": 64
},
"cases": [
{
"name": "correct_sum",
"language": "python3",
"source": "python/sum_correct.py",
"input": "1 2 3\n",
"expected_output": "6\n",
"expect": {"outcome": "accepted", "limit": ""}
},
{
"name": "syntax_error",
"language": "python3",
"source": "python/syntax_error.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "compile_error", "limit": ""}
},
{
"name": "infinite_loop",
"language": "python3",
"source": "python/infinite_loop.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "time_limit_exceeded", "limit": "cpu_time"}
},
{
"name": "sleep_forever",
"language": "python3",
"source": "python/sleep_forever.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "time_limit_exceeded", "limit": "wall_time"}
},
{
"name": "memory_leak",
"language": "python3",
"source": "python/memory_leak.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "memory_limit_exceeded", "limit": "memory"}
},
{
"name": "huge_output",
"language": "python3",
"source": "python/huge_output.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "output_limit_exceeded", "limit": "output"}
},
{
"name": "fork_bomb",
"language": "python3",
"source": "python/fork_bomb.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "runtime_error", "limit": "processes"}
},
{
"name": "network_probe",
"language": "python3",
"source": "python/network_probe.py",
"input": "",
"expected_output": "blocked\n",
"expect": {"outcome": "accepted", "limit": ""}
},
{
"name": "filesystem_probe",
"language": "python3",
"source": "python/filesystem_probe.py",
"input": "",
"expected_output": "isolated\n",
"expect": {"outcome": "accepted", "limit": ""}
},
{
"name": "privilege_probe",
"language": "python3",
"source": "python/privilege_probe.py",
"input": "",
"expected_output": "unprivileged\n",
"expect": {"outcome": "accepted", "limit": ""}
}
]
}
+16
View File
@@ -0,0 +1,16 @@
# Isolation probe: the root file system and the source are read-only, the
# scratch directory is writable, and runner files are not visible.
import os
writable = []
for path in ("/box/injected", "/usr/injected", "/injected", "/lib/injected"):
try:
with open(path, "w") as stream:
stream.write("x")
writable.append(path)
except OSError:
pass
with open("/tmp/scratch", "w") as stream:
stream.write("ok")
visible = [path for path in ("/etc/passwd", "/run/secrets", "/opt/lincodex-runner", "/proc/1") if os.path.exists(path)]
print("isolated" if not writable and not visible else "writable=" + ",".join(writable) + " visible=" + ",".join(visible))
+8
View File
@@ -0,0 +1,8 @@
# Fork bomb that ignores refused forks: the cgroup process limit must stop it.
import os
while True:
try:
os.fork()
except OSError:
pass
+6
View File
@@ -0,0 +1,6 @@
# Endless standard output: the output limit must stop it.
import sys
block = "x" * 65536
while True:
sys.stdout.write(block)
+3
View File
@@ -0,0 +1,3 @@
# Busy loop: the CPU time limit must stop it.
while True:
pass
+4
View File
@@ -0,0 +1,4 @@
# Unbounded allocation of touched memory: the cgroup memory limit must stop it.
chunks = []
while True:
chunks.append(b"x" * (1 << 20))
+18
View File
@@ -0,0 +1,18 @@
# Isolation probe: every attempt to reach a network must fail.
import socket
attempts = [
(socket.AF_INET, ("1.1.1.1", 53)),
(socket.AF_INET, ("127.0.0.1", 8080)),
(socket.AF_INET6, ("::1", 8080)),
]
reached = []
for family, address in attempts:
try:
with socket.socket(family, socket.SOCK_STREAM) as connection:
connection.settimeout(1)
connection.connect(address)
reached.append(address[0])
except OSError:
pass
print("blocked" if not reached else "reached " + " ".join(reached))
+19
View File
@@ -0,0 +1,19 @@
# Isolation probe: the program is an unprivileged user that cannot become
# root or take ownership for root.
import os
checks = [os.getuid() != 0, os.geteuid() != 0, os.getgid() != 0, os.getegid() != 0]
for attempt in (lambda: os.setuid(0), lambda: os.setgid(0)):
try:
attempt()
checks.append(False)
except OSError:
checks.append(True)
with open("/tmp/owned", "w"):
pass
try:
os.chown("/tmp/owned", 0, 0)
checks.append(False)
except OSError:
checks.append(True)
print("unprivileged" if all(checks) else "privileged")
+4
View File
@@ -0,0 +1,4 @@
# Idle wait: it uses no CPU, so only the wall-clock limit can stop it.
import time
time.sleep(3600)
+4
View File
@@ -0,0 +1,4 @@
# Correct solution: prints the sum of the integers on standard input.
import sys
print(sum(int(token) for token in sys.stdin.read().split()))
+3
View File
@@ -0,0 +1,3 @@
# Syntax error: the syntax check must reject it before any test runs.
def broken(:
return 1