feat(runner): add the own code runner contract, client and nsjail service
This commit is contained in:
1 parent
5e1db37746
commit
cdf6bcbb91
109 files changed
+24084
-28
No files matched your search
@@ -13,9 +13,11 @@ from pathlib import Path
|
||||
GENERATED_PREFIXES = (
|
||||
"backend/internal/adapter/primary/http/api/",
|
||||
"backend/internal/adapter/secondary/ml/api/",
|
||||
"backend/internal/adapter/secondary/code_runner/api/",
|
||||
"backend/internal/adapter/secondary/postgres/sqlc/",
|
||||
"frontend/src/shared/api/endpoints/",
|
||||
"frontend/src/shared/api/schemas/",
|
||||
"runner/internal/api/",
|
||||
)
|
||||
GENERATED_BASENAMES = {"wire_gen.go"}
|
||||
GENERATED_FILES = {
|
||||
@@ -23,6 +25,8 @@ GENERATED_FILES = {
|
||||
"api/core/components/schemas.yml",
|
||||
"api/ml/openapi.bundle.yml",
|
||||
"api/ml/components/schemas.yml",
|
||||
"api/runner/openapi.bundle.yml",
|
||||
"api/runner/components/schemas.yml",
|
||||
"ml/src/lincodex_ml/api/models.py",
|
||||
}
|
||||
SOURCE_SUFFIXES = {".go", ".ts", ".tsx", ".js", ".sql", ".json", ".py"}
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Pin the privacy, authentication, and outcome rules of the code runner contract.
|
||||
|
||||
These tests read the bundled contracts, so run them after `make -C api bundle`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
import yaml
|
||||
|
||||
API_DIR = Path(__file__).resolve().parents[1] / "api"
|
||||
RUNNER_BUNDLE = API_DIR / "runner" / "openapi.bundle.yml"
|
||||
CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml"
|
||||
SCHEMA_PREFIX = "#/components/schemas/"
|
||||
HTTP_METHODS = ("get", "put", "post", "patch", "delete")
|
||||
HEALTH_OPERATIONS = {"GetRunnerHealthz", "GetRunnerReadyz"}
|
||||
|
||||
# Request fields that would identify a person or link a run to product
|
||||
# records. The runner needs none of them.
|
||||
FORBIDDEN_FIELDS = {
|
||||
"account",
|
||||
"account_id",
|
||||
"attempt",
|
||||
"attempt_id",
|
||||
"candidate",
|
||||
"candidate_id",
|
||||
"company_id",
|
||||
"contact",
|
||||
"contacts",
|
||||
"email",
|
||||
"first_name",
|
||||
"full_name",
|
||||
"ip",
|
||||
"ip_address",
|
||||
"last_name",
|
||||
"name",
|
||||
"organization_id",
|
||||
"phone",
|
||||
"profile_id",
|
||||
"session",
|
||||
"session_id",
|
||||
"task_id",
|
||||
"telegram",
|
||||
"user",
|
||||
"user_agent",
|
||||
"user_id",
|
||||
"username",
|
||||
}
|
||||
FORBIDDEN_FRAGMENTS = (
|
||||
"account",
|
||||
"attempt",
|
||||
"candidate",
|
||||
"company",
|
||||
"contact",
|
||||
"email",
|
||||
"organization",
|
||||
"person",
|
||||
"phone",
|
||||
"profile",
|
||||
"session",
|
||||
"user",
|
||||
)
|
||||
REQUIRED_OUTCOMES = {
|
||||
"accepted",
|
||||
"wrong_answer",
|
||||
"compile_error",
|
||||
"time_limit_exceeded",
|
||||
"memory_limit_exceeded",
|
||||
"output_limit_exceeded",
|
||||
"runtime_error",
|
||||
"infrastructure_failure",
|
||||
}
|
||||
PROBLEM_SHAPES = ("Problem", "ProblemFieldError", "ProblemFieldLocation")
|
||||
|
||||
|
||||
def load(path: Path) -> dict[str, Any]:
|
||||
with path.open(encoding="utf-8") as stream:
|
||||
document = yaml.safe_load(stream)
|
||||
if not isinstance(document, dict):
|
||||
raise AssertionError(f"{path} is not an OpenAPI document")
|
||||
return document
|
||||
|
||||
|
||||
def operations(document: dict[str, Any]) -> Iterator[tuple[str, str, dict[str, Any], dict[str, Any]]]:
|
||||
for path, item in document["paths"].items():
|
||||
for method in HTTP_METHODS:
|
||||
if method in item:
|
||||
yield path, method, item, item[method]
|
||||
|
||||
|
||||
def schema_name(reference: str) -> str:
|
||||
if not reference.startswith(SCHEMA_PREFIX):
|
||||
raise AssertionError(f"unexpected bundled reference: {reference}")
|
||||
return reference[len(SCHEMA_PREFIX) :]
|
||||
|
||||
|
||||
def walk_schema(
|
||||
schema: Any, schemas: dict[str, Any], seen: set[str], location: str
|
||||
) -> Iterator[tuple[str, dict[str, Any]]]:
|
||||
"""Yield every object schema reachable from schema with its location."""
|
||||
if isinstance(schema, list):
|
||||
for index, item in enumerate(schema):
|
||||
yield from walk_schema(item, schemas, seen, f"{location}[{index}]")
|
||||
return
|
||||
if not isinstance(schema, dict):
|
||||
return
|
||||
reference = schema.get("$ref")
|
||||
if isinstance(reference, str):
|
||||
name = schema_name(reference)
|
||||
if name not in seen:
|
||||
seen.add(name)
|
||||
yield from walk_schema(schemas[name], schemas, seen, location)
|
||||
return
|
||||
if schema.get("type") == "object" or "properties" in schema:
|
||||
yield location, schema
|
||||
for property_name, property_schema in schema.get("properties", {}).items():
|
||||
yield from walk_schema(property_schema, schemas, seen, f"{location}.{property_name}")
|
||||
for key in ("items", "additionalProperties"):
|
||||
if isinstance(schema.get(key), dict):
|
||||
yield from walk_schema(schema[key], schemas, seen, f"{location}.{key}")
|
||||
for key in ("allOf", "oneOf", "anyOf"):
|
||||
if key in schema:
|
||||
yield from walk_schema(schema[key], schemas, seen, f"{location}.{key}")
|
||||
|
||||
|
||||
def request_inputs(document: dict[str, Any]) -> Iterator[tuple[str, Any]]:
|
||||
"""Yield parameter names and request body schemas of every operation."""
|
||||
for path, method, item, operation in operations(document):
|
||||
for parameter in [*item.get("parameters", []), *operation.get("parameters", [])]:
|
||||
yield f"{method.upper()} {path} parameter", {"parameter": parameter["name"]}
|
||||
body = operation.get("requestBody", {})
|
||||
for media in body.get("content", {}).values():
|
||||
yield f"{method.upper()} {path} body", media["schema"]
|
||||
|
||||
|
||||
def forbidden_name(name: str) -> bool:
|
||||
lowered = name.lower()
|
||||
return lowered in FORBIDDEN_FIELDS or any(fragment in lowered for fragment in FORBIDDEN_FRAGMENTS)
|
||||
|
||||
|
||||
def personal_fields(document: dict[str, Any]) -> list[str]:
|
||||
schemas = document["components"]["schemas"]
|
||||
found: list[str] = []
|
||||
for location, source in request_inputs(document):
|
||||
if "parameter" in source:
|
||||
if forbidden_name(source["parameter"]):
|
||||
found.append(f"{location}: {source['parameter']}")
|
||||
continue
|
||||
for object_location, object_schema in walk_schema(source, schemas, set(), location):
|
||||
for property_name in object_schema.get("properties", {}):
|
||||
if forbidden_name(property_name):
|
||||
found.append(f"{object_location}.{property_name}")
|
||||
return found
|
||||
|
||||
|
||||
def without_descriptions(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {key: without_descriptions(item) for key, item in value.items() if key != "description"}
|
||||
if isinstance(value, list):
|
||||
return [without_descriptions(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
class RunnerContractTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.document = load(RUNNER_BUNDLE)
|
||||
self.schemas = self.document["components"]["schemas"]
|
||||
|
||||
def test_requests_carry_no_personal_or_product_identifiers(self) -> None:
|
||||
self.assertEqual(personal_fields(self.document), [])
|
||||
|
||||
def test_detector_finds_a_planted_identifier(self) -> None:
|
||||
planted = copy.deepcopy(self.document)
|
||||
planted["components"]["schemas"]["TestCase"]["properties"]["candidate_id"] = {"type": "string"}
|
||||
planted["components"]["schemas"]["RunLimits"]["properties"]["user_email"] = {"type": "string"}
|
||||
self.assertEqual(
|
||||
sorted(personal_fields(planted)),
|
||||
sorted(
|
||||
[
|
||||
"PUT /v1/runs/{run_id} body.groups.items.tests.items.candidate_id",
|
||||
"PUT /v1/runs/{run_id} body.limits.user_email",
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
def test_request_objects_reject_unknown_fields(self) -> None:
|
||||
for location, source in request_inputs(self.document):
|
||||
if "parameter" in source:
|
||||
continue
|
||||
for object_location, object_schema in walk_schema(source, self.schemas, set(), location):
|
||||
with self.subTest(location=object_location):
|
||||
self.assertIs(object_schema.get("additionalProperties"), False)
|
||||
|
||||
def test_run_operations_require_the_bearer_token(self) -> None:
|
||||
scheme = self.document["components"]["securitySchemes"]["bearerAuth"]
|
||||
self.assertEqual((scheme["type"], scheme["scheme"]), ("http", "bearer"))
|
||||
self.assertEqual(self.document["security"], [{"bearerAuth": []}])
|
||||
for path, method, _, operation in operations(self.document):
|
||||
with self.subTest(operation=operation["operationId"]):
|
||||
if operation["operationId"] in HEALTH_OPERATIONS:
|
||||
self.assertEqual(operation.get("security"), [])
|
||||
else:
|
||||
self.assertNotIn("security", operation, f"{method} {path} must use the global bearer rule")
|
||||
|
||||
def test_outcomes_distinguish_every_required_result(self) -> None:
|
||||
self.assertEqual(set(self.schemas["RunOutcome"]["enum"]), REQUIRED_OUTCOMES)
|
||||
|
||||
def test_submit_run_is_idempotent_by_run_id(self) -> None:
|
||||
item = self.document["paths"]["/v1/runs/{run_id}"]
|
||||
(parameter,) = item["parameters"]
|
||||
self.assertEqual((parameter["in"], parameter["schema"]["format"]), ("path", "uuid"))
|
||||
responses = item["put"]["responses"]
|
||||
self.assertTrue({"200", "202", "503", "default"} <= set(responses))
|
||||
busy = self.document["components"]["responses"]["RunnerBusy"]
|
||||
self.assertTrue(busy["headers"]["Retry-After"]["required"])
|
||||
codes = set(self.schemas["ProblemCode"]["enum"])
|
||||
self.assertTrue({"idempotency_key_reused", "runner_busy", "unauthenticated"} <= codes)
|
||||
self.assertNotIn("run_id", self.schemas["RunRequest"]["properties"])
|
||||
|
||||
def test_problem_shape_matches_core(self) -> None:
|
||||
core = load(CORE_BUNDLE)["components"]["schemas"]
|
||||
for name in PROBLEM_SHAPES:
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(without_descriptions(self.schemas[name]), without_descriptions(core[name]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user