feat(labs): describe the lab task contract and the provisioner port
This commit is contained in:
1 parent
3de226b16c
commit
9fdaa62b9b
91 files changed
+19262
-155
No files matched your search
@@ -14,6 +14,7 @@ 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/lab_provisioner/api/",
|
||||
"backend/internal/adapter/secondary/postgres/sqlc/",
|
||||
"frontend/src/shared/api/endpoints/",
|
||||
"frontend/src/shared/api/schemas/",
|
||||
@@ -27,6 +28,8 @@ GENERATED_FILES = {
|
||||
"api/ml/components/schemas.yml",
|
||||
"api/runner/openapi.bundle.yml",
|
||||
"api/runner/components/schemas.yml",
|
||||
"api/labd/openapi.bundle.yml",
|
||||
"api/labd/components/schemas.yml",
|
||||
"ml/src/lincodex_ml/api/models.py",
|
||||
}
|
||||
SOURCE_SUFFIXES = {".go", ".ts", ".tsx", ".js", ".sql", ".json", ".py"}
|
||||
|
||||
@@ -333,7 +333,7 @@ class AssessmentContractTest(unittest.TestCase):
|
||||
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"])
|
||||
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"])
|
||||
|
||||
def test_attempt_items_and_answers_keep_the_seven_public_formats(self) -> None:
|
||||
def test_attempt_items_and_answers_keep_the_public_formats(self) -> None:
|
||||
expected = {
|
||||
"choice",
|
||||
"number",
|
||||
@@ -343,7 +343,9 @@ class AssessmentContractTest(unittest.TestCase):
|
||||
"configuration",
|
||||
"practice",
|
||||
}
|
||||
self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected)
|
||||
# A lab item is served like the others, but its lab is submitted only
|
||||
# with SubmitMyAssessmentLab, so `lab` is not an answer format.
|
||||
self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected | {"lab"})
|
||||
self.assertEqual(union_enum_values(self.schemas["AssessmentAnswer"], self.schemas), expected)
|
||||
|
||||
def test_candidate_schemas_do_not_name_secrets_or_employer_access(self) -> None:
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
"""Pin the privacy, capacity, and authentication rules of the lab contracts.
|
||||
|
||||
The candidate lab operations of api/core and the internal lab provisioner
|
||||
contract api/labd must never return a node address, a credential, the
|
||||
variant seed, or checker state to a party that does not need it, and a busy
|
||||
lab pool must be a 503 with Retry-After that changes nothing. 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"
|
||||
CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml"
|
||||
LABD_BUNDLE = API_DIR / "labd" / "openapi.bundle.yml"
|
||||
ML_BUNDLE = API_DIR / "ml" / "openapi.bundle.yml"
|
||||
SCHEMA_PREFIX = "#/components/schemas/"
|
||||
RESPONSE_PREFIX = "#/components/responses/"
|
||||
PARAMETER_PREFIX = "#/components/parameters/"
|
||||
EXAMPLE_PREFIX = "#/components/examples/"
|
||||
HTTP_METHODS = ("get", "put", "post", "patch", "delete")
|
||||
|
||||
CANDIDATE_LAB_OPERATIONS = {
|
||||
"CreateMyAssessmentLab",
|
||||
"GetMyAssessmentLab",
|
||||
"CreateMyAssessmentLabConsoleSession",
|
||||
"SubmitMyAssessmentLab",
|
||||
}
|
||||
LABD_HEALTH_OPERATIONS = {"GetLabdHealthz", "GetLabdReadyz"}
|
||||
|
||||
# Property names that would reveal where a node lives, how to log in to it,
|
||||
# or how the answer is checked. Fragments match inside longer names such as
|
||||
# `mgmt_ipv4` or `ssh_key`.
|
||||
INFRASTRUCTURE_FRAGMENTS = (
|
||||
"address",
|
||||
"bridge",
|
||||
"credential",
|
||||
"gateway",
|
||||
"host",
|
||||
"instance",
|
||||
"ipv4",
|
||||
"ipv6",
|
||||
"key",
|
||||
"mac",
|
||||
"netmask",
|
||||
"password",
|
||||
"port",
|
||||
"secret",
|
||||
"snapshot",
|
||||
"ssh",
|
||||
"subnet",
|
||||
)
|
||||
INFRASTRUCTURE_NAMES = {"ip", "cidr", "url", "uri"}
|
||||
# The candidate additionally never sees the seed, the checker, or a token.
|
||||
CANDIDATE_ONLY_FRAGMENTS = (
|
||||
"check",
|
||||
"criteri",
|
||||
"score",
|
||||
"seed",
|
||||
"template",
|
||||
"token",
|
||||
"verdict",
|
||||
)
|
||||
# Request fields that would link a lab to a person or a product record. The
|
||||
# provisioner needs none of them.
|
||||
PERSONAL_FRAGMENTS = (
|
||||
"account",
|
||||
"attempt",
|
||||
"candidate",
|
||||
"company",
|
||||
"contact",
|
||||
"email",
|
||||
"item",
|
||||
"organization",
|
||||
"person",
|
||||
"phone",
|
||||
"profile",
|
||||
"session",
|
||||
"user",
|
||||
)
|
||||
|
||||
|
||||
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 operation_by_id(document: dict[str, Any], operation_id: str) -> dict[str, Any]:
|
||||
for _, _, _, operation in operations(document):
|
||||
if operation["operationId"] == operation_id:
|
||||
return operation
|
||||
raise AssertionError(f"operation {operation_id} is missing")
|
||||
|
||||
|
||||
def resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]:
|
||||
reference = response.get("$ref")
|
||||
if isinstance(reference, str):
|
||||
if not reference.startswith(RESPONSE_PREFIX):
|
||||
raise AssertionError(f"unexpected bundled reference: {reference}")
|
||||
return document["components"]["responses"][reference[len(RESPONSE_PREFIX) :]]
|
||||
return response
|
||||
|
||||
|
||||
def resolve_parameter(document: dict[str, Any], parameter: dict[str, Any]) -> dict[str, Any]:
|
||||
reference = parameter.get("$ref")
|
||||
if isinstance(reference, str):
|
||||
if not reference.startswith(PARAMETER_PREFIX):
|
||||
raise AssertionError(f"unexpected bundled reference: {reference}")
|
||||
return document["components"]["parameters"][reference[len(PARAMETER_PREFIX) :]]
|
||||
return parameter
|
||||
|
||||
|
||||
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):
|
||||
if not reference.startswith(SCHEMA_PREFIX):
|
||||
raise AssertionError(f"unexpected bundled reference: {reference}")
|
||||
name = reference[len(SCHEMA_PREFIX) :]
|
||||
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 success_schemas(document: dict[str, Any], operation_ids: set[str]) -> Iterator[tuple[str, Any]]:
|
||||
"""Yield the JSON schema of every 2xx response of the given operations."""
|
||||
for path, method, _, operation in operations(document):
|
||||
if operation["operationId"] not in operation_ids:
|
||||
continue
|
||||
for status, response in operation["responses"].items():
|
||||
if not str(status).startswith("2"):
|
||||
continue
|
||||
for media in resolve_response(document, response).get("content", {}).values():
|
||||
yield f"{method.upper()} {path} {status}", media["schema"]
|
||||
|
||||
|
||||
def matching_fields(
|
||||
document: dict[str, Any],
|
||||
sources: Iterator[tuple[str, Any]],
|
||||
fragments: tuple[str, ...],
|
||||
names: set[str],
|
||||
) -> list[str]:
|
||||
schemas = document["components"]["schemas"]
|
||||
found: list[str] = []
|
||||
for location, source in sources:
|
||||
for object_location, object_schema in walk_schema(source, schemas, set(), location):
|
||||
for property_name in object_schema.get("properties", {}):
|
||||
lowered = property_name.lower()
|
||||
if lowered in names or any(fragment in lowered for fragment in fragments):
|
||||
found.append(f"{object_location}.{property_name}")
|
||||
return found
|
||||
|
||||
|
||||
def candidate_lab_schemas(document: dict[str, Any]) -> Iterator[tuple[str, Any]]:
|
||||
"""Yield the lab responses and the lab item content that the attempt serves."""
|
||||
yield from success_schemas(document, CANDIDATE_LAB_OPERATIONS)
|
||||
yield "ItemContent lab", {"$ref": SCHEMA_PREFIX + "LabItemContent"}
|
||||
|
||||
|
||||
def candidate_leaks(document: dict[str, Any]) -> list[str]:
|
||||
return matching_fields(
|
||||
document,
|
||||
candidate_lab_schemas(document),
|
||||
INFRASTRUCTURE_FRAGMENTS + CANDIDATE_ONLY_FRAGMENTS,
|
||||
INFRASTRUCTURE_NAMES,
|
||||
)
|
||||
|
||||
|
||||
def labd_operation_ids(document: dict[str, Any]) -> set[str]:
|
||||
return {operation["operationId"] for _, _, _, operation in operations(document)}
|
||||
|
||||
|
||||
def labd_leaks(document: dict[str, Any]) -> list[str]:
|
||||
return matching_fields(
|
||||
document,
|
||||
success_schemas(document, labd_operation_ids(document)),
|
||||
INFRASTRUCTURE_FRAGMENTS + ("seed",),
|
||||
INFRASTRUCTURE_NAMES,
|
||||
)
|
||||
|
||||
|
||||
def labd_request_identifiers(document: dict[str, Any]) -> list[str]:
|
||||
schemas = document["components"]["schemas"]
|
||||
found: list[str] = []
|
||||
for path, method, item, operation in operations(document):
|
||||
for reference in [*item.get("parameters", []), *operation.get("parameters", [])]:
|
||||
parameter = resolve_parameter(document, reference)
|
||||
name = parameter["name"].lower()
|
||||
if any(fragment in name for fragment in PERSONAL_FRAGMENTS):
|
||||
found.append(f"{method.upper()} {path} parameter {parameter['name']}")
|
||||
for media in operation.get("requestBody", {}).get("content", {}).values():
|
||||
location = f"{method.upper()} {path} body"
|
||||
for object_location, object_schema in walk_schema(media["schema"], schemas, set(), location):
|
||||
for property_name in object_schema.get("properties", {}):
|
||||
if any(fragment in property_name.lower() for fragment in PERSONAL_FRAGMENTS):
|
||||
found.append(f"{object_location}.{property_name}")
|
||||
return found
|
||||
|
||||
|
||||
class CandidateLabContractTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.document = load(CORE_BUNDLE)
|
||||
self.schemas = self.document["components"]["schemas"]
|
||||
|
||||
def test_every_lab_operation_exists(self) -> None:
|
||||
for operation_id in CANDIDATE_LAB_OPERATIONS:
|
||||
with self.subTest(operation=operation_id):
|
||||
operation_by_id(self.document, operation_id)
|
||||
|
||||
def test_responses_carry_no_address_key_or_checker_state(self) -> None:
|
||||
self.assertEqual(candidate_leaks(self.document), [])
|
||||
|
||||
def test_detector_finds_planted_leaks(self) -> None:
|
||||
planted = copy.deepcopy(self.document)
|
||||
planted["components"]["schemas"]["AssessmentLabNode"]["properties"]["mgmt_ipv4"] = {"type": "string"}
|
||||
planted["components"]["schemas"]["AssessmentLab"]["properties"]["checker_score"] = {"type": "integer"}
|
||||
planted["components"]["schemas"]["AssessmentLabConsoleSession"]["properties"]["ssh_key"] = {"type": "string"}
|
||||
leaks = candidate_leaks(planted)
|
||||
for field in ("nodes.items.mgmt_ipv4", "checker_score", "ssh_key"):
|
||||
with self.subTest(field=field):
|
||||
self.assertTrue(any(leak.endswith(field) for leak in leaks), leaks)
|
||||
|
||||
def test_lab_objects_reject_unknown_fields(self) -> None:
|
||||
for name in (
|
||||
"AssessmentLab",
|
||||
"AssessmentLabNode",
|
||||
"AssessmentLabCreate",
|
||||
"AssessmentLabConsoleSession",
|
||||
"AssessmentLabConsoleSessionCreate",
|
||||
"AssessmentLabSubmission",
|
||||
"LabAnswer",
|
||||
"LabItemContent",
|
||||
):
|
||||
with self.subTest(schema=name):
|
||||
self.assertIs(self.schemas[name].get("additionalProperties"), False)
|
||||
|
||||
def test_answer_format_lab_names_only_the_lab(self) -> None:
|
||||
answer = self.schemas["LabAnswer"]
|
||||
self.assertEqual(answer["properties"]["format"]["enum"], ["lab"])
|
||||
self.assertEqual(set(answer["properties"]), {"format", "lab_id"})
|
||||
self.assertEqual(self.schemas["LabItemContent"]["properties"]["format"]["enum"], ["lab"])
|
||||
submission = operation_by_id(self.document, "SubmitMyAssessmentLab")
|
||||
body = submission["requestBody"]["content"]["application/json"]["schema"]
|
||||
self.assertEqual(body["$ref"], SCHEMA_PREFIX + "AssessmentLabSubmission")
|
||||
|
||||
def test_busy_pool_is_a_retryable_503_that_changes_nothing(self) -> None:
|
||||
create = operation_by_id(self.document, "CreateMyAssessmentLab")
|
||||
reference = create["responses"]["503"]["$ref"]
|
||||
self.assertEqual(reference, RESPONSE_PREFIX + "ServiceUnavailable")
|
||||
busy = resolve_response(self.document, create["responses"]["503"])
|
||||
self.assertIn("Retry-After", busy["headers"])
|
||||
self.assertIn("application/problem+json", busy["content"])
|
||||
description = create["description"]
|
||||
self.assertIn("answers 503 service_unavailable with Retry-After", description)
|
||||
self.assertIn("Nothing was stored", description)
|
||||
self.assertIn("the attempt is not consumed", description)
|
||||
# The 503 is not replayed under the Idempotency-Key, so a retry is
|
||||
# evaluated again once capacity is free.
|
||||
self.assertIn("400, 429, and 503 are not", description)
|
||||
for operation_id in ("CreateMyAssessmentLabConsoleSession", "SubmitMyAssessmentLab"):
|
||||
with self.subTest(operation=operation_id):
|
||||
operation = operation_by_id(self.document, operation_id)
|
||||
self.assertEqual(operation["responses"]["503"]["$ref"], reference)
|
||||
|
||||
def test_lab_is_an_item_format_answered_only_by_its_own_operation(self) -> None:
|
||||
self.assertIn({"$ref": SCHEMA_PREFIX + "LabItemContent"}, self.schemas["ItemContent"]["oneOf"])
|
||||
answer_formats = set()
|
||||
for variant in self.schemas["AssessmentAnswer"]["oneOf"]:
|
||||
name = variant["$ref"][len(SCHEMA_PREFIX) :]
|
||||
answer_formats.update(self.schemas[name]["properties"]["format"]["enum"])
|
||||
self.assertNotIn("lab", answer_formats)
|
||||
users = [
|
||||
name
|
||||
for name, schema in self.schemas.items()
|
||||
if SCHEMA_PREFIX + "LabAnswer" in yaml.safe_dump(schema)
|
||||
]
|
||||
self.assertEqual(users, ["AssessmentLabSubmission"])
|
||||
answers = operation_by_id(self.document, "SubmitMyAssessmentAnswer")
|
||||
self.assertIn("SubmitMyAssessmentLab", answers["description"])
|
||||
self.assertIn("`/answer/format`", answers["description"])
|
||||
|
||||
def test_lab_problems_reuse_existing_codes(self) -> None:
|
||||
codes = set(self.schemas["ProblemCode"]["enum"])
|
||||
self.assertFalse({code for code in codes if code.startswith("lab_") or "_lab" in code})
|
||||
for operation_id in CANDIDATE_LAB_OPERATIONS:
|
||||
operation = operation_by_id(self.document, operation_id)
|
||||
for status, response in operation["responses"].items():
|
||||
content = resolve_response(self.document, response).get("content", {})
|
||||
for example in content.get("application/problem+json", {}).get("examples", {}).values():
|
||||
reference = example.get("$ref")
|
||||
if isinstance(reference, str):
|
||||
self.assertTrue(reference.startswith(EXAMPLE_PREFIX), reference)
|
||||
example = self.document["components"]["examples"][reference[len(EXAMPLE_PREFIX) :]]
|
||||
value = example["value"]
|
||||
with self.subTest(operation=operation_id, status=status):
|
||||
self.assertIn(value["code"], codes)
|
||||
|
||||
def test_problem_codes_stay_identical_to_the_ml_copy(self) -> None:
|
||||
ml = load(ML_BUNDLE)["components"]["schemas"]["ProblemCode"]["enum"]
|
||||
self.assertEqual(self.schemas["ProblemCode"]["enum"], ml)
|
||||
|
||||
def test_mutating_lab_operations_require_csrf(self) -> None:
|
||||
for operation_id in CANDIDATE_LAB_OPERATIONS - {"GetMyAssessmentLab"}:
|
||||
with self.subTest(operation=operation_id):
|
||||
operation = operation_by_id(self.document, operation_id)
|
||||
self.assertEqual(operation["security"], [{"sessionCookie": [], "sessionCsrf": []}])
|
||||
|
||||
|
||||
class LabProvisionerContractTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.document = load(LABD_BUNDLE)
|
||||
self.schemas = self.document["components"]["schemas"]
|
||||
|
||||
def test_operations_cover_the_lab_lifecycle(self) -> None:
|
||||
self.assertEqual(
|
||||
labd_operation_ids(self.document) - LABD_HEALTH_OPERATIONS,
|
||||
{"CreateLab", "GetLab", "DeleteLab", "CreateLabConsoleToken", "CheckLab"},
|
||||
)
|
||||
|
||||
def test_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 LABD_HEALTH_OPERATIONS:
|
||||
self.assertEqual(operation.get("security"), [])
|
||||
else:
|
||||
self.assertNotIn("security", operation, f"{method} {path} must use the global bearer rule")
|
||||
|
||||
def test_requests_carry_no_personal_or_product_identifiers(self) -> None:
|
||||
self.assertEqual(labd_request_identifiers(self.document), [])
|
||||
|
||||
def test_responses_carry_no_address_key_or_seed(self) -> None:
|
||||
self.assertEqual(labd_leaks(self.document), [])
|
||||
|
||||
def test_detector_finds_planted_leaks(self) -> None:
|
||||
planted = copy.deepcopy(self.document)
|
||||
planted["components"]["schemas"]["LabNode"]["properties"]["ipv4_address"] = {"type": "string"}
|
||||
planted["components"]["schemas"]["LabCreateRequest"]["properties"]["candidate_id"] = {"type": "string"}
|
||||
self.assertEqual(
|
||||
[leak.rsplit(".", 1)[-1] for leak in labd_leaks(planted)],
|
||||
["ipv4_address"] * len(labd_leaks(planted)),
|
||||
)
|
||||
self.assertTrue(labd_leaks(planted))
|
||||
self.assertEqual(
|
||||
labd_request_identifiers(planted),
|
||||
["PUT /v1/labs/{lab_id} body.candidate_id"],
|
||||
)
|
||||
|
||||
def test_request_objects_reject_unknown_fields(self) -> None:
|
||||
for _, _, _, operation in operations(self.document):
|
||||
for media in operation.get("requestBody", {}).get("content", {}).values():
|
||||
for location, schema in walk_schema(media["schema"], self.schemas, set(), operation["operationId"]):
|
||||
with self.subTest(location=location):
|
||||
self.assertIs(schema.get("additionalProperties"), False)
|
||||
|
||||
def test_busy_pool_is_separate_from_an_infrastructure_failure(self) -> None:
|
||||
codes = set(self.schemas["ProblemCode"]["enum"])
|
||||
self.assertTrue({"lab_pool_busy", "lab_unavailable", "unauthenticated", "idempotency_key_reused"} <= codes)
|
||||
create = self.document["paths"]["/v1/labs/{lab_id}"]["put"]
|
||||
busy = resolve_response(self.document, create["responses"]["503"])
|
||||
self.assertTrue(busy["headers"]["Retry-After"]["required"])
|
||||
example = busy["content"]["application/problem+json"]["examples"]["lab_pool_busy"]["value"]
|
||||
self.assertEqual((example["status"], example["code"]), (503, "lab_pool_busy"))
|
||||
self.assertTrue({"200", "202", "503", "default"} <= set(create["responses"]))
|
||||
|
||||
def test_create_is_idempotent_by_lab_id(self) -> None:
|
||||
item = self.document["paths"]["/v1/labs/{lab_id}"]
|
||||
(reference,) = item["parameters"]
|
||||
parameter = resolve_parameter(self.document, reference)
|
||||
self.assertEqual((parameter["in"], parameter["schema"]["format"]), ("path", "uuid"))
|
||||
self.assertNotIn("lab_id", self.schemas["LabCreateRequest"]["properties"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user