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

+1 -1
View File
@@ -4,7 +4,7 @@ Use the source that owns the fact being discussed. Read the relevant source befo
- The user's request sets the authorized task scope and product choices for that task.
- Source code shows behavior that exists in this checkout. A passing test gives evidence only for the behavior it exercises.
- api/core/openapi.yml and api/ml/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output.
- api/core/openapi.yml, api/ml/openapi.yml, and api/runner/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output.
- Backend migrations define the database schema. sqlc query files define queries that sqlc generates.
- Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.9. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags.
- Compose, Nginx, and observability configuration define the local deployment scaffold. They do not prove that a remote deployment or production security review occurred.
+3 -2
View File
@@ -4,10 +4,11 @@ The repository has separate public and internal OpenAPI contracts:
- api/core/openapi.yml describes browser-to-Go operations.
- api/ml/openapi.yml describes internal Go-to-ML operations.
- api/runner/openapi.yml describes internal operations between Go and the code runner.
Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint both specifications. Do not hand-edit bundled files.
Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint every specification. Do not hand-edit bundled files.
The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/.
The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. The Go code runner client is configured in backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/.
OpenAPI 3.2.0 is the target contract version. Verify only the feature subset used by this repository through the pinned bundler, linter, ogen, Go runtime path, Orval, Python Pydantic models, and documentation pipeline. A passing fixture does not establish full support for every OpenAPI 3.2 feature. Record the exact checks run.
+10 -7
View File
@@ -13,44 +13,47 @@ install: ## Install project dependencies
printf '\n==> %s install\n' "$$part"; \
$(MAKE) -C "$$part" install || status=1; \
done; \
printf '\n==> backend deps\n'; \
$(MAKE) -C backend deps || status=1; \
for part in backend runner; do \
printf '\n==> %s deps\n' "$$part"; \
$(MAKE) -C "$$part" deps || status=1; \
done; \
exit "$$status"
generate: ## Generate shared contracts, Go and TypeScript code, and Python models
$(MAKE) -C api bundle
API_PREPARED=1 $(MAKE) -C backend generate
API_PREPARED=1 $(MAKE) -C runner generate
API_PREPARED=1 $(MAKE) -C frontend generate
API_PREPARED=1 $(MAKE) -C ml generate
gen: generate ## Alias for generate
fmt: ## Format all project parts
@status=0; for part in api backend frontend ml; do \
@status=0; for part in api backend runner frontend ml; do \
printf '\n==> %s fmt\n' "$$part"; \
$(MAKE) -C "$$part" fmt || status=1; \
done; exit "$$status"
fmt-check: ## Check formatting without changing files
@status=0; for part in api backend frontend ml; do \
@status=0; for part in api backend runner frontend ml; do \
printf '\n==> %s fmt-check\n' "$$part"; \
$(MAKE) -C "$$part" fmt-check || status=1; \
done; exit "$$status"
lint: ## Run configured linters
@status=0; for part in api backend frontend ml; do \
@status=0; for part in api backend runner frontend ml; do \
printf '\n==> %s lint\n' "$$part"; \
$(MAKE) -C "$$part" lint || status=1; \
done; exit "$$status"
test: ## Run unit and component tests
@status=0; for part in backend frontend ml; do \
@status=0; for part in backend runner frontend ml; do \
printf '\n==> %s test\n' "$$part"; \
$(MAKE) -C "$$part" test || status=1; \
done; exit "$$status"
check: ## Run local checks for code, docs, deployment, and observability
@status=0; for part in api backend frontend ml deploy observability; do \
@status=0; for part in api backend runner frontend ml deploy observability; do \
printf '\n==> %s check\n' "$$part"; \
$(MAKE) -C "$$part" check || status=1; \
done; \
+1
View File
@@ -43,6 +43,7 @@ Short directory guides:
| [backend/](backend/README.en.md) | Main Go service |
| [frontend/](frontend/README.en.md) | React and TypeScript interface |
| [ml/](ml/README.en.md) | Separate Python service for ML |
| [runner/](runner/README.en.md) | Go code runner with nsjail |
| [deploy/](deploy/README.en.md) | Docker Compose, Nginx, and service startup |
| [observability/](observability/README.en.md) | Metrics, logs, and dashboards |
| [security/](security/README.en.md) | Security scanners and rules |
+1
View File
@@ -49,6 +49,7 @@ make -C deploy demo-seed DEMO_MODE=isolated
| [backend/](backend/README.md) | Основной сервис на Go |
| [frontend/](frontend/README.md) | Интерфейс на React и TypeScript |
| [ml/](ml/README.md) | Отдельный Python-сервис для ML |
| [runner/](runner/README.md) | Исполнитель кода на Go с nsjail |
| [deploy/](deploy/README.md) | Docker Compose, Nginx и запуск сервисов |
| [observability/](observability/README.md) | Метрики, логи и дашборды |
| [security/](security/README.md) | Сканеры и правила безопасности |
+7 -3
View File
@@ -16,23 +16,27 @@ install: ## Install pinned OpenAPI tooling
npm ci --prefix "$(API_DIR)" --ignore-scripts --no-audit --no-fund
.PHONY: bundle
bundle: ## Merge split schemas and create public and ML bundles
bundle: ## Merge split schemas and create public, ML, and code runner bundles
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/core"
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/ml"
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/runner"
"$(REDOCLY)" bundle "$(API_DIR)/core/openapi.yml" --output "$(API_DIR)/core/openapi.bundle.yml"
"$(REDOCLY)" bundle "$(API_DIR)/ml/openapi.yml" --output "$(API_DIR)/ml/openapi.bundle.yml"
"$(REDOCLY)" bundle "$(API_DIR)/runner/openapi.yml" --output "$(API_DIR)/runner/openapi.bundle.yml"
.PHONY: lint
lint: bundle ## Lint both bundled contracts
lint: bundle ## Lint every bundled contract
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/core/openapi.bundle.yml"
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/ml/openapi.bundle.yml"
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/runner/openapi.bundle.yml"
.PHONY: check
check: lint ## Build and lint both contract bundles
check: lint ## Build and lint every contract bundle and run the contract tests
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_merge_schemas.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_assessment_contract.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_match_contract.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_runner_contract.py'
.PHONY: check-compat
check-compat: bundle ## Compare the public contract with API_BASE_REF
+13 -1
View File
@@ -6,9 +6,10 @@ Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come fir
- `core/` defines the main backend's public API.
- `ml/` defines the ML service's internal HTTP API.
- `runner/` defines the internal HTTP API of the own code runner.
- `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0.
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`.
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`; the code runner server code is generated from `runner/codegen/`.
From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code.
@@ -100,6 +101,17 @@ Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with t
The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
### Code runner contract
`runner/openapi.yml` describes the internal API of the code runner, which only the Go backend calls. ogen generates the Go client from `backend/codegen/ogen-code-runner.yml` into `backend/internal/adapter/secondary/code_runner/api/`; no use case calls it yet.
- Transport and sign-in. The runner listens on a private interface of its host over HTTPS (TLS 1.3). Every operation except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`; the token is a shared random secret of at least 32 characters from the deployment secret store. A wrong or missing token answers 401 `unauthenticated`. Plain HTTP is allowed only by an explicit switch of the local dev Compose file.
- Data. `RunRequest` carries only the language, the source code, the limits, and the test groups; each group has a label, a visibility (`public` or `hidden`), a checker kind, and tests with an input and an expected output. It has no candidate, account, attempt, task, or company field; `scripts/test_runner_contract.py` checks this for every request schema, together with `additionalProperties: false` on every request object.
- Idempotency. `PUT /v1/runs/{run_id}` (`SubmitRun`) takes a random UUID from the backend. A new ID with a free slot starts the run and answers 202, the same ID with the same body returns the current state with 200 without running again, and the same ID with a different body answers 422 `idempotency_key_reused`. Bodies are compared by a SHA-256 fingerprint of the decoded request. When every slot is busy or the process is stopping, the answer is 503 `runner_busy` with `Retry-After`; nothing is stored, and the backend keeps the queue.
- Result. `GetRun` returns `state` (`running` or `finished`) and, per group, the outcome `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error`, or `infrastructure_failure`, the number of passed tests, the CPU time, and the peak memory. `limit` names the limit that stopped a test (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Only public tests carry a stderr diagnostic; hidden tests never carry program output.
- Checker. The current kinds are `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines) and `tokens` (token sequences split on ASCII whitespace). The `Checker` object grows with new `kind` values and optional parameters, such as a float tolerance.
- Errors use the api/core `Problem` shape with a runner-specific `ProblemCode` enum: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal`, and `runner_busy`. `scripts/test_runner_contract.py` checks that the shape matches api/core.
### Identity: sessions, cookie, and CSRF
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders.
+13 -1
View File
@@ -6,9 +6,10 @@
- `core/` - публичный API основного backend.
- `ml/` - внутренний HTTP API ML-сервиса.
- `runner/` - внутренний HTTP API собственного исполнителя кода.
- `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0.
Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`.
Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`; серверный код исполнителя генерируется по `runner/codegen/`.
Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код.
@@ -100,6 +101,17 @@
ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback.
### Контракт исполнителя кода
`runner/openapi.yml` описывает внутренний API исполнителя кода, который вызывает только Go backend. Go-клиент генерируется ogen по `backend/codegen/ogen-code-runner.yml` в `backend/internal/adapter/secondary/code_runner/api/`; его пока не вызывает ни один usecase.
- Транспорт и вход. Исполнитель слушает частный интерфейс своего хоста по HTTPS (TLS 1.3). Все операции, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`; токен - общий случайный секрет не короче 32 символов из хранилища секретов развертывания. Неверный или отсутствующий токен дает 401 `unauthenticated`. Простой HTTP разрешен только явным переключателем локального dev Compose.
- Данные. `RunRequest` содержит только язык, исходный код, лимиты и группы тестов; у каждой группы есть метка, видимость (`public` или `hidden`), вид checker и тесты с входом и ожидаемым выводом. Полей кандидата, аккаунта, попытки, задания или компании нет; `scripts/test_runner_contract.py` проверяет это для всех схем запросов, а также `additionalProperties: false` у каждого объекта запроса.
- Идемпотентность. `PUT /v1/runs/{run_id}` (`SubmitRun`) принимает случайный UUID от backend. Новый ID при свободном слоте запускает прогон и отвечает 202, тот же ID с тем же телом возвращает текущее состояние с 200 без повторного запуска, тот же ID с другим телом дает 422 `idempotency_key_reused`. Тела сравниваются по SHA-256 отпечатку разобранного запроса. Когда все слоты заняты или процесс останавливается, ответ - 503 `runner_busy` с `Retry-After`; ничего не сохраняется, очередь держит backend.
- Результат. `GetRun` возвращает `state` (`running` или `finished`) и итог по каждой группе: `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` или `infrastructure_failure`, число пройденных тестов, время CPU и пиковую память. `limit` называет сработавший лимит (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Диагностика stderr есть только у публичных тестов; у скрытых тестов нет вывода программы.
- Checker. Сейчас есть `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце) и `tokens` (последовательности токенов по ASCII-пробелам). Объект `Checker` расширяется новыми `kind` и необязательными параметрами, например допуском для чисел.
- Ошибки используют форму `Problem` из api/core; перечисление `ProblemCode` свое: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal` и `runner_busy`. Совпадение формы с api/core проверяет `scripts/test_runner_contract.py`.
### Identity: сессии, cookie и CSRF
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками.
+57
View File
@@ -0,0 +1,57 @@
Problem:
description: >-
Any error response. The body is a Problem whose `status` equals the HTTP
status and whose `code` is one of ProblemCode.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
validation_failed:
summary: Request fields do not match the contract
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
errors:
- in: body
pointer: /groups/1/id
code: invalid
message: The value does not match the contract.
idempotency_key_reused:
summary: The run ID was used with a different payload
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Run ID reused with a different payload
status: 422
code: idempotency_key_reused
detail: A run with this ID exists with a different payload.
RunnerBusy:
description: >-
Every sandbox slot is busy or the runner is draining; code runner_busy.
Nothing was stored. Retry with the same run ID after Retry-After.
headers:
Retry-After:
description: Number of seconds to wait before retrying the request.
required: true
schema:
type: integer
format: int32
minimum: 0
maximum: 3600
example: 2
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
runner_busy:
summary: No free sandbox slot
value:
type: urn:lincodex:problem:runner_busy
title: Runner busy
status: 503
code: runner_busy
detail: Every sandbox slot is busy. Retry later with the same run ID.
+452
View File
@@ -0,0 +1,452 @@
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/ProblemFieldError'
ProblemCode:
type: string
description: 'Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.'
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: '#/ProblemFieldLocation'
pointer:
type: string
maxLength: 1024
pattern: ^(/([^~/]|~[01])*)*$
description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
RunRequest:
type: object
description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: '#/RunLanguage'
source:
type: string
minLength: 1
maxLength: 65536
description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it.
limits:
$ref: '#/RunLimits'
groups:
type: array
minItems: 1
maxItems: 4
description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run.
items:
$ref: '#/TestGroup'
RunLanguage:
type: string
description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: Standard output per test in KiB. The test is stopped as soon as it writes more.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: '#/TestKey'
visibility:
$ref: '#/TestVisibility'
checker:
$ref: '#/Checker'
tests:
type: array
minItems: 1
maxItems: 50
description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test.
items:
$ref: '#/TestCase'
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: ^[a-z0-9][a-z0-9_-]{0,31}$
description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier.
TestVisibility:
type: string
description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.'
enum:
- public
- hidden
Checker:
type: object
description: How the standard output of a test is compared with `expected_output`. Future kinds, such as a float tolerance or a custom checker, add a `kind` value and their own optional parameters to this object.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: '#/CheckerKind'
CheckerKind:
type: string
description: '- exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines.
- tokens: both texts split on ASCII whitespace give the same sequence of tokens.'
enum:
- exact
- tokens
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: '#/TestKey'
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
RunState:
type: string
description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.'
enum:
- running
- finished
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: '#/RunState'
result:
$ref: '#/RunResult'
RunOutcome:
type: string
description: 'Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run''s outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group''s outcome is the outcome of its first failed test, otherwise accepted.'
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
TerminationLimit:
type: string
description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.'
enum:
- cpu_time
- wall_time
- memory
- output
- processes
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: '#/RunOutcome'
compile:
$ref: '#/CompileResult'
groups:
type: array
maxItems: 4
description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests.
items:
$ref: '#/GroupResult'
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: '#/RunOutcome'
diagnostic:
type: string
maxLength: 4096
description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: '#/TestKey'
visibility:
$ref: '#/TestVisibility'
outcome:
$ref: '#/RunOutcome'
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed.
items:
$ref: '#/TestResult'
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: '#/TestKey'
outcome:
$ref: '#/RunOutcome'
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.'
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: '#/TerminationLimit'
diagnostic:
type: string
maxLength: 2048
description: Truncated standard error of a failed public test. Hidden tests never carry it.
@@ -0,0 +1,22 @@
schemas:
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
@@ -0,0 +1,138 @@
schemas:
Problem:
type: object
description: >-
Problem details (RFC 9457) returned with the application/problem+json
media type for every error response. This is the runner copy of the
public api/core Problem schema; keep both copies identical except for
descriptions and the ProblemCode enum. `code` is the stable,
machine-readable reason; clients branch on it rather than on `title`,
`detail`, or the HTTP status alone. The body never contains internal
error text, stack traces, SQL, file paths, credentials, contact data, or
echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: >-
URI that identifies the problem type. It has the form
`urn:lincodex:problem:<code>` and is an identifier, not a link to
dereference.
title:
type: string
minLength: 1
maxLength: 200
description: >-
Short, fixed English summary of the problem type. It does not change
between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: "#/schemas/ProblemCode"
detail:
type: string
maxLength: 1000
description: >-
Safe English explanation of this occurrence. It never contains
internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: "^[A-Za-z0-9._-]+$"
description: >-
Request identifier of the call when the caller propagated one; it is
not a secret.
errors:
type: array
maxItems: 100
description: >-
Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: "#/schemas/ProblemFieldError"
ProblemCode:
type: string
description: |-
Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: "#/schemas/ProblemFieldLocation"
pointer:
type: string
maxLength: 1024
pattern: "^(/([^~/]|~[01])*)*$"
description: >-
JSON Pointer (RFC 6901). For `body` it points into the request body
document, for example `/limits/time_limit_ms`; an empty string means the whole
body. For a parameter it is `/` followed by the parameter name, for
example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: "^[a-z][a-z0-9_]*$"
description: >-
Stable field reason. Current values are `required` (missing value)
and `invalid` (malformed value or a value outside the schema).
Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
@@ -0,0 +1,347 @@
schemas:
RunRequest:
type: object
description: >-
One source and its test groups. The request has no field for a
candidate, account, attempt, task, or company; the backend maps a run ID
to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: "#/schemas/RunLanguage"
source:
type: string
minLength: 1
maxLength: 65536
description: >-
Complete program text in UTF-8. The runner writes it to a read-only
file inside the sandbox and never logs it.
limits:
$ref: "#/schemas/RunLimits"
groups:
type: array
minItems: 1
maxItems: 4
description: >-
Test groups in evaluation order, for example one public group and
three hidden groups. Group IDs are unique in a run.
items:
$ref: "#/schemas/TestGroup"
RunLanguage:
type: string
description: >-
Language and runtime of the source. `python3` runs the Python 3
interpreter of the runner image with isolated mode and no bytecode
writes; a syntax check runs first and fails with compile_error.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: >-
CPU time per test, including interpreter startup, summed over every
process of the test. The wall-clock limit is twice this value plus
a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: >-
Memory of the test's processes in MiB, enforced by a cgroup v2
memory limit without swap. The limit also leaves a small fixed
allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: >-
Standard output per test in KiB. The test is stopped as soon as it
writes more.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: "#/schemas/TestKey"
visibility:
$ref: "#/schemas/TestVisibility"
checker:
$ref: "#/schemas/Checker"
tests:
type: array
minItems: 1
maxItems: 50
description: >-
Tests in evaluation order. Test IDs are unique in a group. A group
stops at its first failed test.
items:
$ref: "#/schemas/TestCase"
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: "^[a-z0-9][a-z0-9_-]{0,31}$"
description: >-
Opaque label chosen by the backend, for example `public` or `hidden-1`.
It is not a database identifier.
TestVisibility:
type: string
description: >-
`public` tests may be shown to the person who wrote the source; their
results may carry a diagnostic excerpt. `hidden` results never carry
program output or diagnostics.
enum:
- public
- hidden
Checker:
type: object
description: >-
How the standard output of a test is compared with `expected_output`.
Future kinds, such as a float tolerance or a custom checker, add a
`kind` value and their own optional parameters to this object.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: "#/schemas/CheckerKind"
CheckerKind:
type: string
description: |-
- exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines.
- tokens: both texts split on ASCII whitespace give the same sequence of tokens.
enum:
- exact
- tokens
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: "#/schemas/TestKey"
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
RunState:
type: string
description: >-
`running` until every group was evaluated or the run failed;
`finished` when `result` is final.
enum:
- running
- finished
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: "#/schemas/RunState"
result:
$ref: "#/schemas/RunResult"
RunOutcome:
type: string
description: |-
Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted.
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
TerminationLimit:
type: string
description: >-
The limit that stopped a test: CPU time, wall-clock time, memory,
standard output, or the number of processes and threads.
enum:
- cpu_time
- wall_time
- memory
- output
- processes
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: "#/schemas/RunOutcome"
compile:
$ref: "#/schemas/CompileResult"
groups:
type: array
maxItems: 4
description: >-
One result per requested group in request order. After
compile_error or infrastructure_failure every group has that
outcome and no tests.
items:
$ref: "#/schemas/GroupResult"
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: "#/schemas/RunOutcome"
diagnostic:
type: string
maxLength: 4096
description: >-
Compiler or syntax checker message for compile_error, truncated to
the limit. It can quote the source, never test data.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: "#/schemas/TestKey"
visibility:
$ref: "#/schemas/TestVisibility"
outcome:
$ref: "#/schemas/RunOutcome"
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: >-
Results of the evaluated tests in order. Tests after the first
failed one are not run and not listed.
items:
$ref: "#/schemas/TestResult"
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: "#/schemas/TestKey"
outcome:
$ref: "#/schemas/RunOutcome"
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: >-
Peak memory of the test in KiB: the cgroup high-water mark of every
process of the test, including the sandbox supervisor process and
file cache charged to the test.
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: "#/schemas/TerminationLimit"
diagnostic:
type: string
maxLength: 2048
description: >-
Truncated standard error of a failed public test. Hidden tests
never carry it.
+633
View File
@@ -0,0 +1,633 @@
openapi: 3.2.0
info:
title: Lincodex Code Runner API
version: 0.1.0
description: |-
Internal API of the own code runner. Only the Go backend calls it; it is
never exposed to browsers or to the public network.
Transport and authentication: the runner listens on a private network
interface of its dedicated host and serves HTTPS (TLS 1.3). Every
operation except the health routes requires `Authorization: Bearer
<token>`; the token is a shared random secret of at least 32 characters
that comes from the deployment secret store, never from this repository.
A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists
only behind an explicit development switch of the local Compose file.
Data minimization: a run carries only the language, the source code, the
limits, and the test groups. It has no candidate, account, attempt, or
task identifiers, names, or contacts. The run ID is a random UUID chosen
by the backend for idempotency; the runner keeps it only in memory.
Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free
and answers immediately; the caller polls GetRun until `state` is
`finished`. The runner does not queue runs: when every slot is busy it
answers 503 `runner_busy`, and the backend keeps the queue.
servers:
- url: /
security:
- bearerAuth: []
paths:
/healthz:
get:
operationId: GetRunnerHealthz
summary: Check whether the runner process is responding.
security: []
tags:
- health
responses:
'200':
description: The runner process is responding.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerHealthResponse'
default:
$ref: '#/components/responses/Problem'
/readyz:
get:
operationId: GetRunnerReadyz
summary: Check whether the sandbox is prepared to accept runs.
description: 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.
security: []
tags:
- health
responses:
'200':
description: The sandbox is prepared.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerReadinessResponse'
'503':
description: The sandbox is not prepared or the process is draining.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerReadinessResponse'
default:
$ref: '#/components/responses/Problem'
/v1/runs/{run_id}:
parameters:
- name: run_id
in: path
required: true
description: 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.
schema:
type: string
format: uuid
put:
operationId: SubmitRun
summary: Start a sandboxed run of one source against its test groups.
description: |-
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.
tags:
- runs
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/RunRequest'
responses:
'200':
description: A run with this ID and the same payload already exists.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
'202':
description: The run was accepted and started.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
'503':
$ref: '#/components/responses/RunnerBusy'
default:
$ref: '#/components/responses/Problem'
get:
operationId: GetRun
summary: Read the state and, when finished, the per-group result of a run.
description: 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.
tags:
- runs
responses:
'200':
description: The current state of the run.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
default:
$ref: '#/components/responses/Problem'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: '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.'
responses:
Problem:
description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
validation_failed:
summary: Request fields do not match the contract
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
errors:
- in: body
pointer: /groups/1/id
code: invalid
message: The value does not match the contract.
idempotency_key_reused:
summary: The run ID was used with a different payload
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Run ID reused with a different payload
status: 422
code: idempotency_key_reused
detail: A run with this ID exists with a different payload.
RunnerBusy:
description: Every sandbox slot is busy or the runner is draining; code runner_busy. Nothing was stored. Retry with the same run ID after Retry-After.
headers:
Retry-After:
description: Number of seconds to wait before retrying the request.
required: true
schema:
type: integer
format: int32
minimum: 0
maximum: 3600
example: 2
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
runner_busy:
summary: No free sandbox slot
value:
type: urn:lincodex:problem:runner_busy
title: Runner busy
status: 503
code: runner_busy
detail: Every sandbox slot is busy. Retry later with the same run ID.
schemas:
ProblemCode:
type: string
description: |-
Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: '#/components/schemas/ProblemFieldLocation'
pointer:
type: string
maxLength: 1024
pattern: ^(/([^~/]|~[01])*)*$
description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/components/schemas/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/components/schemas/ProblemFieldError'
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
RunState:
type: string
description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.'
enum:
- running
- finished
RunOutcome:
type: string
description: |-
Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted.
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: '#/components/schemas/RunOutcome'
diagnostic:
type: string
maxLength: 4096
description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data.
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: ^[a-z0-9][a-z0-9_-]{0,31}$
description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier.
TestVisibility:
type: string
description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.'
enum:
- public
- hidden
TerminationLimit:
type: string
description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.'
enum:
- cpu_time
- wall_time
- memory
- output
- processes
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: '#/components/schemas/TestKey'
outcome:
$ref: '#/components/schemas/RunOutcome'
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.'
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: '#/components/schemas/TerminationLimit'
diagnostic:
type: string
maxLength: 2048
description: Truncated standard error of a failed public test. Hidden tests never carry it.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: '#/components/schemas/TestKey'
visibility:
$ref: '#/components/schemas/TestVisibility'
outcome:
$ref: '#/components/schemas/RunOutcome'
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed.
items:
$ref: '#/components/schemas/TestResult'
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: '#/components/schemas/RunOutcome'
compile:
$ref: '#/components/schemas/CompileResult'
groups:
type: array
maxItems: 4
description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests.
items:
$ref: '#/components/schemas/GroupResult'
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: '#/components/schemas/RunState'
result:
$ref: '#/components/schemas/RunResult'
RunLanguage:
type: string
description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: Standard output per test in KiB. The test is stopped as soon as it writes more.
CheckerKind:
type: string
description: |-
- exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines.
- tokens: both texts split on ASCII whitespace give the same sequence of tokens.
enum:
- exact
- tokens
Checker:
type: object
description: How the standard output of a test is compared with `expected_output`. Future kinds, such as a float tolerance or a custom checker, add a `kind` value and their own optional parameters to this object.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: '#/components/schemas/CheckerKind'
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: '#/components/schemas/TestKey'
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: '#/components/schemas/TestKey'
visibility:
$ref: '#/components/schemas/TestVisibility'
checker:
$ref: '#/components/schemas/Checker'
tests:
type: array
minItems: 1
maxItems: 50
description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test.
items:
$ref: '#/components/schemas/TestCase'
RunRequest:
type: object
description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: '#/components/schemas/RunLanguage'
source:
type: string
minLength: 1
maxLength: 65536
description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it.
limits:
$ref: '#/components/schemas/RunLimits'
groups:
type: array
minItems: 1
maxItems: 4
description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run.
items:
$ref: '#/components/schemas/TestGroup'
+49
View File
@@ -0,0 +1,49 @@
openapi: 3.2.0
info:
title: Lincodex Code Runner API
version: 0.1.0
description: |-
Internal API of the own code runner. Only the Go backend calls it; it is
never exposed to browsers or to the public network.
Transport and authentication: the runner listens on a private network
interface of its dedicated host and serves HTTPS (TLS 1.3). Every
operation except the health routes requires `Authorization: Bearer
<token>`; the token is a shared random secret of at least 32 characters
that comes from the deployment secret store, never from this repository.
A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists
only behind an explicit development switch of the local Compose file.
Data minimization: a run carries only the language, the source code, the
limits, and the test groups. It has no candidate, account, attempt, or
task identifiers, names, or contacts. The run ID is a random UUID chosen
by the backend for idempotency; the runner keeps it only in memory.
Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free
and answers immediately; the caller polls GetRun until `state` is
`finished`. The runner does not queue runs: when every slot is busy it
answers 503 `runner_busy`, and the backend keeps the queue.
servers:
- url: /
security:
- bearerAuth: []
paths:
/healthz:
$ref: ./routes/healthz.yml
/readyz:
$ref: ./routes/readyz.yml
/v1/runs/{run_id}:
$ref: ./routes/runs.yml
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: >-
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.
responses:
Problem:
$ref: ./components/responses.yml#/Problem
+15
View File
@@ -0,0 +1,15 @@
get:
operationId: GetRunnerHealthz
summary: Check whether the runner process is responding.
security: []
tags:
- health
responses:
"200":
description: The runner process is responding.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerHealthResponse
default:
$ref: ../components/responses.yml#/Problem
+25
View File
@@ -0,0 +1,25 @@
get:
operationId: GetRunnerReadyz
summary: Check whether the sandbox is prepared to accept runs.
description: >-
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.
security: []
tags:
- health
responses:
"200":
description: The sandbox is prepared.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerReadinessResponse
"503":
description: The sandbox is not prepared or the process is draining.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerReadinessResponse
default:
$ref: ../components/responses.yml#/Problem
+72
View File
@@ -0,0 +1,72 @@
parameters:
- name: run_id
in: path
required: true
description: >-
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.
schema:
type: string
format: uuid
put:
operationId: SubmitRun
summary: Start a sandboxed run of one source against its test groups.
description: |-
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.
tags:
- runs
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunRequest
responses:
"200":
description: A run with this ID and the same payload already exists.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
"202":
description: The run was accepted and started.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
"503":
$ref: ../components/responses.yml#/RunnerBusy
default:
$ref: ../components/responses.yml#/Problem
get:
operationId: GetRun
summary: Read the state and, when finished, the per-group result of a run.
description: >-
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.
tags:
- runs
responses:
"200":
description: The current state of the run.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
default:
$ref: ../components/responses.yml#/Problem
+2
View File
@@ -125,6 +125,7 @@ linters:
paths:
- internal/adapter/primary/http/api/
- internal/adapter/secondary/ml/api/
- internal/adapter/secondary/code_runner/api/
- internal/adapter/secondary/postgres/sqlc/
- internal/bootstrap/wire_gen\.go$
- (^|/)mocks/
@@ -160,6 +161,7 @@ formatters:
paths:
- internal/adapter/primary/http/api/
- internal/adapter/secondary/ml/api/
- internal/adapter/secondary/code_runner/api/
- internal/adapter/secondary/postgres/sqlc/
- internal/bootstrap/wire_gen\.go$
- (^|/)mocks/
+6
View File
@@ -98,6 +98,7 @@ generate gen: ## Regenerate API, SQL, and dependency-injection code in dependenc
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(MAKE) --no-print-directory gen-openapi API_PREPARED=1
$(MAKE) --no-print-directory gen-ml API_PREPARED=1
$(MAKE) --no-print-directory gen-code-runner API_PREPARED=1
$(MAKE) --no-print-directory gen-sqlc
$(MAKE) --no-print-directory gen-wire
$(MAKE) --no-print-directory mocks
@@ -112,6 +113,11 @@ gen-ml: ## Generate the internal ML service client
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml
.PHONY: gen-code-runner
gen-code-runner: ## Generate the internal code runner client
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(GO_TOOL) ogen -config codegen/ogen-code-runner.yml --target internal/adapter/secondary/code_runner/api --package api --clean ../api/runner/openapi.bundle.yml
.PHONY: gen-sqlc
gen-sqlc: ## Generate PostgreSQL query code from migrations and queries
$(GO_TOOL) sqlc generate -f codegen/sqlc.yml
+5
View File
@@ -0,0 +1,5 @@
generator:
features:
disable:
- paths/server
- webhooks/server
@@ -0,0 +1,151 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
ht "github.com/ogen-go/ogen/http"
"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.
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
)
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()),
)
}
type clientConfig struct {
otelConfig
Client ht.Client
}
// ClientOption is client config option.
type ClientOption interface {
applyClient(*clientConfig)
}
var _ ClientOption = (optionFunc[clientConfig])(nil)
func (o optionFunc[C]) applyClient(c *C) {
o(c)
}
var _ ClientOption = (otelOptionFunc)(nil)
func (o otelOptionFunc) applyClient(c *clientConfig) {
o(&c.otelConfig)
}
func newClientConfig(opts ...ClientOption) clientConfig {
cfg := clientConfig{
Client: http.DefaultClient,
}
for _, opt := range opts {
opt.applyClient(&cfg)
}
cfg.initOTEL()
return cfg
}
type baseClient struct {
cfg clientConfig
requests metric.Int64Counter
errors metric.Int64Counter
duration metric.Float64Histogram
}
func (cfg clientConfig) baseClient() (c baseClient, err error) {
c = baseClient{cfg: cfg}
if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil {
return c, err
}
if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil {
return c, err
}
if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil {
return c, err
}
return c, nil
}
// Option is config option.
type Option interface {
ClientOption
}
// 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
})
}
// WithClient specifies http client to use.
func WithClient(client ht.Client) ClientOption {
return optionFunc[clientConfig](func(cfg *clientConfig) {
if client != nil {
cfg.Client = client
}
})
}
@@ -0,0 +1,556 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"io"
"net/url"
"strings"
"time"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"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"
)
func trimTrailingSlashes(u *url.URL) {
u.Path = strings.TrimRight(u.Path, "/")
u.RawPath = strings.TrimRight(u.RawPath, "/")
}
// Invoker invokes operations described by OpenAPI v3 specification.
type Invoker interface {
// GetRun invokes 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 invokes GetRunnerHealthz operation.
//
// Check whether the runner process is responding.
//
// GET /healthz
GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error)
// GetRunnerReadyz invokes 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 invokes 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, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error)
}
// Client implements OAS client.
type Client struct {
serverURL *url.URL
sec SecuritySource
baseClient
}
// NewClient initializes new Client defined by OAS.
func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) {
u, err := url.Parse(serverURL)
if err != nil {
return nil, err
}
trimTrailingSlashes(u)
c, err := newClientConfig(opts...).baseClient()
if err != nil {
return nil, err
}
return &Client{
serverURL: u,
sec: sec,
baseClient: c,
}, nil
}
type serverURLKey struct{}
// WithServerURL sets context key to override server URL.
func WithServerURL(ctx context.Context, u *url.URL) context.Context {
return context.WithValue(ctx, serverURLKey{}, u)
}
func (c *Client) requestURL(ctx context.Context) *url.URL {
u, ok := ctx.Value(serverURLKey{}).(*url.URL)
if !ok {
return c.serverURL
}
return u
}
// GetRun invokes 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 (c *Client) GetRun(ctx context.Context, params GetRunParams) (*RunStatus, error) {
res, err := c.sendGetRun(ctx, params)
return res, err
}
func (c *Client) sendGetRun(ctx context.Context, params GetRunParams) (res *RunStatus, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRun"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.URLTemplateKey.String("/v1/runs/{run_id}"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, GetRunOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [2]string
pathParts[0] = "/v1/runs/"
{
// Encode "run_id" parameter.
e := uri.NewPathEncoder(uri.PathEncoderConfig{
Param: "run_id",
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
return e.EncodeValue(conv.UUIDToString(params.RunID))
}(); err != nil {
return res, errors.Wrap(err, "encode path")
}
encoded, err := e.Result()
if err != nil {
return res, errors.Wrap(err, "encode path")
}
pathParts[1] = encoded
}
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "GET", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
{
type bitset = [1]uint8
var satisfied bitset
{
stage = "Security:BearerAuth"
switch err := c.securityBearerAuth(ctx, GetRunOperation, r); {
case err == nil: // if NO error
satisfied[0] |= 1 << 0
case errors.Is(err, ogenerrors.ErrSkipClientSecurity):
// Skip this security.
default:
return res, errors.Wrap(err, "security \"BearerAuth\"")
}
}
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 {
return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied
}
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeGetRunResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
// GetRunnerHealthz invokes GetRunnerHealthz operation.
//
// Check whether the runner process is responding.
//
// GET /healthz
func (c *Client) GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error) {
res, err := c.sendGetRunnerHealthz(ctx)
return res, err
}
func (c *Client) sendGetRunnerHealthz(ctx context.Context) (res *RunnerHealthResponse, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRunnerHealthz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.URLTemplateKey.String("/healthz"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, GetRunnerHealthzOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [1]string
pathParts[0] = "/healthz"
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "GET", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeGetRunnerHealthzResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
// GetRunnerReadyz invokes 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 (c *Client) GetRunnerReadyz(ctx context.Context) (GetRunnerReadyzRes, error) {
res, err := c.sendGetRunnerReadyz(ctx)
return res, err
}
func (c *Client) sendGetRunnerReadyz(ctx context.Context) (res GetRunnerReadyzRes, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetRunnerReadyz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.URLTemplateKey.String("/readyz"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, GetRunnerReadyzOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [1]string
pathParts[0] = "/readyz"
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "GET", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeGetRunnerReadyzResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
// SubmitRun invokes 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 (c *Client) SubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error) {
res, err := c.sendSubmitRun(ctx, request, params)
return res, err
}
func (c *Client) sendSubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (res SubmitRunRes, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("SubmitRun"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.URLTemplateKey.String("/v1/runs/{run_id}"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, SubmitRunOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [2]string
pathParts[0] = "/v1/runs/"
{
// Encode "run_id" parameter.
e := uri.NewPathEncoder(uri.PathEncoderConfig{
Param: "run_id",
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
return e.EncodeValue(conv.UUIDToString(params.RunID))
}(); err != nil {
return res, errors.Wrap(err, "encode path")
}
encoded, err := e.Result()
if err != nil {
return res, errors.Wrap(err, "encode path")
}
pathParts[1] = encoded
}
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "PUT", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
if err := encodeSubmitRunRequest(request, r); err != nil {
return res, errors.Wrap(err, "encode request")
}
{
type bitset = [1]uint8
var satisfied bitset
{
stage = "Security:BearerAuth"
switch err := c.securityBearerAuth(ctx, SubmitRunOperation, r); {
case err == nil: // if NO error
satisfied[0] |= 1 << 0
case errors.Is(err, ogenerrors.ErrSkipClientSecurity):
// Skip this security.
default:
return res, errors.Wrap(err, "security \"BearerAuth\"")
}
}
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 {
return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied
}
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeSubmitRunResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
@@ -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
@@ -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"
)
@@ -0,0 +1,21 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/google/uuid"
)
// 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
}
// 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
}
@@ -0,0 +1,25 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"bytes"
"net/http"
"github.com/go-faster/jx"
ht "github.com/ogen-go/ogen/http"
)
func encodeSubmitRunRequest(
req *RunRequest,
r *http.Request,
) error {
const contentType = "application/json"
e := new(jx.Encoder)
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
@@ -0,0 +1,605 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"io"
"mime"
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/conv"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
)
func decodeGetRunResponse(resp *http.Response) (res *RunStatus, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response RunStatus
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
}
// Convenient error response.
defRes, err := func() (res *ProblemStatusCode, err error) {
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &ProblemStatusCode{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}()
if err != nil {
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
}
return res, errors.Wrap(defRes, "error")
}
func decodeGetRunnerHealthzResponse(resp *http.Response) (res *RunnerHealthResponse, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response RunnerHealthResponse
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
}
// Convenient error response.
defRes, err := func() (res *ProblemStatusCode, err error) {
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &ProblemStatusCode{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}()
if err != nil {
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
}
return res, errors.Wrap(defRes, "error")
}
func decodeGetRunnerReadyzResponse(resp *http.Response) (res GetRunnerReadyzRes, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response GetRunnerReadyzOK
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 503:
// Code 503.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response GetRunnerReadyzServiceUnavailable
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
}
// Convenient error response.
defRes, err := func() (res *ProblemStatusCode, err error) {
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &ProblemStatusCode{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}()
if err != nil {
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
}
return res, errors.Wrap(defRes, "error")
}
func decodeSubmitRunResponse(resp *http.Response) (res SubmitRunRes, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response SubmitRunOK
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 202:
// Code 202.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response SubmitRunAccepted
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 503:
// Code 503.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
var wrapper RunnerBusyHeaders
wrapper.Response = response
h := uri.NewHeaderDecoder(resp.Header)
// Parse "Retry-After" header.
{
cfg := uri.HeaderParameterDecodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := func() error {
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
wrapper.RetryAfter = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 3600,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(wrapper.RetryAfter)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "parse Retry-After header")
}
}
return &wrapper, nil
default:
return res, validate.InvalidContentType(ct)
}
}
// Convenient error response.
defRes, err := func() (res *ProblemStatusCode, err error) {
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.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 res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &ProblemStatusCode{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}()
if err != nil {
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
}
return res, errors.Wrap(defRes, "error")
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,55 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"net/http"
"github.com/go-faster/errors"
)
// SecuritySource is provider of security values (tokens, passwords, etc.).
type SecuritySource interface {
// BearerAuth provides bearerAuth security value.
// 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.
BearerAuth(ctx context.Context, operationName OperationName) (BearerAuth, error)
}
// 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 *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error {
t, err := s.sec.BearerAuth(ctx, operationName)
if err != nil {
return errors.Wrap(err, "security source \"BearerAuth\"")
}
req.Header.Set("Authorization", "Bearer "+t.Token)
return nil
}
File diff suppressed because it is too large. Load diff
+35 -2
View File
@@ -21,6 +21,12 @@ DEMO_FILE := $(ROOT)/deploy/docker/docker-compose.demo.yml
DEMO_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.demo.release.yml
RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml
ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml
# DEVELOPMENT ONLY: the privileged local code runner. It is never rendered
# together with a release overlay or started by a release target.
RUNNER_DEV_FILE := $(ROOT)/deploy/docker/docker-compose.runner.dev.yml
RUNNER_DEV_PROJECT ?= runner-dev
# Local random service token of the dev runner; runner/.gitignore keeps it out of Git.
RUNNER_DEV_TOKEN_FILE ?= $(ROOT)/runner/.dev/api-token
RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py
RELEASE := PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)"
# Pull policy of release-build for base and service images: missing or always.
@@ -58,7 +64,7 @@ DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DE
DEMO_RELEASE_MANIFEST="$(DEMO_RELEASE_MANIFEST)"
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs runner-dev-config runner-dev-build runner-dev-up runner-dev-down runner-dev-logs check-runner-dev check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
help: ## Show deployment commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -76,6 +82,7 @@ config: ## Render all Compose files with safe example values
APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(DEMO_FILE)" --profile demo-seed config --quiet
APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default LINCODEX_RELEASE_TAG=000000000000 DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" -f "$(DEMO_FILE)" -f "$(DEMO_RELEASE_FILE)" --profile demo-seed config --quiet
E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" config --quiet
build: ## Build local frontend and backend images
APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build
@@ -125,6 +132,29 @@ ml-logs: ## Follow ML service logs
@test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; }
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" logs -f
# DEVELOPMENT ONLY: the code runner in a privileged local container. See the
# header of docker-compose.runner.dev.yml; production runs the runner only on
# its dedicated VM.
runner-dev-config: ## Render the dev-only runner Compose file
RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" config --quiet
runner-dev-build: ## Build the runner image for the dev-only Compose project
RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" build
runner-dev-up: ## Start the dev-only privileged runner on 127.0.0.1 with a local random token
@if [ ! -s "$(RUNNER_DEV_TOKEN_FILE)" ]; then \
mkdir -p "$$(dirname "$(RUNNER_DEV_TOKEN_FILE)")"; \
(umask 077 && python3 -c 'import secrets; print(secrets.token_urlsafe(48))' > "$(RUNNER_DEV_TOKEN_FILE)"); \
printf 'Created the dev runner token file %s\n' "$(RUNNER_DEV_TOKEN_FILE)"; \
fi
RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" up -d --build
runner-dev-down: ## Stop the dev-only runner
RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" down
runner-dev-logs: ## Follow dev-only runner logs
RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" logs -f
# Edge proxy (TLS and tunnel templates under deploy/edge). edge.env is local;
# the checked-in example is used when it does not exist.
.PHONY: edge-render edge-config
@@ -138,7 +168,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release check-perimeter check-e2e-mail check-demo ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check: config check-workflows check-release check-perimeter check-e2e-mail check-demo check-runner-dev ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py'
@@ -152,6 +182,9 @@ check-perimeter: ## Check published ports, the app Nginx paths, limits, and the
check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E2E network
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_e2e_mail.py'
check-runner-dev: ## Check that the dev-only runner switches stay out of production files
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_runner_dev.py'
check-demo: ## Check the guards of the demo targets and the demo overlay without starting services
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_demo.py'
@@ -0,0 +1,59 @@
# DEVELOPMENT ONLY: the code runner on a developer machine (Docker Desktop).
#
# This file is never part of a release or a production deployment. It gives
# the container `privileged: true`, because nsjail needs namespaces and a
# writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain
# HTTP on loopback. A privileged container on the core application host is
# forbidden; production runs the runner image only inside its dedicated VM
# with TLS and without these switches (see docs/en/DEPLOY.md).
#
# Use it through make -C deploy runner-dev-up, which creates the local token
# file named by RUNNER_DEV_TOKEN_FILE.
services:
runner:
build:
context: ../../runner
dockerfile: Dockerfile
image: lincodex-runner-dev:local
# DEV ONLY: see the header.
privileged: true
cgroup: private
# Reaps any orphan as a second line of defense; the runner itself lets
# nsjail reap every jailed process.
init: true
read_only: true
environment:
RUNNER_LISTEN_ADDRESS: ":8080"
# DEV ONLY: production requires RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE.
RUNNER_DEV_ALLOW_PLAINTEXT_HTTP: "true"
RUNNER_API_TOKEN_FILE: /run/secrets/runner_api_token
RUNNER_MAX_CONCURRENT_RUNS: "1"
secrets:
- runner_api_token
tmpfs:
- /var/lib/lincodex-runner/work:size=64m,mode=0711
ports:
- "127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}:8080"
healthcheck:
test: ["CMD", "/opt/lincodex-runner/lincodex-runner", "healthcheck"]
interval: 10s
timeout: 3s
retries: 5
start_period: 5s
restart: unless-stopped
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
# The planned runner VM has 2 vCPU and 3 GB.
deploy:
resources:
limits:
cpus: "2.0"
memory: 3G
pids: 512
secrets:
runner_api_token:
file: ${RUNNER_DEV_TOKEN_FILE:?Set RUNNER_DEV_TOKEN_FILE or use make -C deploy runner-dev-up}
+97
View File
@@ -0,0 +1,97 @@
"""Check that the dev-only code runner switches stay out of production files.
The local runner Compose file gives the container `privileged: true` and
serves plain HTTP, because nsjail needs namespaces and a writable cgroup tree
inside Docker Desktop. Production runs the runner only in its dedicated VM.
These tests read files; the render test also needs the docker CLI.
"""
from __future__ import annotations
import json
import os
import re
import shutil
import subprocess
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DOCKER_DIR = ROOT / "deploy" / "docker"
DEV_FILE = DOCKER_DIR / "docker-compose.runner.dev.yml"
DEPLOY_MAKEFILE = ROOT / "deploy" / "Makefile"
RUNNER_DOCKERFILE = ROOT / "runner" / "Dockerfile"
RELEASE_SCRIPT = ROOT / "deploy" / "scripts" / "release_manifest.py"
DOCKER = os.environ.get("DOCKER", "docker")
DEV_SWITCHES = ("privileged", "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "docker-compose.runner.dev.yml")
# Make targets that may use the dev runner file.
DEV_TARGETS = {"config", "runner-dev-config", "runner-dev-build", "runner-dev-up", "runner-dev-down", "runner-dev-logs"}
TARGET = re.compile(r"^([A-Za-z0-9_-]+):")
class RunnerDevFilesTest(unittest.TestCase):
def test_the_dev_file_is_named_and_marked_as_development_only(self) -> None:
self.assertIn(".dev.", DEV_FILE.name)
header = DEV_FILE.read_text(encoding="utf-8").splitlines()[0]
self.assertTrue(header.startswith("# DEVELOPMENT ONLY"), header)
def test_production_compose_files_have_no_dev_switch(self) -> None:
for path in sorted(DOCKER_DIR.glob("docker-compose*.yml")):
if path == DEV_FILE:
continue
text = path.read_text(encoding="utf-8")
for switch in DEV_SWITCHES:
with self.subTest(file=path.name, switch=switch):
self.assertNotIn(switch, text)
def test_the_production_image_has_no_dev_switch(self) -> None:
text = RUNNER_DOCKERFILE.read_text(encoding="utf-8")
self.assertNotIn("RUNNER_DEV_", text)
self.assertNotIn("--privileged", text)
def test_release_tooling_never_uses_the_dev_file(self) -> None:
self.assertNotIn(DEV_FILE.name, RELEASE_SCRIPT.read_text(encoding="utf-8"))
def test_only_dev_targets_use_the_dev_file(self) -> None:
target = None
users = set()
for line in DEPLOY_MAKEFILE.read_text(encoding="utf-8").splitlines():
match = TARGET.match(line)
if match and not line.startswith(("\t", " ")):
target = match.group(1)
if "$(RUNNER_DEV_FILE)" in line and line.startswith("\t"):
users.add(target)
self.assertTrue(users)
self.assertLessEqual(users, DEV_TARGETS)
class RunnerDevRenderTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
if shutil.which(DOCKER) is None:
raise unittest.SkipTest("docker CLI is not available")
result = subprocess.run(
[DOCKER, "compose", "-p", "runner-dev-check", "-f", str(DEV_FILE), "config", "--format", "json"],
env={**os.environ, "RUNNER_DEV_TOKEN_FILE": "/dev/null"},
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise AssertionError(f"docker compose config failed: {result.stderr}")
cls.runner = json.loads(result.stdout)["services"]["runner"]
def test_the_dev_runner_publishes_only_loopback(self) -> None:
ports = self.runner.get("ports") or []
self.assertTrue(ports)
for port in ports:
self.assertEqual(port["host_ip"], "127.0.0.1")
def test_the_dev_runner_reads_the_token_from_a_secret_file(self) -> None:
environment = self.runner["environment"]
self.assertEqual(environment["RUNNER_API_TOKEN_FILE"], "/run/secrets/runner_api_token")
self.assertNotIn("RUNNER_API_TOKEN", environment)
if __name__ == "__main__":
unittest.main()
+26 -2
View File
@@ -26,9 +26,9 @@ The project brief assigns 35% of its score to matching, 25% to assessment and ca
## Contracts and code generation
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, api/ml/ contains internal Go-to-ML operations, and api/runner/ contains internal operations between Go and the code runner. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/, and the code runner Go client is configured at backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature.
@@ -537,6 +537,7 @@ The local release manifest separates core image verification from product data a
```text
api/core/ public browser-to-Go contract and bundle
api/ml/ internal Go-to-ML contract and bundle
api/runner/ internal Go-to-code-runner contract and bundle
backend/cmd/app/main.go calls bootstrap.Run and reports errors
backend/cmd/migrate/ local migration status, up, and down-one
backend/config/ shared runtime configuration
@@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ Orval configuration
ml/src/ FastAPI service and operational checks
ml/codegen/ Python datamodel-code-generator settings
runner/ Go code runner service: nsjail, cgroup v2, judge, and HTTP API
deploy/ Compose, Nginx, and technical smoke checks
observability/ Prometheus, Loki, Alloy, Grafana provisioning
scripts/ shared documentation and schema tooling
@@ -586,6 +588,7 @@ backend/
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
ml/api/ generated client from backend/codegen/ogen-ml.yml
code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
postgres/sqlc/ generated SQL adapter
redis/ cache adapter and Redis check
@@ -720,6 +723,27 @@ A category changes only by a strict grade upgrade (the database trigger and the
`basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation.
### Code runner
Code practice runs in the own `runner/` service; Judge0 is not used (GPL license, owner decision). The service receives the source, the limits, and the test groups through the internal `api/runner/` contract, runs every test in nsjail, and returns the outcome of every group. The backend computes the 0-3 score from the three hidden groups; the runner only reports which groups passed.
The A16 boundary. Untrusted code runs only on a separate runner host. The target production placement is a dedicated LXD VM on the app host (2 vCPU, 3 GB, one concurrent run) attached to a private bridge without internet access; the backend reaches it over TLS with a bearer token. A privileged container on the core host is forbidden, and a Docker network alone is not a boundary. The runner host holds no business secrets: only its TLS key and the API token.
Isolation layers of one run (implemented):
- nsjail in run-once mode: new network (empty, without loopback), PID, mount, IPC, UTS, user, and cgroup namespaces, `no_new_privs`, dropped capabilities, the user uid/gid 99999 inside and outside the user namespace, and no `/proc`.
- File system: the jail root is a read-only tmpfs; only `/usr` and `/lib` (the interpreter) are mounted read-only, the run directory with the source is mounted read-only as `/box`, plus `/dev/null` and `/dev/urandom`, and the working directory `/tmp` is a size-limited tmpfs. The run directory is removed after the run, and its root is emptied at startup.
- cgroup v2: the supervisor creates the cgroup of every run itself (`memory.max` with a small allowance for nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` for one CPU) and starts nsjail directly inside it with CLONE_INTO_CGROUP. The limits therefore cover the whole process tree, and the OOM, refused fork, and CPU counters are exact.
- rlimits: CPU, file size, open files, core 0, and address space.
- seccomp (kafel): the process is killed on ptrace, mount and namespace calls, keyrings, bpf, perf, userfaultfd, io_uring, kernel modules, and clock and swap administration; clone with namespace flags kills the process, clone3 answers ENOSYS, and sockets other than AF_UNIX answer EAFNOSUPPORT.
- The supervisor checks CPU, wall clock, OOM, and the process limit every 10 ms and, when a limit fires, kills the jailed processes but keeps nsjail so that it reaps its child; if nsjail does not exit within a second, the whole cgroup is killed. After a run the cgroup is removed only once it is empty.
The service bounds concurrent runs (1 by default) and answers 503 `runner_busy` when no slot is free; the backend keeps the queue. The contract and the configuration bound the request body, the source, the inputs, and the output. Logs carry only the method, operation, status, duration, run ID, language, group and test counts, and outcome; the source, test data, program output, and token never reach a log. Runs live only in memory and are forgotten after their TTL; the backend resubmits a run lost in a restart.
Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test.
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; Go (compile and run); a float tolerance checker and custom checkers; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`.
## Matching and explanations
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
+39
View File
@@ -735,6 +735,44 @@ Verified on the app host (TASK-592): from a guest on `lxdbr-runner` the internet
Cleanup before the rollout removed only the Docker build cache (`docker builder prune -af`, about 8 GB). `apt-get clean` and `journalctl --vacuum-size=100M` need sudo and are left to the operator. Docker volumes, the images of the running stack, `wg0`, `awg-lincodex` and the `ufw` rules are not touched.
## Code runner
The `runner/Dockerfile` image holds the Go supervisor, nsjail, and Python from `python:alpine`; pip and ensurepip are removed. The base images are the `GO_IMAGE` and `RUNTIME_IMAGE` arguments, so a release build can pin their digests. The supervisor runs as root inside its own host or VM because it needs namespaces, user mapping, and writes to its delegated cgroup. Candidate programs run as uid 99999 without capabilities.
### Local (development only)
`deploy/docker/docker-compose.runner.dev.yml` is a separate dev project `runner-dev`. It gives the container `privileged: true`, because nsjail needs namespaces and a writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain HTTP on 127.0.0.1 only. The file is never used by a release or in production; `make -C deploy check-runner-dev` checks that its switches stay out of the other Compose files, the production image, and the release tooling.
make -C deploy runner-dev-config
make -C deploy runner-dev-up
make -C deploy runner-dev-logs
make -C deploy runner-dev-down
`runner-dev-up` creates a local random token in `runner/.dev/api-token` (ignored by Git) when it is missing and starts the service on `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Call it with `Authorization: Bearer $(cat runner/.dev/api-token)` and `PUT /v1/runs/<uuid>` from the `api/runner/` contract.
### Production (planned)
The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)), never on the core host and never with the dev file. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. Rolling out the VM, issuing the certificate, storing the token for the backend, and monitoring are not implemented yet.
| Variable | Default | Purpose |
| --- | --- | --- |
| `RUNNER_LISTEN_ADDRESS` | `:8443` | HTTP(S) address |
| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | none | TLS 1.3 certificate and key; required outside dev |
| `RUNNER_API_TOKEN_FILE` or `RUNNER_API_TOKEN` | none | Token of at least 32 characters; prefer the file |
| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Dev Compose only: HTTP without TLS |
| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Concurrent runs; more answer 503 `runner_busy` |
| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Request body limit |
| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | In-memory result retention |
| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After when busy and the wait for runs at shutdown |
| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Run directories; emptied at startup, tmpfs recommended |
| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | The service's delegated cgroup v2 |
| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Paths in the image |
| `RUNNER_SANDBOX_UID` | `99999` | Program user, never root |
| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Processes and threads of a run |
| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Memory allowance for nsjail above the task limit |
| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | `/tmp` size, file size, and open files |
| `RUNNER_LOG_LEVEL` | `info` | JSON log level |
## Services and images
Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately.
@@ -752,6 +790,7 @@ Container images use moving `latest` or `alpine` tags where the upstream publish
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
| BusyBox | busybox | GPL-2.0-only |
| nsjail | Alpine `nsjail` package in the code runner image | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) |
Upstream references: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html).
+5 -3
View File
@@ -51,7 +51,7 @@ What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
@@ -100,22 +100,24 @@ Each top-level directory except `.github/` has a short Russian `README.md` and a
| --- | --- |
| api/core/ | Public browser-to-Go OpenAPI contract |
| api/ml/ | Internal Go-to-ML OpenAPI contract |
| api/runner/ | Internal OpenAPI contract between Go and the code runner |
| scripts/ | Shared schema merge, generated drift, and docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen |
| backend/config/ | Shared Go configuration outside internal |
| frontend/ | Vite SPA, Orval configuration, generated TypeScript |
| ml/ | Python service, lockfile, and Pydantic model generator |
| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests |
| deploy/ | Compose, Nginx, and smoke script |
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
| security/ | Scanner configuration, installation, Make targets, and local reports |
| .agents/ | Canonical project instructions and working standards |
| docs/ru/, docs/en/ | User documentation in Russian and English |
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
## Contracts and generation
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/ and api/ml/ and then bundle both inputs. The public and internal APIs remain separate contracts.
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts.
Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed.
+14
View File
@@ -581,6 +581,20 @@ What these tests do not show: a real invitation event through Kafka and the rela
The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker.
## Code runner tests
| Command | What it checks |
| --- | --- |
| make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token |
| make -C runner lint | golangci-lint for Linux, including the isolation tests |
| make -C runner check-generated | The generated ogen server matches the bundle |
| make -C runner test-sandbox | Isolation tests in a privileged dev container with real nsjail and cgroup v2 |
| make -C deploy check-runner-dev | Dev switches stay out of production files |
`test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process.
What the tests do not prove: isolation in the production VM (they have not run there yet), protection against kernel, nsjail, or cgroup vulnerabilities, the absence of side channels, or behavior under load. The full A16 isolation suite is planned separately and will extend the same fixtures.
## Future software validation
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
+27 -3
View File
@@ -26,15 +26,15 @@ Go владеет авторизацией, подтвержденными ка
## Контракты и генерация
Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Обе спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles.
Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML, api/runner/ - внутренний контракт Go и исполнителя кода. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Все спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles.
Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код.
Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/, Go-клиент исполнителя кода - по backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код.
Целевая версия OpenAPI - 3.2.0. Проверяется только используемое подмножество: bundling/lint, ogen, chi adapter, runtime путь API, Orval, Python-модели Pydantic и документация. Проверка одной fixture или чтение версии parser не доказывает поддержку всех возможностей OpenAPI 3.2.0.
В публичном API префикс /api/v1 применяется один раз. Служебный /metrics остается отдельным внутренним маршрутом. Health операции именуются с суффиксом z: healthz и readyz. DTO генераторов не заменяют проверку владельца, членства в компании, согласия или допустимости перехода бизнес-состояния.
Генерация идет из исходных контрактов. Core и ML bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную.
Генерация идет из исходных контрактов. Core, ML и runner bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную.
## Границы сервисов и данных
@@ -537,6 +537,7 @@ Offsets и партиции. Каждый обработчик - один уча
```text
api/core/ публичный контракт браузер-Go и bundle
api/ml/ внутренний контракт Go-ML и bundle
api/runner/ внутренний контракт Go и исполнителя кода и bundle
backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
backend/cmd/migrate/ локальные status, up и down-one для миграций
backend/config/ общая конфигурация runtime
@@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ конфигурация Orval
ml/src/ FastAPI сервис и operational checks
ml/codegen/ настройки Python datamodel-code-generator
runner/ Go-сервис исполнителя кода: nsjail, cgroup v2, judge и HTTP API
deploy/ Compose, Nginx и технические smoke checks
observability/ Prometheus, Loki, Alloy и Grafana provisioning
scripts/ общие инструменты для документации и схем
@@ -586,6 +588,7 @@ backend/
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует
ml/api/ generated client из backend/codegen/ogen-ml.yml
code_runner/api/ generated client из backend/codegen/ogen-code-runner.yml
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
@@ -720,6 +723,27 @@ contact_grant относится к паре кандидат-компания
`basis` - то же значение, что `source` решения о категории. Сейчас оно всегда `synthetic_demo`: база принимает только демонстрационный источник и `calibration_status = uncalibrated`. Поэтому карточки кандидата и подбор организаций показывают такую категорию как демонстрационную, а не как проверенное измерение. Основание обязательно в каждом объекте категории, поэтому категория без основания не может выглядеть стандартным подтверждением.
### Исполнитель кода
Практика с кодом исполняется собственным сервисом `runner/`; Judge0 не используется (лицензия GPL, решение владельца). Сервис принимает исходный код, лимиты и группы тестов по внутреннему контракту `api/runner/`, запускает каждый тест в nsjail и возвращает исход каждой группы. Балл 0-3 по трем скрытым группам считает backend; исполнитель только сообщает, какие группы пройдены.
Граница A16. Недоверенный код запускается только на отдельном хосте исполнителя. Целевое production-размещение - выделенная LXD VM на app-хосте (2 vCPU, 3 GB, один параллельный прогон), подключенная к частному bridge без выхода в интернет; backend обращается к ней по TLS с bearer-токеном. Привилегированный контейнер на core-хосте запрещен, а сеть Docker сама по себе не считается границей. На хосте исполнителя нет бизнес-секретов: только его TLS-ключ и токен API.
Слои изоляции одного прогона (реализовано):
- nsjail в режиме одного запуска: новые пространства имен network (пустое, без loopback), PID, mount, IPC, UTS, user и cgroup, `no_new_privs`, сброс capabilities, пользователь uid/gid 99999 внутри и снаружи user namespace, без `/proc`.
- Файловая система: корень jail - tmpfs, смонтированный только для чтения; внутрь попадают только `/usr` и `/lib` (интерпретатор) только для чтения, каталог прогона с исходником как `/box` только для чтения, `/dev/null` и `/dev/urandom`, а рабочий каталог `/tmp` - tmpfs ограниченного размера. Каталог прогона удаляется после прогона, его корень очищается при старте.
- cgroup v2: супервизор сам создает cgroup каждого прогона (`memory.max` с небольшим запасом на nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` на один CPU) и запускает nsjail сразу внутри него через CLONE_INTO_CGROUP. Поэтому лимиты покрывают весь процессный tree, а счетчики OOM, отказов fork и CPU точные.
- rlimits: CPU, размер файла, открытые файлы, core 0, адресное пространство.
- seccomp (kafel): завершение процесса при ptrace, mount и namespace-вызовах, keyring, bpf, perf, userfaultfd, io_uring, модулях ядра и администрировании часов и swap; clone с флагами namespace завершает процесс, clone3 отвечает ENOSYS, сокеты кроме AF_UNIX отвечают EAFNOSUPPORT.
- Супервизор отслеживает CPU, стену, OOM и лимит процессов каждые 10 мс и при срабатывании убивает процессы jail, оставляя nsjail, чтобы тот забрал своего потомка; если nsjail не завершился за секунду, убивается вся cgroup. После прогона cgroup удаляется только пустой.
Сервис ограничивает число параллельных прогонов (по умолчанию 1) и отвечает 503 `runner_busy` при занятом слоте; очередь держит backend. Размер тела запроса, исходника, входа и вывода ограничен контрактом и конфигурацией. Логи содержат только метод, операцию, статус, длительность, run ID, язык, число групп и тестов и исход; исходник, тестовые данные, вывод программы и токен в логи не попадают. Прогоны хранятся только в памяти и забываются после TTL; потерянный при рестарте прогон backend отправляет снова.
Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту.
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; Go (компиляция и запуск); checker с допуском для чисел и собственный checker; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`.
## Подбор и объяснение
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
+39
View File
@@ -737,6 +737,44 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml
Чистка перед раскаткой удалила только кеш сборки Docker (`docker builder prune -af`, около 8 ГБ). `apt-get clean` и `journalctl --vacuum-size=100M` требуют sudo и оставлены оператору. Тома Docker, образы работающего стека, `wg0`, `awg-lincodex` и правила `ufw` не затронуты.
## Исполнитель кода
Образ `runner/Dockerfile` содержит Go-супервизор, nsjail и Python из `python:alpine`; pip и ensurepip удалены. Базовые образы - аргументы `GO_IMAGE` и `RUNTIME_IMAGE`, поэтому сборка выпуска может закрепить их digest. Супервизор работает root внутри своего хоста или VM: ему нужны namespaces, отображение пользователя и запись в делегированную cgroup. Программы кандидата работают как uid 99999 без capabilities.
### Локально (только разработка)
`deploy/docker/docker-compose.runner.dev.yml` - отдельный dev-проект `runner-dev`. Он дает контейнеру `privileged: true`, потому что nsjail внутри VM Docker Desktop нужны namespaces и записываемая cgroup v2, и обслуживает простой HTTP только на 127.0.0.1. Этот файл никогда не используется в выпуске или production; `make -C deploy check-runner-dev` проверяет, что его переключатели не попали в другие Compose-файлы, production-образ и инструменты выпуска.
make -C deploy runner-dev-config
make -C deploy runner-dev-up
make -C deploy runner-dev-logs
make -C deploy runner-dev-down
`runner-dev-up` создает локальный случайный токен в `runner/.dev/api-token` (игнорируется Git), если его нет, и запускает сервис на `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Вызов: `Authorization: Bearer $(cat runner/.dev/api-token)` и `PUT /v1/runs/<uuid>` по контракту `api/runner/`.
### Production (запланировано)
Исполнитель работает только в VM `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)), никогда на core-хосте и никогда с dev-файлом. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). Раскатка VM, выпуск сертификата, хранение токена на стороне backend и мониторинг еще не реализованы.
| Переменная | По умолчанию | Назначение |
| --- | --- | --- |
| `RUNNER_LISTEN_ADDRESS` | `:8443` | Адрес HTTP(S) |
| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | нет | Сертификат и ключ TLS 1.3; обязательны вне dev |
| `RUNNER_API_TOKEN_FILE` или `RUNNER_API_TOKEN` | нет | Токен не короче 32 символов; предпочтителен файл |
| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Только dev Compose: HTTP без TLS |
| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Параллельные прогоны; сверх них 503 `runner_busy` |
| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Лимит тела запроса |
| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | Хранение результатов в памяти |
| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After при занятости и ожидание прогонов при остановке |
| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Каталоги прогонов; очищается при старте, рекомендуется tmpfs |
| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | Делегированная cgroup v2 сервиса |
| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Пути в образе |
| `RUNNER_SANDBOX_UID` | `99999` | Пользователь программ, не root |
| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Процессы и потоки прогона |
| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Запас памяти на nsjail сверх лимита задания |
| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | Размер `/tmp`, размер файла и открытые файлы |
| `RUNNER_LOG_LEVEL` | `info` | Уровень JSON-логов |
## Сервисы и образы
Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно.
@@ -754,6 +792,7 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
| BusyBox | busybox | GPL-2.0-only |
| nsjail | пакет Alpine `nsjail` в образе исполнителя кода | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) |
Ссылки на upstream: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html).
+5 -3
View File
@@ -51,7 +51,7 @@ Frontend зависимости выбираются из актуальных s
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
- OpenAPI контракты api/core/, api/ml/ и api/runner/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий).
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
@@ -100,22 +100,24 @@ Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `Same
| --- | --- |
| api/core/ | Публичный OpenAPI контракт браузер-Go |
| api/ml/ | Внутренний OpenAPI контракт Go-ML |
| api/runner/ | Внутренний OpenAPI контракт Go и исполнителя кода |
| scripts/ | Общее объединение схем, generated drift и docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя |
| backend/config/ | Общая конфигурация Go вне internal |
| frontend/ | Vite SPA, Orval config и generated TypeScript |
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
| runner/ | Go-сервис исполнителя кода: nsjail, cgroup v2, judge, ogen-сервер и тесты изоляции |
| deploy/ | Compose, Nginx и smoke |
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
| security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты |
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Go client исполнителя кода создается из backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
## Контракты и генерация
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/ и api/ml/, затем bundles для обоих входов. Публичный и внутренний API не объединяются в одну спецификацию.
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/, api/ml/ и api/runner/, затем bundles для каждого входа. Публичный и внутренние API не объединяются в одну спецификацию.
Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его.
+14
View File
@@ -581,6 +581,20 @@ Vitest работает в Node без DOM, поэтому ограничени
Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker.
## Тесты исполнителя кода
| Команда | Что проверяет |
| --- | --- |
| make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах |
| make -C runner lint | golangci-lint для Linux, включая тесты изоляции |
| make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle |
| make -C runner test-sandbox | Тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 |
| make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы |
`test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс.
Что тесты не доказывают: изоляцию в production VM (там они еще не запускались), защиту от уязвимостей ядра, nsjail или cgroup, отсутствие побочных каналов и устойчивость под нагрузкой. Полный набор проверок A16 запланирован отдельно и расширит те же fixtures.
## Будущая программная валидация
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
+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)
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more