ctfy.sdk.node_client
HTTP client for platform → node machine calls.
Every call is authenticated with the target node's bearer token —
minted per node at registration and used in both directions. End users
never touch this client; they talk to the platform, which proxies to
the node. Node endpoints are defined in
server/routes/node_instances.py.
1"""HTTP client for platform → node machine calls. 2 3Every call is authenticated with the target node's bearer token — 4minted per node at registration and used in both directions. End users 5never touch this client; they talk to the platform, which proxies to 6the node. Node endpoints are defined in 7``server/routes/node_instances.py``. 8""" 9 10from __future__ import annotations 11 12import base64 13import dataclasses 14import json 15from collections.abc import Iterable, Iterator, Mapping, Sequence 16from pathlib import Path 17from typing import Any, TypeVar 18from urllib.parse import quote 19 20import httpx 21from pydantic import BaseModel, Field, ValidationError 22 23from ctfy.challenge.deception import DeceptionSummary 24from ctfy.core.agent_log import NodeAgentLog 25from ctfy.core.attachment_layout import ( 26 InvalidAttachmentName, 27 attachment_url_path, 28 component_refusal, 29) 30from ctfy.core.awd_network import MatchNetwork 31from ctfy.core.challenge import ChallengeReloadResult 32from ctfy.core.constants import ( 33 DEFAULT_CLIENT_TIMEOUT, 34 HARNESS_CREATE_TIMEOUT_S, 35 HARNESS_IMAGE_INSPECT_TIMEOUT_S, 36 IMAGE_PULL_TIMEOUT_S, 37) 38from ctfy.core.enums import InternetAccess, TcpAccess 39from ctfy.core.exceptions import NodeRequestError 40from ctfy.core.exploit_wire import ( 41 FRAMED, 42 FRAMED_CONTENT_TYPE, 43 REQUEST_BYTES_HEADER, 44 ExploitBody, 45) 46from ctfy.core.failure_text import tail 47from ctfy.core.freeze_budget import freeze_client_wait_s, freeze_deadline_s 48from ctfy.core.instance_disk_retention import ( 49 CAPTURE_DROPPED_BYTES_HEADER, 50 CAPTURE_DROPPED_SEGMENTS_HEADER, 51) 52from ctfy.core.judge_budget import DEFAULT_JUDGE_TIMEOUT_S, judge_exec_s 53from ctfy.core.judge_budget import platform_wait_s as judge_platform_wait_s 54from ctfy.core.log import log 55from ctfy.core.node_features import CAPABILITY_FEATURES, feature_enabled 56from ctfy.core.observed_contact import ContactReading 57from ctfy.core.patch_budget import patch_client_wait_s 58from ctfy.core.prebuild_tag import ChallengeFreezeResult 59from ctfy.core.resource_budget import ResourceBudget 60from ctfy.core.smoke_budget import SOLUTION_BUILD_TIMEOUT_S 61from ctfy.core.smoke_live import NodeSmokeProgress 62from ctfy.sdk.base import RETRY_UNSENT, BaseHttpClient 63from ctfy.server.models.challenge import AttachmentList 64from ctfy.server.models.instance import InstanceTrafficPage, InstanceTrafficWitnesses 65from ctfy.server.models.node import ( 66 AgentIngressPeer, 67 AgentIngressPeerRemoved, 68 AgentIngressPeerRequest, 69 AgentRuntime, 70 AwdAttackResult, 71 BuildAllQueued, 72 BuildPushCancelled, 73 BuildPushProgress, 74 BuildStateRows, 75 CheckResult, 76 ComposeContainer, 77 FabricProbeReport, 78 FabricStatus, 79 HarnessImagePolicy, 80 HarnessLimits, 81 HarnessRegistryAuth, 82 HarnessRun, 83 HarnessRunResult, 84 InstanceHeld, 85 InstanceInternetChange, 86 InstanceInternetChanged, 87 InstanceStarted, 88 InstanceStatusReport, 89 NodeAuthoredPush, 90 NodeAuthoredResult, 91 NodeAuthoredSmokePush, 92 NodeAuthoredSmokeResult, 93 NodeCapabilities, 94 NodeDiskFree, 95 NodeInstanceList, 96 NodeInstanceSummary, 97 NodeRangePush, 98 NodeRangeResult, 99 NodeRangeVerifyPush, 100 NodeRangeVerifyResult, 101 NodeSmokeEntrance, 102 NodeSmokeExploitOutcome, 103 PatchVerifyResult, 104 PullAllQueued, 105 PullStateRows, 106) 107from ctfy.server.node_state import ChallengeBuildState, ChallengePullState 108from ctfy.server.traffic_tail import coerce_page 109 110 111@dataclasses.dataclass(frozen=True) 112class PcapCapture: 113 """A node's merged capture, and what the cap dropped from it (#1714).""" 114 115 data: bytes 116 #: ``None`` = the node did not say (older build); ``0`` = nothing. 117 dropped_bytes: int | None = None 118 dropped_segments: int | None = None 119 120 121def _header_int(resp: httpx.Response, name: str) -> int | None: 122 raw = resp.headers.get(name) 123 if raw is None: 124 return None 125 try: 126 return max(0, int(raw)) 127 except ValueError: 128 return None 129 130 131def _raise_for_node_status(resp: httpx.Response) -> None: 132 """Like ``resp.raise_for_status()`` but preserves the node's error body. 133 134 On a 4xx/5xx, pull the FastAPI ``{"detail": ...}`` field (or the raw 135 body as a fallback) and raise :class:`NodeRequestError` so the real 136 failure reaches the caller instead of httpx's generic status string. 137 """ 138 if not resp.is_error: 139 return 140 detail = "" 141 code = "" 142 try: 143 body = resp.json() 144 except (json.JSONDecodeError, ValueError): 145 body = None 146 if isinstance(body, dict): 147 d = body.get("detail") 148 if isinstance(d, str): 149 detail = d 150 elif isinstance(d, dict) and isinstance(d.get("code"), str): 151 # A node naming its failure (#1835): keep the name as a field 152 # and the sentence as the detail, so neither a reader of the 153 # code nor a human reading the detail meets JSON. 154 code = str(d["code"]) 155 message = d.get("message") 156 detail = message if isinstance(message, str) else json.dumps(d) 157 elif d is not None: 158 detail = json.dumps(d) 159 if not detail: 160 detail = (resp.text or "").strip() 161 raise NodeRequestError(resp.status_code, detail, code=code) 162 163 164_M = TypeVar("_M", bound=BaseModel) 165 166 167def _parsed(model: type[_M], resp: httpx.Response) -> _M: 168 """The node's answer, as the model the node itself declares. 169 170 ⚠️ **A parse failure raises rather than defaulting.** Its neighbour 171 ``instance_health`` falls back to an empty ``DeceptionSummary``, and 172 that is right there: the summary is decoration on a liveness answer 173 the caller already has. These carry the *verdict* — whether a checker 174 passed, what an attack read — and a default is a verdict nobody 175 reached. The checker's own fail direction is closed, and an answer 176 this client cannot parse is not an answer. 177 178 ⚠️ Unknown fields are ignored (pydantic's default), which is the 179 forward-compatible half: the node and the platform are deployed 180 separately, ``ctfy/core/version.py`` exists because they skew, and a 181 newer node sending a field this platform has never heard of must not 182 fail the call. 183 """ 184 try: 185 return model.model_validate(resp.json()) 186 except (ValidationError, ValueError) as exc: 187 # ⚠️ ``resp.status_code``, not a synthetic one: the node 188 # *answered*, and the failure is that its body does not fit the 189 # contract. Reporting a 502 here would say the node was 190 # unreachable, which sends whoever reads it to the wrong host. 191 raise NodeRequestError( 192 resp.status_code, 193 f"answered something this platform cannot read as {model.__name__}: {exc}", 194 ) from exc 195 196 197def _parsed_list(model: type[_M], resp: httpx.Response) -> list[_M]: 198 """A JSON array of *model*, with the same failure direction as 199 :func:`_parsed` — one unreadable element fails the call rather than 200 being dropped, because a partial list read as a whole one is how a 201 re-adoption pass decides an instance is gone.""" 202 body = resp.json() 203 if not isinstance(body, list): 204 raise NodeRequestError( 205 resp.status_code, f"expected a list of {model.__name__}, got {type(body).__name__}" 206 ) 207 try: 208 return [model.model_validate(item) for item in body] 209 except (ValidationError, ValueError) as exc: 210 raise NodeRequestError( 211 resp.status_code, 212 f"answered something this platform cannot read as a list of {model.__name__}: {exc}", 213 ) from exc 214 215 216class HealthReading(BaseModel): 217 """One health poll's three answers. 218 219 ⚠️ **A record rather than a tuple, and the reason is recorded one 220 subsystem over.** ``competition_results`` lost ``attempts`` and 221 ``last_solve_at`` to a hand-made ``(rank, flags, solved)`` tuple 222 sitting between a board that produced them and a template that 223 consumed them; this poll had two answers and now has three, so the 224 tuple was one field away from the same fate. Growing a record is a 225 field; growing a tuple is every call site, silently re-bound. 226 """ 227 228 healthy: bool = False 229 deception: DeceptionSummary = Field(default_factory=DeceptionSummary) 230 contact: ContactReading = Field(default_factory=ContactReading) 231 new_processes: dict[str, list[str]] = Field(default_factory=dict) 232 233 234def masked_capabilities(caps: NodeCapabilities, disabled: Iterable[str]) -> NodeCapabilities: 235 """*caps* with every feature in *disabled* answered ``False`` (#3037). 236 237 The effective value is *supported by the node* AND *enabled by the 238 admin*. ⚠️ Only names that are features are masked 239 (`ctfy.core.node_features.CAPABILITY_FEATURES`), so an unknown or stale name 240 in the row turns nothing off — the switch fails open. A placement switch 241 (``public_ports``) is not a capability and is asked by placement instead. 242 """ 243 off = [f for f in CAPABILITY_FEATURES if not feature_enabled(disabled, f)] 244 if not off: 245 return caps 246 update: dict[str, object] = dict.fromkeys(off, False) 247 for flag in off: 248 reason = f"{flag}_reason" 249 if reason in NodeCapabilities.model_fields: 250 update[reason] = "switched off by an admin on this node" 251 return caps.model_copy(update=update) 252 253 254#: How much of an exploit archive one body chunk carries (a multiple of 3, so 255#: each chunk's base64 is whole). 256_ARCHIVE_CHUNK = 3 * (1 << 18) 257 258#: Stands in for ``exploit.archive_b64`` while the JSON is serialised; the 259#: archive's base64 is streamed in its place. 260_ARCHIVE_SLOT = "@@ctfy-exploit-archive-b64@@" 261 262 263class _ArchiveBody: 264 """A body that streams *archive* between *head* and *tail* (#3628). 265 266 ⚠️ Re-iterable, never a generator: a retry of an unsent request 267 (``RETRY_UNSENT``) iterates it again and reopens the file. 268 """ 269 270 def __init__(self, head: bytes, archive: Path, tail: bytes, *, b64: bool) -> None: 271 self.head, self.archive, self.tail, self.b64 = head, archive, tail, b64 272 273 def __len__(self) -> int: 274 size = self.archive.stat().st_size 275 return len(self.head) + (4 * -(-size // 3) if self.b64 else size) + len(self.tail) 276 277 def __iter__(self) -> Iterator[bytes]: 278 yield self.head 279 with self.archive.open("rb") as f: 280 while chunk := f.read(_ARCHIVE_CHUNK): 281 yield base64.b64encode(chunk) if self.b64 else chunk 282 if self.tail: 283 yield self.tail 284 285 286def harness_run_content( 287 body: dict[str, Any], archive: Path, *, exploit_body: ExploitBody 288) -> dict[str, Any]: 289 """``content`` and ``headers`` for a harness run whose exploit archive is *archive*. 290 291 ⚠️ **Streamed either way (#3628)**: the archive is never read whole, 292 base64'd and serialised beside itself on the writer. To a node that reads 293 the framed body (``exploit_body="framed"``) it rides raw after the JSON 294 (`core.exploit_wire`); to an older one it is the same JSON it always read, 295 ``exploit.archive_b64`` spliced in as base64 of each chunk. 296 """ 297 exploit = body.get("exploit") 298 if not isinstance(exploit, dict): 299 raise ValueError("an exploit archive needs the exploit's fields") 300 if exploit_body == FRAMED: 301 head = json.dumps({**body, "exploit": {**exploit, "archive_b64": ""}}).encode() 302 stream = _ArchiveBody(head, archive, b"", b64=False) 303 headers = { 304 "Content-Type": FRAMED_CONTENT_TYPE, 305 REQUEST_BYTES_HEADER: str(len(head)), 306 } 307 else: 308 text = json.dumps({**body, "exploit": {**exploit, "archive_b64": _ARCHIVE_SLOT}}) 309 before, slot, after = text.partition(json.dumps(_ARCHIVE_SLOT)) 310 if not slot or _ARCHIVE_SLOT in after: 311 raise ValueError("the exploit's archive slot is not unique in the request") 312 stream = _ArchiveBody((before + '"').encode(), archive, ('"' + after).encode(), b64=True) 313 headers = {"Content-Type": "application/json"} 314 return {"content": stream, "headers": {**headers, "Content-Length": str(len(stream))}} 315 316 317class NodeClient(BaseHttpClient): 318 """Thin sync HTTP client; one instance per node URL.""" 319 320 def __init__( 321 self, 322 node_url: str, 323 token: str, 324 *, 325 timeout: int = DEFAULT_CLIENT_TIMEOUT, 326 max_retries: int = 2, 327 transport: httpx.BaseTransport | None = None, 328 disabled_features: Iterable[str] = (), 329 ) -> None: 330 """*disabled_features* are the features an admin switched off on this 331 node (#3037, `ctfy.core.node_features`): :meth:`capabilities` answers 332 ``False`` for each, whatever the node says, so a caller reads the 333 effective value and cannot forget the switch. ``()`` is the raw answer 334 — every platform construction passes the node row's set 335 (`test_every_node_client_carries_the_switches`). 336 337 *transport* is `BaseHttpClient`'s own seam, passed through so a 338 test can drive a real node app over the real client — the hop the 339 fakes on either side of it cannot see. 340 341 *max_retries* is passed through too: a best-effort read or a stop 342 is tried once (#2812), because a retry on a timeout multiplies the 343 one number that has to stay small. 344 345 ⚠️ **A call that starts long work retries only a request that never 346 left** (#3162, :data:`~ctfy.sdk.base.RETRY_UNSENT`): every POST here 347 that names its own HTTP timeout says so per call, because a 348 ``ReadTimeout`` is a request the node has and is still running. 349 ``start_instance`` keeps the default — the node replays it from the 350 instance id. Guarded by `ctfy/tests/test_long_node_work_is_sent_once.py`.""" 351 super().__init__( 352 f"{node_url.rstrip('/')}/api/v1", 353 token, 354 timeout=timeout, 355 max_retries=max_retries, 356 transport=transport, 357 ) 358 self.disabled_features = frozenset(disabled_features) 359 360 # -- lifecycle ---------------------------------------------------------- 361 362 def start_instance( 363 self, 364 *, 365 challenge_id: str, 366 instance_id: str, 367 ttl: int, 368 answers: dict[str, str], 369 proxy_output_dir: str | None = None, 370 env: dict[str, str] | None = None, 371 publish_gamebox: bool = False, 372 match_network: MatchNetwork | None = None, 373 open_shell_password: str = "", 374 authored_revision: str = "", 375 internet: InternetAccess = InternetAccess.ALLOW, 376 tcp_access: TcpAccess = TcpAccess.TLS_SNI, 377 egress_allow_hosts: list[str] | None = None, 378 resource_budget: ResourceBudget | None = None, 379 compose_up_timeout_s: int = 0, 380 vpn_callback: bool = False, 381 ) -> InstanceStarted: 382 resp = self.request( 383 "POST", 384 "/instances", 385 json={ 386 # #1835: the authored tree's revision this start must run; 387 # a node holding another (or none) fetches it first. 388 "authored_revision": authored_revision, 389 "challenge_id": challenge_id, 390 "instance_id": instance_id, 391 "ttl": ttl, 392 "answers": answers, 393 "proxy_output_dir": proxy_output_dir, 394 "env": env or {}, 395 "publish_gamebox": publish_gamebox, 396 # ``None`` rather than an omitted key: the node's model 397 # defaults to None either way, and sending it explicitly 398 # keeps the body's shape stable across both branches. 399 "match_network": (dataclasses.asdict(match_network) if match_network else None), 400 # Classic-AWD open shell (#1725): the box's starting root 401 # password, empty for every managed / non-AWD start. 402 "open_shell_password": open_shell_password, 403 # #1969: ``deny`` holds the box off the internet; the hosts 404 # are the platform-internal ones it still reaches. 405 "internet": str(internet), 406 # #2082: how a player reaches the box's TCP services. 407 "tcp_access": str(tcp_access), 408 "egress_allow_hosts": list(egress_allow_hosts or []), 409 # The CPU / memory a player-authored box is held to; ``None`` 410 # for the corpus and from an older platform. 411 "resource_budget": ( 412 resource_budget.model_dump() if resource_budget is not None else None 413 ), 414 # #3165: the platform's ``compose_up_timeout_s``, so the node 415 # spends the budget the platform waits on; ``0`` = the node's own. 416 "compose_up_timeout_s": compose_up_timeout_s, 417 # #3598: arm the tunnel's callback forward (one-team boxes only). 418 "vpn_callback": vpn_callback, 419 }, 420 ) 421 _raise_for_node_status(resp) 422 return _parsed(InstanceStarted, resp) 423 424 def stop_instance(self, instance_id: str) -> None: 425 resp = self.request("DELETE", f"/instances/{instance_id}") 426 resp.raise_for_status() 427 428 def apply_fabric( 429 self, 430 *, 431 index: int, 432 interface: dict[str, Any], 433 match_network: str = "", 434 ) -> FabricStatus: 435 """Put this node on one match's WireGuard fabric. 436 437 ⚠️ **Returns the model, never ``resp.json()``.** The platform 438 reads the verdict field by field, and on a dict a renamed field 439 is ``None`` — falsy — which reads as "the arena did not open", 440 so a wire change would quietly report every node as broken. 441 442 Returns the node's verdict rather than raising on a refusal: the 443 route answers **200 with a body** precisely so that "this node is 444 unreachable" and "this node rejected the plan" stay different 445 facts, and a caller fanning out over an arena needs to tell them 446 apart — one is waited on, the other is looked at. 447 448 *match_network* lets the node check the tunnel landed in the 449 namespace its boxes are in, and open the bridge's one hole. It is 450 the platform's own fact (`awd_network.network_name`), so the node 451 is told rather than guessing. 452 """ 453 resp = self.request( 454 "POST", 455 "/fabric", 456 json={ 457 "index": index, 458 "interface": interface, 459 "match_network": match_network, 460 }, 461 ) 462 resp.raise_for_status() 463 return _parsed(FabricStatus, resp) 464 465 def probe_fabric( 466 self, 467 *, 468 index: int, 469 peers: list[dict[str, str]], 470 mtu: int = 0, 471 ) -> FabricProbeReport: 472 """Ask named peers the three link questions. Applies nothing. 473 474 ⚠️ **Returns the model, never ``resp.json()``** — same reason 475 `apply_fabric` gives: on a dict a renamed field reads as falsy, 476 which here means "your tunnel is down" about a wire change. 477 """ 478 resp = self.request( 479 "POST", 480 "/fabric/probe", 481 json={"index": index, "peers": peers, "mtu": mtu}, 482 ) 483 resp.raise_for_status() 484 return _parsed(FabricProbeReport, resp) 485 486 def remove_fabric(self, *, index: int, match_network: str = "") -> FabricStatus: 487 """Take this node off one match's fabric and close its hole. 488 489 ⚠️ *match_network* is what lets the node resolve the bridge and 490 delete the ``DOCKER-USER`` rules by name. Without it the tunnel 491 goes and the hole stays — open on whatever docker gives that 492 bridge name next. 493 """ 494 resp = self.request( 495 "DELETE", 496 f"/fabric/{index}", 497 params={"match_network": match_network}, 498 ) 499 resp.raise_for_status() 500 return _parsed(FabricStatus, resp) 501 502 def stop_instance_service(self, instance_id: str, service: str) -> int: 503 """Stop one compose service, leaving the instance running. 504 505 The exercise format's session close (§4b.4). Returns how many 506 containers the node stopped — 0 means the challenge declares no 507 such service, which is a real answer rather than a failure, so 508 the caller can distinguish it from a cut tunnel. 509 """ 510 resp = self.request( 511 "POST", 512 f"/instances/{instance_id}/stop-service", 513 json={"service": service}, 514 ) 515 resp.raise_for_status() 516 body = resp.json() 517 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0 518 519 def capabilities( 520 self, *, harness_admission: bool = False, agent_ingress: bool = False 521 ) -> NodeCapabilities: 522 """What this node can do beyond the original verbs. 523 524 ⚠️ **A 404 is an answer, not an error**: a node from before hold / 525 resume has no such route, and "cannot hold" is exactly what the 526 platform needs to hear -- the caller then falls back to deleting. 527 Any other failure raises, because an unreachable node is not a node 528 that cannot hold. 529 """ 530 # ⚠️ #2356: ``harness_admission`` makes the node prove it can hold 531 # an admitted run, which writes its host firewall — asked only by 532 # the admission paths, never by hold / internet. 533 # #3020: ``agent_ingress`` makes the node converge its listener, 534 # asked only before handing a published target over WireGuard. 535 params = { 536 **({"harness_admission": "true"} if harness_admission else {}), 537 **({"agent_ingress": "true"} if agent_ingress else {}), 538 } 539 resp = self.request("GET", "/capabilities", params=params or None) 540 if resp.status_code == 404: 541 return NodeCapabilities() 542 resp.raise_for_status() 543 return masked_capabilities(_parsed(NodeCapabilities, resp), self.disabled_features) 544 545 def create_agent_ingress_peer( 546 self, *, run_id: str, public_key: str, ports: list[int], ttl_s: int 547 ) -> AgentIngressPeer: 548 """Add *run_id*'s peer to the node's agent-ingress listener (#3020). 549 550 Only the public key crosses; the caller keeps the private half. 551 Raises on any non-2xx (the node's refusal is in the detail). 552 """ 553 body = AgentIngressPeerRequest( 554 run_id=run_id, public_key=public_key, ports=ports, ttl_s=ttl_s 555 ) 556 resp = self.request("POST", "/agent-ingress/peers", json=body.model_dump(mode="json")) 557 resp.raise_for_status() 558 return _parsed(AgentIngressPeer, resp) 559 560 def delete_agent_ingress_peer(self, run_id: str) -> bool: 561 """Revoke *run_id*'s peer; ``False`` when the node held none.""" 562 resp = self.request("DELETE", f"/agent-ingress/peers/{run_id}") 563 resp.raise_for_status() 564 return _parsed(AgentIngressPeerRemoved, resp).removed 565 566 def hold_instance(self, instance_id: str, mode: str) -> int: 567 """Pause or stop an instance, removing nothing. Returns containers held.""" 568 resp = self.request("POST", f"/instances/{instance_id}/hold", json={"mode": mode}) 569 resp.raise_for_status() 570 return _parsed(InstanceHeld, resp).count 571 572 def resume_instance(self, instance_id: str) -> int: 573 """Bring a held instance back. Returns containers brought back.""" 574 resp = self.request("POST", f"/instances/{instance_id}/resume") 575 resp.raise_for_status() 576 return _parsed(InstanceHeld, resp).count 577 578 def change_instance_internet( 579 self, instance_id: str, change: InstanceInternetChange 580 ) -> InstanceInternetChanged: 581 """Change a running box's internet verdict (#2067). 582 583 Raises :class:`NodeRequestError` on any refusal, carrying the node's 584 ``code`` (:data:`~ctfy.core.exceptions.NODE_INTERNET_CHANGE_FAILED` 585 when its firewall could not converge — the node has then put its 586 record back, so nothing changed). 587 """ 588 resp = self.request( 589 "POST", f"/instances/{instance_id}/internet", json=change.model_dump(mode="json") 590 ) 591 _raise_for_node_status(resp) 592 return _parsed(InstanceInternetChanged, resp) 593 594 def stop_all(self) -> None: 595 resp = self.request("POST", "/admin/stop-all") 596 resp.raise_for_status() 597 598 def put_authored_challenge(self, push: NodeAuthoredPush) -> NodeAuthoredResult: 599 """Ask the node to write an approved player upload into its catalog. 600 601 ⚠️ **The bytes travel here, unlike `put_generated_range`.** That 602 one sends a scenario because the node can compile it; a 603 player-authored tree has no compiler and no corpus entry, so the 604 archive is what there is to send. 605 606 The node answers **200 with ``ok: false``** for a refusal, so a 607 node that declined the archive and a node that could not be 608 reached stay different facts; only the second raises here. 609 """ 610 resp = self.request("POST", "/admin/authored", json=push.model_dump(mode="json")) 611 resp.raise_for_status() 612 return _parsed(NodeAuthoredResult, resp) 613 614 def smoke_authored_challenge( 615 self, push: NodeAuthoredSmokePush, *, timeout: int | None = None 616 ) -> NodeAuthoredSmokeResult: 617 """Ask the node to run an authored challenge's own reference exploit. 618 619 ⚠️ **Takes its own timeout.** A smoke run brings a whole estate 620 up; the client default is sized for a status call and would give 621 up while the node is still doing what it was asked. 622 """ 623 kwargs: dict[str, Any] = {"json": push.model_dump(mode="json")} 624 if timeout is not None: 625 kwargs["timeout"] = timeout 626 resp = self.request("POST", "/admin/authored/smoke", retry_on=RETRY_UNSENT, **kwargs) 627 resp.raise_for_status() 628 return _parsed(NodeAuthoredSmokeResult, resp) 629 630 def smoke_progress(self, run_id: str, since: int = 0) -> NodeSmokeProgress | None: 631 """The steps and lines a running smoke has produced since *since* (#2145). 632 633 ``None`` when the node holds no feed for *run_id* — a node older than 634 the feed, or a run that never started — which a watcher reads as 635 *unwatched*. Any other failure raises: the caller decides that a 636 watcher's trouble must never fail the run it watches. 637 """ 638 # ⚠️ A short timeout of its own: this is read once a second beside a 639 # run that may be minutes long, and a read that hangs on a busy worker 640 # must not hold the watcher past the run it watches. 641 resp = self.request( 642 "GET", 643 f"/admin/authored/smoke/{run_id}/progress", 644 params={"since": since}, 645 timeout=10, 646 ) 647 if resp.status_code == 404: 648 return None 649 resp.raise_for_status() 650 return _parsed(NodeSmokeProgress, resp) 651 652 def smoke_entrance(self, run_id: str) -> NodeSmokeEntrance: 653 """The player's entrance to the smoke box held for *run_id* (#2819 W2). 654 655 ``pending`` / ``ready`` / ``gone``; a 404 (a node older than the 656 route) raises, which the caller reads as *this node cannot hold*. 657 """ 658 resp = self.request("GET", f"/admin/authored/smoke/{run_id}/entrance", timeout=15) 659 resp.raise_for_status() 660 return _parsed(NodeSmokeEntrance, resp) 661 662 def post_smoke_exploit(self, run_id: str, outcome: NodeSmokeExploitOutcome) -> bool: 663 """Hand the held smoke box its exploit outcome (#2819 W2). 664 665 ``True`` when the node took it; ``False`` when it holds no box for 666 *run_id* any more (it tore down on its own timeout) or had one. 667 """ 668 resp = self.request( 669 "POST", 670 f"/admin/authored/smoke/{run_id}/exploit", 671 json=outcome.model_dump(mode="json"), 672 timeout=30, 673 # First outcome wins on the node, so a resend is harmless; but a 674 # read timeout is a post that may have landed (#3162). 675 retry_on=RETRY_UNSENT, 676 ) 677 if resp.status_code == 404: 678 return False 679 resp.raise_for_status() 680 return bool(resp.json().get("taken")) 681 682 def harness_log(self, run_id: str, after: int = 0) -> NodeAgentLog | None: 683 """An agent run's console lines numbered above *after* (#2401). 684 685 ``None`` when the node holds no console for *run_id* — a node older 686 than the feed, or a run that never started there — which a watcher 687 reads as *unwatched*. Any other failure raises: the caller decides 688 that a watcher's trouble must never fail the run it watches. 689 """ 690 # ⚠️ A short timeout of its own, as ``smoke_progress``: read once a 691 # second beside a run that may be hours long. 692 resp = self.request( 693 "GET", f"/harness/runs/{run_id}/log", params={"after": after}, timeout=10 694 ) 695 if resp.status_code == 404: 696 return None 697 resp.raise_for_status() 698 return _parsed(NodeAgentLog, resp) 699 700 def harness_result(self, run_id: str) -> HarnessRunResult | None: 701 """What the node knows of a run's harness call (#3021). 702 703 ``None`` when the node has no such route — a node older than the 704 result store, which can never return a run's outcome after its call 705 is gone. ``state="unknown"`` is the node answering that it holds 706 nothing for *run_id*. Any other failure raises: an unreachable node 707 is neither of those, and the caller bounds how long it waits on one. 708 """ 709 resp = self.request("GET", f"/harness/runs/{run_id}/result", timeout=30) 710 if resp.status_code == 404: 711 return None 712 resp.raise_for_status() 713 return _parsed(HarnessRunResult, resp) 714 715 def put_generated_range(self, push: NodeRangePush) -> NodeRangeResult: 716 """Ask the node to build a generated range from its scenario. 717 718 ⚠️ **The scenario travels, not the estate.** The corpus is 719 mounted on the node and the compiler ships inside it, so 70-odd 720 rendered files never cross this API — and the corpus commit that 721 rides along is what stops one scenario becoming two different 722 estates under one id across a fleet. 723 724 The node answers **200 with ``ok: false``** for a refusal, so a 725 node that declined and a node that could not be reached stay 726 different facts; only the second raises here. 727 """ 728 resp = self.request("POST", "/admin/ranges", json=push.model_dump(mode="json")) 729 resp.raise_for_status() 730 return _parsed(NodeRangeResult, resp) 731 732 def verify_generated_range( 733 self, push: NodeRangeVerifyPush, *, timeout: int | None = None 734 ) -> NodeRangeVerifyResult: 735 """Ask the node to build a scenario, solve it, and take it down. 736 737 ⚠️ **The longest call in this API**, so the caller passes its own 738 timeout: the node's budget is ``compose_timeout_s + 739 solve_timeout_s`` and a client that used the default would give 740 up while the node was still building — then retry, and start a 741 second estate beside the first. 742 743 ⚠️ A client timeout does **not** leave a range running: the node 744 tears down in its own ``finally``. What is lost is the answer, 745 not the host. 746 747 The node answers **200 with an ``error``** for a refusal, the 748 same split ``put_generated_range`` uses; only an unreachable node 749 raises. 750 """ 751 kwargs: dict[str, Any] = {"json": push.model_dump(mode="json")} 752 if timeout is not None: 753 # httpx takes a per-request override; the client-wide value 754 # stays whatever the caller constructed this with. 755 kwargs["timeout"] = timeout 756 resp = self.request("POST", "/admin/ranges/verify", retry_on=RETRY_UNSENT, **kwargs) 757 resp.raise_for_status() 758 return _parsed(NodeRangeVerifyResult, resp) 759 760 def cancel_generated_range_verify(self, run_id: str) -> bool: 761 """Tell the node to stop a verification it is running. 762 763 ⚠️ **A miss is success, not a 404 to report.** The cancel races 764 the run's own finish, so "no such run" means the run already 765 ended — which is what the operator asked for. The node answers 766 ``{"cancelled": false}`` for that case rather than raising, and 767 this returns it so a caller that wants to say "it had already 768 finished" can. 769 """ 770 resp = self.request("POST", f"/admin/ranges/verify/{run_id}/cancel") 771 resp.raise_for_status() 772 body = resp.json() 773 return bool(body.get("cancelled")) 774 775 def rescan_challenges(self) -> ChallengeReloadResult: 776 """Tell the node to drop its spec cache and re-scan challenges_dir. 777 778 Returns ``{total, added, removed}`` so the platform can report 779 the per-node outcome of a cluster-wide rescan.""" 780 resp = self.request("POST", "/admin/rescan-challenges") 781 resp.raise_for_status() 782 return _parsed(ChallengeReloadResult, resp) 783 784 # -- admin pre-build (image cache warming) ------------------------------ 785 786 def build_challenge( 787 self, 788 challenge_id: str, 789 *, 790 authored_revision: str = "", 791 resource_budget: ResourceBudget | None = None, 792 ) -> ChallengeBuildState: 793 """Ask the node to pre-build images for *challenge_id*. 794 795 Fires-and-returns: the node persists ``status="building"`` and 796 spawns a daemon thread; the body returned here is that initial 797 state row. Polling :meth:`get_build_state` is how the platform 798 learns when it lands on ``built`` / ``failed``. *authored_revision* 799 is #1835's: the tree the build must be of, fetched if not held. 800 """ 801 params = {"authored_revision": authored_revision} if authored_revision else None 802 # #2504: an authored tree pre-builds under this budget, or not at all. 803 kwargs: dict[str, Any] = {} 804 if resource_budget is not None: 805 kwargs["json"] = {"resource_budget": resource_budget.model_dump()} 806 resp = self.request( 807 "POST", f"/admin/challenges/{challenge_id}/build", params=params, **kwargs 808 ) 809 _raise_for_node_status(resp) 810 return _parsed(ChallengeBuildState, resp) 811 812 def build_all_challenges( 813 self, 814 challenge_ids: list[str] | None = None, 815 *, 816 resource_budget: ResourceBudget | None = None, 817 ) -> BuildAllQueued: 818 """Queue background pre-build on the node. 819 820 With ``challenge_ids=None`` the node builds every spec it knows. 821 With an explicit list (the platform scoping a bulk build to a 822 competition's challenge set) only those are built. Returns 823 ``{queued, skipped_built, skipped_in_progress}`` so the platform 824 can report per-node what got picked up. Sequential on the node 825 side — no fan-out across the corpus. 826 """ 827 kwargs: dict[str, Any] = {} 828 body: dict[str, Any] = {} 829 if challenge_ids is not None: 830 body["challenge_ids"] = challenge_ids 831 if resource_budget is not None: 832 # #2504: what an authored id in the scope pre-builds under. 833 body["resource_budget"] = resource_budget.model_dump() 834 if body: 835 kwargs["json"] = body 836 resp = self.request("POST", "/admin/challenges/build-all", **kwargs) 837 _raise_for_node_status(resp) 838 return _parsed(BuildAllQueued, resp) 839 840 def build_push_challenge( 841 self, 842 challenge_id: str, 843 *, 844 push_ticket: str = "", 845 deadline_s: int = 0, 846 cleanup: bool = False, 847 cache_max_bytes: int = 0, 848 confine_network: bool = False, 849 authored_revision: str = "", 850 run_id: str = "", 851 resource_budget: ResourceBudget | None = None, 852 ) -> ChallengeFreezeResult: 853 """Build one challenge's ``build:`` services and freeze them to the registry. 854 855 Layer 2 producer (P0). **Blocks** until the challenge is built + 856 pushed (or skipped as already frozen), unlike the fire-and-return 857 :meth:`build_challenge`. ⚠️ *deadline_s* bounds the node's whole 858 freeze (#3167, `ctfy.core.freeze_budget`; ``0`` sends the node's own 859 default), and the HTTP wait is derived from it — 860 `freeze_client_wait_s`, past the node's own answer — so the client 861 never abandons a freeze the node is still running. Sent once: a 862 ``ReadTimeout`` is a request the node has (#3162). Returns the per-service freeze result; 863 the platform's ``challenge_build_push`` task calls this one 864 challenge at a time. *push_ticket* is the platform's short-lived 865 registry credential the node's ``docker push`` authenticates with 866 — the node runs it in a container with no ambient login. 867 *cleanup* asks the node to remove what the build left and prune its 868 build cache to *cache_max_bytes* afterwards, and *confine_network* 869 keeps every ``RUN`` off the host's network (both the freeze pool, #1827). 870 *run_id* names this call for :meth:`cancel_build_push` and 871 :meth:`build_push_progress` while it is in flight (#1949). 872 """ 873 resp = self.request( 874 "POST", 875 f"/admin/challenges/{challenge_id}/build-push", 876 json={ 877 "push_ticket": push_ticket, 878 "cleanup": cleanup, 879 "cache_max_bytes": cache_max_bytes, 880 "confine_network": confine_network, 881 "authored_revision": authored_revision, 882 "run_id": run_id, 883 "deadline_s": deadline_s, 884 # #2504: the build limits an authored tree is frozen under; 885 # a node refuses one that arrives without them. 886 "resource_budget": ( 887 resource_budget.model_dump() if resource_budget is not None else None 888 ), 889 }, 890 timeout=freeze_client_wait_s(deadline_s or freeze_deadline_s()), 891 retry_on=RETRY_UNSENT, 892 ) 893 _raise_for_node_status(resp) 894 return _parsed(ChallengeFreezeResult, resp) 895 896 def cancel_build_push(self, run_id: str) -> BuildPushCancelled: 897 """Cancel the freeze :meth:`build_push_challenge` started under *run_id* (#1949). 898 899 Idempotent; ``found`` false means the node holds no such run. 900 """ 901 resp = self.request("POST", "/admin/build-push/cancel", json={"run_id": run_id}) 902 _raise_for_node_status(resp) 903 return _parsed(BuildPushCancelled, resp) 904 905 def build_push_progress(self, run_id: str) -> BuildPushProgress: 906 """What the freeze running under *run_id* is doing now (#1949).""" 907 resp = self.request("GET", f"/admin/build-push/{run_id}/progress") 908 _raise_for_node_status(resp) 909 return _parsed(BuildPushProgress, resp) 910 911 def get_disk_free(self) -> NodeDiskFree: 912 """Free space on the node's data filesystem, read now (#1827). 913 914 Raises on any failure — including a node predating the route, which 915 answers 404 — and the freeze reads every failure as *cannot tell*, 916 which stops it. 917 """ 918 resp = self.request("GET", "/admin/disk") 919 _raise_for_node_status(resp) 920 return _parsed(NodeDiskFree, resp) 921 922 def get_build_state(self) -> BuildStateRows: 923 """Fetch every per-challenge build-state row on this node. 924 925 Returns ``{"rows": [{challenge_id, status, built_at, error}, …]}``. 926 ``status`` is one of ``unbuilt`` / ``building`` / ``built`` / 927 ``failed``; ``unbuilt`` placeholders are synthesised for specs 928 the node has seen but never been asked to build. 929 """ 930 resp = self.request("GET", "/admin/challenges/build-state") 931 _raise_for_node_status(resp) 932 return _parsed(BuildStateRows, resp) 933 934 def pull_challenge(self, challenge_id: str) -> ChallengePullState: 935 """Ask the node to pre-pull registry images for *challenge_id*. 936 937 Pull-side twin of :meth:`build_challenge`: the node persists 938 ``status="pulling"`` and spawns a daemon thread; poll 939 :meth:`get_pull_state` for the ``pulled`` / ``failed`` landing. 940 """ 941 resp = self.request("POST", f"/admin/challenges/{challenge_id}/pull") 942 _raise_for_node_status(resp) 943 return _parsed(ChallengePullState, resp) 944 945 def pull_all_challenges(self, challenge_ids: list[str] | None = None) -> PullAllQueued: 946 """Queue background pre-pull on the node. 947 948 With ``challenge_ids=None`` the node pulls every spec it knows; 949 with an explicit list only those (the platform scoping to a 950 competition). Returns ``{queued, skipped_pulled, 951 skipped_in_progress}``. 952 """ 953 kwargs: dict[str, Any] = {} 954 if challenge_ids is not None: 955 kwargs["json"] = {"challenge_ids": challenge_ids} 956 resp = self.request("POST", "/admin/challenges/pull-all", **kwargs) 957 _raise_for_node_status(resp) 958 return _parsed(PullAllQueued, resp) 959 960 def get_pull_state(self) -> PullStateRows: 961 """Fetch every per-challenge pull-state row on this node. 962 963 Returns ``{"rows": [{challenge_id, status, pulled_at, error}, …]}``. 964 ``status`` is one of ``unpulled`` / ``pulling`` / ``pulled`` / 965 ``failed``; ``unpulled`` placeholders are synthesised for specs 966 the node has seen but never been asked to pull. 967 """ 968 resp = self.request("GET", "/admin/challenges/pull-state") 969 _raise_for_node_status(resp) 970 return _parsed(PullStateRows, resp) 971 972 # -- status / health ---------------------------------------------------- 973 974 def get_status(self, instance_id: str) -> InstanceStatusReport: 975 resp = self.request("GET", f"/instances/{instance_id}/status") 976 resp.raise_for_status() 977 return _parsed(InstanceStatusReport, resp) 978 979 def list_instances(self) -> list[NodeInstanceSummary]: 980 """Every instance the node still has bookkeeping for. 981 982 Used by the platform's boot re-adoption pass to decide which 983 durable claims still have containers behind them. ``get_status`` 984 answers the same question one id at a time; asking it per claim 985 would cost one round trip per instance to a node that may be 986 slow or down, on the path that gates startup. 987 """ 988 resp = self.request("GET", "/instances") 989 resp.raise_for_status() 990 return _parsed(NodeInstanceList, resp).items 991 992 def check_health(self, instance_id: str) -> bool: 993 return self.check_health_verbose(instance_id).healthy 994 995 def check_health_verbose(self, instance_id: str) -> HealthReading: 996 """Health plus whatever agent-deception telemetry the node read. 997 998 One call, because the platform already polls this endpoint for 999 every live instance every tick and a second round trip per 1000 instance would be the whole cost of the feature. ``check_health`` 1001 stays a bool for the callers that only ever wanted one. 1002 1003 Never an error, whatever arrives: this rides the health poll, 1004 and telemetry must not be able to mark a healthy instance 1005 unhealthy. 1006 1007 ⚠️ **The two ways this can come back empty are different facts 1008 and used to be one.** An older node sends no ``deception`` key 1009 at all — it *did not say*, which is ``channel=None`` and 1010 authorises nothing. A body this platform cannot parse is 1011 something else: the node did say, and we could not read it. That 1012 is ``unreadable``, the same value the reader gives for a missing 1013 file, because it is the same fact — there is no usable channel 1014 here — arriving through a different door. 1015 1016 The parse failure that matters is version skew in the other 1017 direction: a **newer** node reporting an ``ObservationKind`` this 1018 platform does not have. ``Observation.kind`` is typed, so one 1019 unknown member fails the whole model rather than dropping one 1020 row — which is the right refusal (the node's word is not ours to 1021 edit) and exactly why it must not land as "reported nothing". 1022 """ 1023 resp = self.request("GET", f"/instances/{instance_id}/health") 1024 resp.raise_for_status() 1025 body = resp.json() 1026 raw = body.get("deception") 1027 if not raw: 1028 summary = DeceptionSummary() 1029 else: 1030 try: 1031 summary = DeceptionSummary.model_validate(raw) 1032 except ValidationError as exc: 1033 log.info( 1034 "unreadable deception telemetry from node", 1035 instance_id=instance_id, 1036 error=tail(str(exc), limit=200), 1037 ) 1038 summary = DeceptionSummary(channel="unreadable") 1039 raw_contact = body.get("contact") 1040 if not raw_contact: 1041 contact = ContactReading() 1042 else: 1043 try: 1044 contact = ContactReading.model_validate(raw_contact) 1045 except ValidationError as exc: 1046 log.info( 1047 "unreadable contact telemetry from node", 1048 instance_id=instance_id, 1049 error=tail(str(exc), limit=200), 1050 ) 1051 contact = ContactReading(channel="unreadable") 1052 raw_procs = body.get("new_processes") 1053 # ⚠️ Shape-checked rather than trusted: an older node sends 1054 # nothing and a newer one could send a shape this platform does 1055 # not model, and neither may reach a reader as *a container full 1056 # of intruders*. Anything unreadable is silence, which for a 1057 # signal built to under-report is the honest reading. 1058 procs: dict[str, list[str]] = {} 1059 if isinstance(raw_procs, dict): 1060 for container, names in raw_procs.items(): 1061 if isinstance(container, str) and isinstance(names, list): 1062 procs[container] = [str(n) for n in names] 1063 return HealthReading( 1064 healthy=bool(body.get("is_healthy")), 1065 deception=summary, 1066 contact=contact, 1067 new_processes=procs, 1068 ) 1069 1070 def node_health(self) -> dict[str, Any]: 1071 """Liveness + ``{running, capacity}`` for heartbeat.""" 1072 resp = self.request("GET", "/health") 1073 resp.raise_for_status() 1074 body: dict[str, Any] = resp.json() 1075 return body 1076 1077 # -- traffic / runtime -------------------------------------------------- 1078 1079 def get_traffic_page( 1080 self, instance_id: str, *, cursor: str = "", limit: int = 0 1081 ) -> InstanceTrafficPage: 1082 """One page of mitmproxy flows; the capture lives on the node's FS. 1083 1084 ⚠️ **The one method that must not use ``_parsed``.** A node from 1085 before paging answers with a bare *list* — it sent the whole 1086 capture and understands no cursor — and a strict 1087 ``model_validate`` turns that supported skew into a raised 1088 request. So the body goes through ``coerce_page``, which already 1089 owns every decision about an unexpected shape, and the caller 1090 gets the model. 1091 1092 This is the same move ``coerce_page`` was written for, one layer 1093 down. Its docstring used to say the parsing belonged 1094 "platform-side … so a route and this client cannot come to 1095 disagree" — and there were *three* platform-side calls doing it. 1096 There is one call now, at the seam that knows the request 1097 cursor, which is what the fallback needs; the routes hold the 1098 type instead of re-deciding its shape. 1099 1100 ⚠️ **An empty ``cursor`` means "from the beginning".** Passing 1101 one on every poll re-reads the whole capture, which is the cost 1102 the paged read exists to remove — arriving through the caller 1103 rather than through the node. 1104 """ 1105 params: dict[str, Any] = {} 1106 if cursor: 1107 params["cursor"] = cursor 1108 if limit > 0: 1109 params["limit"] = limit 1110 resp = self.request("GET", f"/instances/{instance_id}/traffic", params=params) 1111 resp.raise_for_status() 1112 page = coerce_page(resp.json(), cursor) 1113 return InstanceTrafficPage( 1114 flows=page.flows, 1115 cursor=page.cursor, 1116 truncated=page.truncated, 1117 capture=page.capture, 1118 ) 1119 1120 def get_traffic_witnesses( 1121 self, instance_id: str, *, cursor: str = "", limit: int = 0 1122 ) -> InstanceTrafficWitnesses: 1123 """Who spoke to this box since *cursor*, with no bodies moved. 1124 1125 §7.1's correlation reads one gamebox per team per round. Through 1126 :meth:`get_traffic_page` that is every flow, both bodies 1127 included (~100 kB apiece by ``CLAUDE.md``'s measurement), 1128 pulled across the wire to extract a handful of addresses; the 1129 node reduces instead and this carries the result. 1130 1131 ⚠️ **Strict parsing here, unlike its neighbour, and that is the 1132 difference between an old field and an old route.** 1133 ``get_traffic_page`` is lenient because a node from before 1134 paging answers the *same* path with a bare list, which is 1135 supported skew. This route did not exist on such a node at all, 1136 so the honest answer from one is a 404 — and a lenient parse of 1137 an error body would hand the round loop an empty witness set, 1138 which reads as *nobody was there*. The caller catches the 1139 request error and records the round as unknown. 1140 """ 1141 params: dict[str, Any] = {} 1142 if cursor: 1143 params["cursor"] = cursor 1144 if limit > 0: 1145 params["limit"] = limit 1146 resp = self.request("GET", f"/instances/{instance_id}/traffic-witnesses", params=params) 1147 resp.raise_for_status() 1148 return _parsed(InstanceTrafficWitnesses, resp) 1149 1150 def list_containers(self, instance_id: str) -> list[ComposeContainer]: 1151 """Enumerate every container in an instance's compose project. 1152 1153 Backs the admin-shell feature: the platform forwards a 1154 ``GET /admin/instances/{id}/containers`` to the assigned node, 1155 which returns one row per container (challenge services and 1156 platform-injected sidecars alike). The WebSocket reverse-proxy 1157 is opened separately and does not go through ``NodeClient``. 1158 """ 1159 resp = self.request("GET", f"/instances/{instance_id}/containers") 1160 _raise_for_node_status(resp) 1161 return _parsed_list(ComposeContainer, resp) 1162 1163 def run_checker( 1164 self, 1165 instance_id: str, 1166 *, 1167 service: str, 1168 cmd: list[str], 1169 timeout_s: int = DEFAULT_JUDGE_TIMEOUT_S, 1170 ) -> CheckResult: 1171 """Exec an author-supplied checker in a trusted judge sidecar. 1172 1173 Backs the checker / exec-judge feature: the platform forwards a 1174 verify request to the assigned node, which runs ``cmd`` inside the 1175 named sidecar and returns 1176 ``{exit_code, stdout, stderr, timed_out, error}``. 1177 1178 ⚠️ *timeout_s* is the author's, and the node clamps it (#3169): the 1179 clamped budget is what is sent and what the wait is derived from 1180 (`core.judge_budget.platform_wait_s`), so ``0`` no longer waits 10 s 1181 on a node running 30, and ``600`` no longer holds a threadpool slot 1182 for 610 s on a node that stops at 120. Sent once (``RETRY_UNSENT``). 1183 """ 1184 exec_s = judge_exec_s(timeout_s) 1185 resp = self.request( 1186 "POST", 1187 f"/instances/{instance_id}/check", 1188 json={"service": service, "cmd": cmd, "timeout_s": exec_s}, 1189 timeout=judge_platform_wait_s(exec_s), 1190 retry_on=RETRY_UNSENT, 1191 ) 1192 _raise_for_node_status(resp) 1193 return _parsed(CheckResult, resp) 1194 1195 def run_harness( 1196 self, 1197 *, 1198 image: str, 1199 run_id: str = "", 1200 env: dict[str, str], 1201 timeout_s: int = 1800, 1202 untrusted: bool = False, 1203 network: str = "", 1204 own_network: bool = False, 1205 match_network: str = "", 1206 match_address: str = "", 1207 brief: dict[str, Any] | None = None, 1208 target_instance: str = "", 1209 target_aliases: dict[str, str] | None = None, 1210 target_access: str = "", 1211 vpn_config: str = "", 1212 estate_zones: Sequence[str] = (), 1213 target_endpoints: Sequence[str] = (), 1214 target_hosts: Mapping[str, str] | None = None, 1215 target_datagram_endpoints: Sequence[str] = (), 1216 pull_ticket: str = "", 1217 registry_auth: HarnessRegistryAuth | None = None, 1218 limits: HarnessLimits | None = None, 1219 admission_profile: bool = False, 1220 egress_allow: list[str] | None = None, 1221 internet: bool = True, 1222 rootfs_budget_bytes: int = 0, 1223 unpack_budget_bytes: int = 0, 1224 disk_low_watermark_bytes: int = 0, 1225 ingress: bool = True, 1226 local_ingress: bool = False, 1227 platform_image: bool = False, 1228 image_policy: HarnessImagePolicy | None, 1229 attachments: dict[str, str] | None = None, 1230 keep_work: bool = False, 1231 resume_work: bool = False, 1232 exploit: dict[str, Any] | None = None, 1233 exploit_archive: Path | None = None, 1234 exploit_body: ExploitBody = "", 1235 ) -> HarnessRun: 1236 """Run a one-shot evaluation-harness container on the node. 1237 1238 ``exploit`` (#2819 W2) runs a smoke's reference exploit in the fence 1239 instead of an agent (``HarnessExploit``'s fields); sent only when set. 1240 ``exploit_archive`` is its packed tree on disk (#3628), streamed into 1241 the body (:func:`harness_run_content`) as the node's 1242 ``capabilities().exploit_body`` — passed as *exploit_body* — reads it. 1243 1244 ``image_policy`` (#2608) is **required, with no default**: every 1245 caller says whether this image is a user's (the registry rules the 1246 node re-checks before pulling) or the platform's own (``None``). An 1247 untrusted run without one is refused by the node. 1248 1249 The node ``docker run``s ``image`` with ``env`` injected, waits for it 1250 to exit (bounded by ``timeout_s``), and returns 1251 ``{exit_code, stdout, stderr, timed_out, error}`` — the same shape as 1252 :meth:`run_checker`. The harness writes its JSON rollup to stdout. The 1253 per-call HTTP timeout sits above the node's run budget so the client 1254 doesn't abandon the request before the (long-running) harness returns. 1255 1256 ``untrusted`` runs the image under the node's isolation profile — 1257 off host networking, bounded resources, no capabilities — for an 1258 image the platform did not build. It requires a network: the 1259 node answers 400 without one, because "isolate this" and "I will 1260 not say where the target lives" do not compose. 1261 1262 Any of ``network`` (the target instance's own, when the caller 1263 knows it), ``own_network`` or ``target_instance`` satisfies that. 1264 ⚠️ Most eval dispatches need the second: there the harness 1265 *starts* the target partway through its own run, so at ``docker 1266 run`` time no target network exists and there is no name to 1267 send. The node creates a fresh bridge and removes it afterwards. 1268 1269 ``target_instance`` reverses that ordering, and is what an 1270 `engagement` uses: the platform starts the estate first and names 1271 it here, and the node wires its published containers to the 1272 agent's bridge. ⚠️ An **id**, never a network name — the name is 1273 a fact only the node's daemon can read, and ``docker run`` 1274 *creates* whatever string it is handed, so a platform guessing 1275 one starts a run that reaches nothing. 1276 """ 1277 body: dict[str, Any] = { 1278 "image": image, 1279 "env": env, 1280 "timeout_s": timeout_s, 1281 "untrusted": untrusted, 1282 "network": network, 1283 "own_network": own_network, 1284 "match_network": match_network, 1285 # ⚠️ **The platform-assigned arena address.** The node 1286 # connects the agent to the match network with this 1287 # ``--ip``, so the address is known before the round loop 1288 # asks (§7.1). Empty means "let docker's IPAM pick" — an 1289 # older platform's behaviour, and what keeps a node reading 1290 # this field unchanged for every non-arena dispatch. 1291 "match_address": match_address, 1292 # ⚠️ Sent even when empty, so a node reading it gets the 1293 # same shape either way; the node's default is what makes 1294 # an older platform's dispatch unchanged. 1295 "pull_ticket": pull_ticket, 1296 # #3475: the owner's registry login, sent **only when set**, 1297 # so a node that predates the field sees the body it always did. 1298 **({"registry_auth": registry_auth.model_dump()} if registry_auth is not None else {}), 1299 # ⚠️ ``None`` leaves the node's own defaults in force, which is 1300 # what a dispatch said before the ceilings were settings. 1301 "limits": limits.model_dump() if limits is not None else None, 1302 # ⚠️ Same rule, and empty is a real answer here too: a 1303 # dispatch with no run row (the conformance probe, a dry 1304 # run) has nothing to label, and a label with an empty 1305 # value would make every one of them answer one query. 1306 "run_id": run_id, 1307 # ⚠️ Sent as the already-built manifest. The platform is 1308 # the side that knows the challenge, the competition and 1309 # the run mode; a node deriving its own would be a 1310 # second implementation of a published contract. 1311 "brief": brief, 1312 "target_instance": target_instance, 1313 # ⚠️ **The names the brief published, so they resolve on 1314 # the agent's bridge too.** An estate's hosts answer to a 1315 # per-instance FQDN minted by its own resolver; joined to 1316 # a new network a container answers only to its compose 1317 # *service* name. Sending the mapping is what keeps the 1318 # address the agent was told about true under either 1319 # placement — without it the agent is handed a hostname 1320 # that does not resolve, reaches nothing, and reports an 1321 # empty result, which reads as a model that gave up. 1322 # 1323 # ⚠️ The platform's to send: it computed the surface. A 1324 # node re-deriving it from the rendered compose would be 1325 # a second implementation of the address the brief has 1326 # already promised. 1327 "target_aliases": target_aliases or {}, 1328 # #2550: ``{name: base64}`` for ``/ctfy/work/attachments/``. 1329 # ⚠️ Sent only when there are some, so every other dispatch 1330 # is byte-identical to before. 1331 **({"attachments": attachments} if attachments else {}), 1332 # #2550 restarts: sent only when asked for, like the files. 1333 **({"keep_work": True} if keep_work else {}), 1334 **({"resume_work": True} if resume_work else {}), 1335 # #2861 slice B: the target access the platform read off the 1336 # target's node. ⚠️ Sent only when there is one, so every 1337 # other dispatch is byte-identical to before; and only to a 1338 # node whose ``capabilities().harness_access`` said it reads 1339 # them, or to the target's own node (where an older node's 1340 # local read is still right). 1341 **( 1342 { 1343 "target_access": target_access, 1344 "vpn_config": vpn_config, 1345 "estate_zones": list(estate_zones), 1346 "target_endpoints": list(target_endpoints), 1347 } 1348 if target_access 1349 else {} 1350 ), 1351 # #3020: names → the target node's ingress address, for a 1352 # published target handed over the agent-ingress tunnel. Sent 1353 # only when there are some, and only to a node whose 1354 # ``capabilities().harness_ingress_access`` said it reads them. 1355 **({"target_hosts": dict(target_hosts)} if target_hosts else {}), 1356 # #3446: the published endpoints that are UDP, which the node 1357 # never TCP-probes. Sent only when there are some. 1358 **( 1359 {"target_datagram_endpoints": list(target_datagram_endpoints)} 1360 if target_datagram_endpoints 1361 else {} 1362 ), 1363 # #2356: ⚠️ sent only when asked for, so a dispatch that does 1364 # not ask is byte-identical to an older platform's — and an 1365 # older node, which would ignore the fields, is never sent 1366 # them: the caller checks ``capabilities().harness_admission``. 1367 **( 1368 { 1369 "admission_profile": True, 1370 "egress_allow": list(egress_allow or []), 1371 "internet": internet, 1372 "rootfs_budget_bytes": rootfs_budget_bytes, 1373 "unpack_budget_bytes": unpack_budget_bytes, 1374 "disk_low_watermark_bytes": disk_low_watermark_bytes, 1375 "ingress": ingress, 1376 # #2819 W1, F2: sent only when asked for. 1377 **({"local_ingress": True} if local_ingress else {}), 1378 } 1379 if admission_profile 1380 else {} 1381 ), 1382 "image_policy": image_policy.model_dump() if image_policy is not None else None, 1383 # #2608 N4: only for a row with no owner; see the node's request. 1384 **({"platform_image": True} if platform_image else {}), 1385 **({"exploit": exploit} if exploit is not None else {}), 1386 } 1387 resp = self.request( 1388 "POST", 1389 "/harness/run", 1390 **( 1391 {"json": body} 1392 if exploit_archive is None 1393 else harness_run_content(body, exploit_archive, exploit_body=exploit_body) 1394 ), 1395 timeout=( 1396 timeout_s 1397 # #2819 W2: the exploit's `solution/Dockerfile` builds first. 1398 + (SOLUTION_BUILD_TIMEOUT_S if exploit is not None else 0) 1399 + IMAGE_PULL_TIMEOUT_S 1400 + HARNESS_IMAGE_INSPECT_TIMEOUT_S 1401 + HARNESS_CREATE_TIMEOUT_S 1402 + 30 1403 ), 1404 retry_on=RETRY_UNSENT, 1405 ) 1406 _raise_for_node_status(resp) 1407 return _parsed(HarnessRun, resp) 1408 1409 def cancel_harness(self, *, run_id: str) -> int: 1410 """Stop whatever this node is running for ``run_id``; returns how many. 1411 1412 Until this existed a dispatched container was reclaimed by 1413 **nothing but its own timeout** — ``_harness_timeout``'s docstring 1414 says exactly that — so an operator pressing cancel on a 1415 match-long run was asking for something the platform had no way 1416 to deliver. 1417 1418 ⚠️ **Zero is an ordinary answer, not a failure.** The run may have 1419 finished on its own, been dispatched to a different node, or been 1420 lost to a node restart. A caller that read zero as an error would 1421 report a broken platform every time a cancel arrived a second 1422 late. 1423 """ 1424 resp = self.request("POST", "/harness/cancel", json={"run_id": run_id}) 1425 body = resp.json() 1426 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0 1427 1428 def verify_patch( 1429 self, challenge_id: str, files: dict[str, bytes], *, deadline_s: int 1430 ) -> PatchVerifyResult: 1431 """Build a submitted patch on the node and return its verdict. 1432 1433 ``files`` maps a challenge-relative path to its new bytes; base64 1434 is applied here because a patch target may legitimately be 1435 binary. Returns ``{verdict, detail, applied, steps, error}``. 1436 1437 **An empty ``verdict`` with a populated ``error`` is not a 1438 judgement** — it means the node refused the submission, the 1439 verifier crashed, or the run's deadline ran out. The caller must 1440 retry or retire the lease rather than write a score, since failing 1441 to judge a patch is not the same as judging it unfixed. 1442 1443 ⚠️ *deadline_s* bounds the node's whole run (#3164, 1444 `ctfy.core.patch_budget`), and the HTTP wait is derived from it — 1445 `patch_client_wait_s`, past the node's own answer — so the client 1446 never abandons a request the node is still working on. Sent once: 1447 a ``ReadTimeout`` is a request the node has (#3162). 1448 """ 1449 resp = self.request( 1450 "POST", 1451 "/patches/verify", 1452 json={ 1453 "challenge_id": challenge_id, 1454 "files": { 1455 path: base64.b64encode(content).decode() for path, content in files.items() 1456 }, 1457 "deadline_s": deadline_s, 1458 }, 1459 timeout=patch_client_wait_s(deadline_s), 1460 retry_on=RETRY_UNSENT, 1461 ) 1462 _raise_for_node_status(resp) 1463 return _parsed(PatchVerifyResult, resp) 1464 1465 def collect_patch_files( 1466 self, instance_id: str, service: str, paths: list[str] 1467 ) -> dict[str, bytes]: 1468 """Read a player's SSH edits back out of their running box. 1469 1470 ``paths`` are absolute in-container paths the *platform* derived 1471 from the pristine source tree. Returns only what could be read: 1472 a path missing from the reply means the player did not change it, 1473 and the caller falls back to the shipped file rather than 1474 recording a deletion they never made. 1475 """ 1476 resp = self.request( 1477 "POST", 1478 f"/instances/{instance_id}/patch-collect", 1479 json={"service": service, "paths": paths}, 1480 ) 1481 _raise_for_node_status(resp) 1482 body: dict[str, str] = resp.json() 1483 return {path: base64.b64decode(blob) for path, blob in body.items()} 1484 1485 def write_awd_answers(self, boxes: dict[str, dict[str, str]]) -> dict[str, str]: 1486 """Rotate a round's flags into every box of this node, in one call. 1487 1488 ⚠️ **One call for the whole node, never one per box.** §5.2's 1489 capacity red line is 1000 teams x 3 services injected inside 1490 120 s; per-box that is 3000 round trips, batched it is about 1491 fourteen. The signature is the enforcement — a caller cannot 1492 accidentally loop. 1493 1494 Returns ``{instance_id: ""}`` for the boxes written and a reason 1495 for the ones that were not, because one team's unreachable box 1496 must not cost every other team on the node its rotation. An 1497 unrotated box keeps serving last round's flag, which anyone 1498 holding the old value can replay. 1499 """ 1500 resp = self.request("POST", "/awd/answers", json={"boxes": boxes}) 1501 _raise_for_node_status(resp) 1502 result: dict[str, str] = resp.json() 1503 return result 1504 1505 def probe_awd_service( 1506 self, 1507 *, 1508 instance_id: str, 1509 service_id: str, 1510 tick: int, 1511 flag: str, 1512 previous_flag: str = "", 1513 previous_flag_id: str = "", 1514 ) -> dict[str, str]: 1515 """Run one round's SLA probes against one box, from outside it. 1516 1517 The flags travel *to* the node: a checker that sourced its 1518 expected value from the box it is checking would pass on any box 1519 that returns whatever it was handed. 1520 """ 1521 resp = self.request( 1522 "POST", 1523 "/awd/probe", 1524 json={ 1525 "instance_id": instance_id, 1526 "service_id": service_id, 1527 "tick": tick, 1528 "flag": flag, 1529 "previous_flag": previous_flag, 1530 "previous_flag_id": previous_flag_id, 1531 }, 1532 ) 1533 _raise_for_node_status(resp) 1534 result: dict[str, str] = resp.json() 1535 return result 1536 1537 def attack_awd_box( 1538 self, 1539 *, 1540 instance_id: str, 1541 tick: int, 1542 timeout_s: int = 60, 1543 agent_image: str = "", 1544 counter_flag: str = "", 1545 forensic_marker: str = "", 1546 llm_api_key: str = "", 1547 ) -> AwdAttackResult: 1548 """Run this box's own reference exploit against it, once. 1549 1550 Per **box**, not per service: one `run_exploit` discovers every 1551 answer the challenge declares and prints them all. 1552 1553 ``timeout_s`` is sent because the platform is what knows how long 1554 a round is; the node clamps it, because a container held open for 1555 an hour is the node's problem whoever asked for it. 1556 1557 ``forensic_marker`` is §4.3.1's, carried only by the agent 1558 branch: `build_attack_argv` passes no environment at all, so a 1559 marker on the reference exploit would be the one value that 1560 voids `EXPLOIT007`'s guarantee. 1561 1562 ``agent_image`` + ``counter_flag`` switch the node to §4.2b's 1563 agent attacker. ⚠️ **Both or neither** — the node refuses a half 1564 request rather than falling back to the reference exploit, which 1565 would run a different format than the one configured while the 1566 board looked entirely normal. 1567 """ 1568 resp = self.request( 1569 "POST", 1570 "/awd/attack", 1571 json={ 1572 "instance_id": instance_id, 1573 "tick": tick, 1574 "timeout_s": timeout_s, 1575 "agent_image": agent_image, 1576 "counter_flag": counter_flag, 1577 "forensic_marker": forensic_marker, 1578 "llm_api_key": llm_api_key, 1579 }, 1580 ) 1581 _raise_for_node_status(resp) 1582 return _parsed(AwdAttackResult, resp) 1583 1584 def get_container_logs(self, instance_id: str) -> str: 1585 """Fetch combined container stdout/stderr for archival.""" 1586 resp = self.request("GET", f"/instances/{instance_id}/container-logs") 1587 resp.raise_for_status() 1588 return str(resp.json().get("logs") or "") 1589 1590 def get_pcap(self, instance_id: str) -> PcapCapture: 1591 """Fetch the merged tcpdump capture for *instance_id*. 1592 1593 ``data`` is empty when no capture exists (sidecar disabled, 1594 instance never reached the running state, etc.) so callers can 1595 persist conditionally without try/except. 1596 1597 ⚠️ **It also says what the per-instance cap already dropped** 1598 (#1714), off the node's response headers, and ``None`` when the 1599 node did not say — an older node, which is *not reported*, never 1600 a clean capture. 1601 """ 1602 resp = self.request("GET", f"/instances/{instance_id}/pcap") 1603 if resp.status_code == 404: 1604 return PcapCapture(data=b"") 1605 resp.raise_for_status() 1606 return PcapCapture( 1607 data=resp.content, 1608 dropped_bytes=_header_int(resp, CAPTURE_DROPPED_BYTES_HEADER), 1609 dropped_segments=_header_int(resp, CAPTURE_DROPPED_SEGMENTS_HEADER), 1610 ) 1611 1612 def get_harness_artifact(self, artifact_id: str) -> bytes: 1613 """One finished run's collected archive, or ``b""``. 1614 1615 ⚠️ **Empty rather than an exception for a 404**, following 1616 :meth:`get_pcap`. The node reaps uncollected archives, and a 1617 platform that comes back after a restart is exactly the caller 1618 that meets one that is gone — a state its own record already 1619 describes, not a transport failure. 1620 """ 1621 resp = self.request("GET", f"/harness/artifacts/{artifact_id}") 1622 if resp.status_code == 404: 1623 return b"" 1624 resp.raise_for_status() 1625 return resp.content 1626 1627 def delete_harness_artifact(self, artifact_id: str) -> bool: 1628 """Tell the node the archive has been stored and can go. 1629 1630 ⚠️ **Never raises on a transport failure**, because it is called 1631 after the bytes are safely in object storage: turning a cleanup 1632 error into the run's error would replace a success with a 1633 janitorial complaint. The node's reaper collects whatever this 1634 misses. 1635 """ 1636 try: 1637 resp = self.request("DELETE", f"/harness/artifacts/{artifact_id}") 1638 except Exception: 1639 return False 1640 return resp.status_code == 200 1641 1642 def get_agent_runtime(self, instance_id: str) -> AgentRuntime: 1643 """Provider-agnostic runtime hints for attaching an agent (proxy URL, 1644 CA PEM, optional Docker-specific names). Replaces the old 1645 sandbox-network shape.""" 1646 resp = self.request("GET", f"/instances/{instance_id}/agent-runtime") 1647 resp.raise_for_status() 1648 return _parsed(AgentRuntime, resp) 1649 1650 # -- per-instance rendered attachments --------------------------------- 1651 1652 def list_instance_attachments(self, instance_id: str) -> AttachmentList: 1653 """List per-instance attachments rendered into the node's workdir. 1654 1655 Backs the platform's per-instance attachment endpoint, which 1656 surfaces the team-specific rendered file listing. 1657 1658 ⚠️ This used to hand back the raw dict, under a docstring saying 1659 "caller projects through :class:`AttachmentList` for typing" — 1660 the node's route already declared that model, so the type existed 1661 and this method's signature was the one place it was dropped. 1662 Projecting *here* means there is one place a malformed answer is 1663 caught rather than one per caller.""" 1664 resp = self.request("GET", f"/instances/{instance_id}/attachments") 1665 resp.raise_for_status() 1666 return _parsed(AttachmentList, resp) 1667 1668 def get_vpn_config(self, instance_id: str) -> bytes: 1669 """Fetch the per-instance VPN client config from the node. 1670 1671 The node reads the backend's client config out of the 1672 instance's VPN service container (generated on first boot by 1673 the base image's bootstrap) and rewrites its endpoint to the 1674 node's public host:port. Returns the body verbatim — the 1675 platform-side route adds the ``Content-Disposition`` header 1676 before re-emitting to the player, because only it knows the 1677 backend and therefore the filename the player needs. 1678 1679 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1680 proxy route catches 404 and re-emits to the player, anything 1681 else is treated as a 502. 1682 """ 1683 resp = self.request("GET", f"/instances/{instance_id}/vpn-config") 1684 resp.raise_for_status() 1685 return resp.content 1686 1687 def get_vpn_access(self, instance_id: str) -> tuple[bytes, tuple[str, ...] | None]: 1688 """The player's VPN config plus the estate's resolver zones (#2861 B). 1689 1690 The config is :meth:`get_vpn_config`'s, byte for byte; the zones ride 1691 a response header the node adds only when asked. ``None`` for the 1692 zones is a node that did not say (older, or docker unreadable there) 1693 — never "no zones". Raises like :meth:`get_vpn_config`. 1694 """ 1695 resp = self.request( 1696 "GET", f"/instances/{instance_id}/vpn-config", params={"estate_zones": "true"} 1697 ) 1698 resp.raise_for_status() 1699 raw = resp.headers.get("X-Ctfy-Estate-Zones") 1700 return resp.content, (tuple(raw.split()) if raw is not None else None) 1701 1702 def download_instance_attachment(self, instance_id: str, filename: str) -> tuple[bytes, str]: 1703 """Download one per-instance attachment as ``(bytes, content_type)``. 1704 1705 Buffers the whole body — attachments are bounded (typical case 1706 is a 10 KB binary or a small text file). For huge captures the 1707 caller should hand the player a CDN URL instead. 1708 1709 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1710 proxy route catches 404 and re-emits to the player, anything 1711 else is a 502. Invalid names or instance keys raise 1712 ``InvalidAttachmentName`` before any request is sent.""" 1713 # The instance is a single route key, never part of the file name. 1714 if component_refusal(instance_id) is not None: 1715 raise InvalidAttachmentName("Invalid attachment instance") 1716 resp = self.request( 1717 "GET", 1718 f"/instances/{quote(instance_id, safe='')}/attachments/{attachment_url_path(filename)}", 1719 ) 1720 resp.raise_for_status() 1721 return resp.content, resp.headers.get("content-type", "application/octet-stream")
112@dataclasses.dataclass(frozen=True) 113class PcapCapture: 114 """A node's merged capture, and what the cap dropped from it (#1714).""" 115 116 data: bytes 117 #: ``None`` = the node did not say (older build); ``0`` = nothing. 118 dropped_bytes: int | None = None 119 dropped_segments: int | None = None
A node's merged capture, and what the cap dropped from it (#1714).
217class HealthReading(BaseModel): 218 """One health poll's three answers. 219 220 ⚠️ **A record rather than a tuple, and the reason is recorded one 221 subsystem over.** ``competition_results`` lost ``attempts`` and 222 ``last_solve_at`` to a hand-made ``(rank, flags, solved)`` tuple 223 sitting between a board that produced them and a template that 224 consumed them; this poll had two answers and now has three, so the 225 tuple was one field away from the same fate. Growing a record is a 226 field; growing a tuple is every call site, silently re-bound. 227 """ 228 229 healthy: bool = False 230 deception: DeceptionSummary = Field(default_factory=DeceptionSummary) 231 contact: ContactReading = Field(default_factory=ContactReading) 232 new_processes: dict[str, list[str]] = Field(default_factory=dict)
One health poll's three answers.
⚠️ A record rather than a tuple, and the reason is recorded one
subsystem over. competition_results lost attempts and
last_solve_at to a hand-made (rank, flags, solved) tuple
sitting between a board that produced them and a template that
consumed them; this poll had two answers and now has three, so the
tuple was one field away from the same fate. Growing a record is a
field; growing a tuple is every call site, silently re-bound.
235def masked_capabilities(caps: NodeCapabilities, disabled: Iterable[str]) -> NodeCapabilities: 236 """*caps* with every feature in *disabled* answered ``False`` (#3037). 237 238 The effective value is *supported by the node* AND *enabled by the 239 admin*. ⚠️ Only names that are features are masked 240 (`ctfy.core.node_features.CAPABILITY_FEATURES`), so an unknown or stale name 241 in the row turns nothing off — the switch fails open. A placement switch 242 (``public_ports``) is not a capability and is asked by placement instead. 243 """ 244 off = [f for f in CAPABILITY_FEATURES if not feature_enabled(disabled, f)] 245 if not off: 246 return caps 247 update: dict[str, object] = dict.fromkeys(off, False) 248 for flag in off: 249 reason = f"{flag}_reason" 250 if reason in NodeCapabilities.model_fields: 251 update[reason] = "switched off by an admin on this node" 252 return caps.model_copy(update=update)
caps with every feature in disabled answered False (#3037).
The effective value is supported by the node AND enabled by the
admin. ⚠️ Only names that are features are masked
(ctfy.core.node_features.CAPABILITY_FEATURES), so an unknown or stale name
in the row turns nothing off — the switch fails open. A placement switch
(public_ports) is not a capability and is asked by placement instead.
287def harness_run_content( 288 body: dict[str, Any], archive: Path, *, exploit_body: ExploitBody 289) -> dict[str, Any]: 290 """``content`` and ``headers`` for a harness run whose exploit archive is *archive*. 291 292 ⚠️ **Streamed either way (#3628)**: the archive is never read whole, 293 base64'd and serialised beside itself on the writer. To a node that reads 294 the framed body (``exploit_body="framed"``) it rides raw after the JSON 295 (`core.exploit_wire`); to an older one it is the same JSON it always read, 296 ``exploit.archive_b64`` spliced in as base64 of each chunk. 297 """ 298 exploit = body.get("exploit") 299 if not isinstance(exploit, dict): 300 raise ValueError("an exploit archive needs the exploit's fields") 301 if exploit_body == FRAMED: 302 head = json.dumps({**body, "exploit": {**exploit, "archive_b64": ""}}).encode() 303 stream = _ArchiveBody(head, archive, b"", b64=False) 304 headers = { 305 "Content-Type": FRAMED_CONTENT_TYPE, 306 REQUEST_BYTES_HEADER: str(len(head)), 307 } 308 else: 309 text = json.dumps({**body, "exploit": {**exploit, "archive_b64": _ARCHIVE_SLOT}}) 310 before, slot, after = text.partition(json.dumps(_ARCHIVE_SLOT)) 311 if not slot or _ARCHIVE_SLOT in after: 312 raise ValueError("the exploit's archive slot is not unique in the request") 313 stream = _ArchiveBody((before + '"').encode(), archive, ('"' + after).encode(), b64=True) 314 headers = {"Content-Type": "application/json"} 315 return {"content": stream, "headers": {**headers, "Content-Length": str(len(stream))}}
content and headers for a harness run whose exploit archive is archive.
⚠️ Streamed either way (#3628): the archive is never read whole,
base64'd and serialised beside itself on the writer. To a node that reads
the framed body (exploit_body="framed") it rides raw after the JSON
(core.exploit_wire); to an older one it is the same JSON it always read,
exploit.archive_b64 spliced in as base64 of each chunk.
318class NodeClient(BaseHttpClient): 319 """Thin sync HTTP client; one instance per node URL.""" 320 321 def __init__( 322 self, 323 node_url: str, 324 token: str, 325 *, 326 timeout: int = DEFAULT_CLIENT_TIMEOUT, 327 max_retries: int = 2, 328 transport: httpx.BaseTransport | None = None, 329 disabled_features: Iterable[str] = (), 330 ) -> None: 331 """*disabled_features* are the features an admin switched off on this 332 node (#3037, `ctfy.core.node_features`): :meth:`capabilities` answers 333 ``False`` for each, whatever the node says, so a caller reads the 334 effective value and cannot forget the switch. ``()`` is the raw answer 335 — every platform construction passes the node row's set 336 (`test_every_node_client_carries_the_switches`). 337 338 *transport* is `BaseHttpClient`'s own seam, passed through so a 339 test can drive a real node app over the real client — the hop the 340 fakes on either side of it cannot see. 341 342 *max_retries* is passed through too: a best-effort read or a stop 343 is tried once (#2812), because a retry on a timeout multiplies the 344 one number that has to stay small. 345 346 ⚠️ **A call that starts long work retries only a request that never 347 left** (#3162, :data:`~ctfy.sdk.base.RETRY_UNSENT`): every POST here 348 that names its own HTTP timeout says so per call, because a 349 ``ReadTimeout`` is a request the node has and is still running. 350 ``start_instance`` keeps the default — the node replays it from the 351 instance id. Guarded by `ctfy/tests/test_long_node_work_is_sent_once.py`.""" 352 super().__init__( 353 f"{node_url.rstrip('/')}/api/v1", 354 token, 355 timeout=timeout, 356 max_retries=max_retries, 357 transport=transport, 358 ) 359 self.disabled_features = frozenset(disabled_features) 360 361 # -- lifecycle ---------------------------------------------------------- 362 363 def start_instance( 364 self, 365 *, 366 challenge_id: str, 367 instance_id: str, 368 ttl: int, 369 answers: dict[str, str], 370 proxy_output_dir: str | None = None, 371 env: dict[str, str] | None = None, 372 publish_gamebox: bool = False, 373 match_network: MatchNetwork | None = None, 374 open_shell_password: str = "", 375 authored_revision: str = "", 376 internet: InternetAccess = InternetAccess.ALLOW, 377 tcp_access: TcpAccess = TcpAccess.TLS_SNI, 378 egress_allow_hosts: list[str] | None = None, 379 resource_budget: ResourceBudget | None = None, 380 compose_up_timeout_s: int = 0, 381 vpn_callback: bool = False, 382 ) -> InstanceStarted: 383 resp = self.request( 384 "POST", 385 "/instances", 386 json={ 387 # #1835: the authored tree's revision this start must run; 388 # a node holding another (or none) fetches it first. 389 "authored_revision": authored_revision, 390 "challenge_id": challenge_id, 391 "instance_id": instance_id, 392 "ttl": ttl, 393 "answers": answers, 394 "proxy_output_dir": proxy_output_dir, 395 "env": env or {}, 396 "publish_gamebox": publish_gamebox, 397 # ``None`` rather than an omitted key: the node's model 398 # defaults to None either way, and sending it explicitly 399 # keeps the body's shape stable across both branches. 400 "match_network": (dataclasses.asdict(match_network) if match_network else None), 401 # Classic-AWD open shell (#1725): the box's starting root 402 # password, empty for every managed / non-AWD start. 403 "open_shell_password": open_shell_password, 404 # #1969: ``deny`` holds the box off the internet; the hosts 405 # are the platform-internal ones it still reaches. 406 "internet": str(internet), 407 # #2082: how a player reaches the box's TCP services. 408 "tcp_access": str(tcp_access), 409 "egress_allow_hosts": list(egress_allow_hosts or []), 410 # The CPU / memory a player-authored box is held to; ``None`` 411 # for the corpus and from an older platform. 412 "resource_budget": ( 413 resource_budget.model_dump() if resource_budget is not None else None 414 ), 415 # #3165: the platform's ``compose_up_timeout_s``, so the node 416 # spends the budget the platform waits on; ``0`` = the node's own. 417 "compose_up_timeout_s": compose_up_timeout_s, 418 # #3598: arm the tunnel's callback forward (one-team boxes only). 419 "vpn_callback": vpn_callback, 420 }, 421 ) 422 _raise_for_node_status(resp) 423 return _parsed(InstanceStarted, resp) 424 425 def stop_instance(self, instance_id: str) -> None: 426 resp = self.request("DELETE", f"/instances/{instance_id}") 427 resp.raise_for_status() 428 429 def apply_fabric( 430 self, 431 *, 432 index: int, 433 interface: dict[str, Any], 434 match_network: str = "", 435 ) -> FabricStatus: 436 """Put this node on one match's WireGuard fabric. 437 438 ⚠️ **Returns the model, never ``resp.json()``.** The platform 439 reads the verdict field by field, and on a dict a renamed field 440 is ``None`` — falsy — which reads as "the arena did not open", 441 so a wire change would quietly report every node as broken. 442 443 Returns the node's verdict rather than raising on a refusal: the 444 route answers **200 with a body** precisely so that "this node is 445 unreachable" and "this node rejected the plan" stay different 446 facts, and a caller fanning out over an arena needs to tell them 447 apart — one is waited on, the other is looked at. 448 449 *match_network* lets the node check the tunnel landed in the 450 namespace its boxes are in, and open the bridge's one hole. It is 451 the platform's own fact (`awd_network.network_name`), so the node 452 is told rather than guessing. 453 """ 454 resp = self.request( 455 "POST", 456 "/fabric", 457 json={ 458 "index": index, 459 "interface": interface, 460 "match_network": match_network, 461 }, 462 ) 463 resp.raise_for_status() 464 return _parsed(FabricStatus, resp) 465 466 def probe_fabric( 467 self, 468 *, 469 index: int, 470 peers: list[dict[str, str]], 471 mtu: int = 0, 472 ) -> FabricProbeReport: 473 """Ask named peers the three link questions. Applies nothing. 474 475 ⚠️ **Returns the model, never ``resp.json()``** — same reason 476 `apply_fabric` gives: on a dict a renamed field reads as falsy, 477 which here means "your tunnel is down" about a wire change. 478 """ 479 resp = self.request( 480 "POST", 481 "/fabric/probe", 482 json={"index": index, "peers": peers, "mtu": mtu}, 483 ) 484 resp.raise_for_status() 485 return _parsed(FabricProbeReport, resp) 486 487 def remove_fabric(self, *, index: int, match_network: str = "") -> FabricStatus: 488 """Take this node off one match's fabric and close its hole. 489 490 ⚠️ *match_network* is what lets the node resolve the bridge and 491 delete the ``DOCKER-USER`` rules by name. Without it the tunnel 492 goes and the hole stays — open on whatever docker gives that 493 bridge name next. 494 """ 495 resp = self.request( 496 "DELETE", 497 f"/fabric/{index}", 498 params={"match_network": match_network}, 499 ) 500 resp.raise_for_status() 501 return _parsed(FabricStatus, resp) 502 503 def stop_instance_service(self, instance_id: str, service: str) -> int: 504 """Stop one compose service, leaving the instance running. 505 506 The exercise format's session close (§4b.4). Returns how many 507 containers the node stopped — 0 means the challenge declares no 508 such service, which is a real answer rather than a failure, so 509 the caller can distinguish it from a cut tunnel. 510 """ 511 resp = self.request( 512 "POST", 513 f"/instances/{instance_id}/stop-service", 514 json={"service": service}, 515 ) 516 resp.raise_for_status() 517 body = resp.json() 518 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0 519 520 def capabilities( 521 self, *, harness_admission: bool = False, agent_ingress: bool = False 522 ) -> NodeCapabilities: 523 """What this node can do beyond the original verbs. 524 525 ⚠️ **A 404 is an answer, not an error**: a node from before hold / 526 resume has no such route, and "cannot hold" is exactly what the 527 platform needs to hear -- the caller then falls back to deleting. 528 Any other failure raises, because an unreachable node is not a node 529 that cannot hold. 530 """ 531 # ⚠️ #2356: ``harness_admission`` makes the node prove it can hold 532 # an admitted run, which writes its host firewall — asked only by 533 # the admission paths, never by hold / internet. 534 # #3020: ``agent_ingress`` makes the node converge its listener, 535 # asked only before handing a published target over WireGuard. 536 params = { 537 **({"harness_admission": "true"} if harness_admission else {}), 538 **({"agent_ingress": "true"} if agent_ingress else {}), 539 } 540 resp = self.request("GET", "/capabilities", params=params or None) 541 if resp.status_code == 404: 542 return NodeCapabilities() 543 resp.raise_for_status() 544 return masked_capabilities(_parsed(NodeCapabilities, resp), self.disabled_features) 545 546 def create_agent_ingress_peer( 547 self, *, run_id: str, public_key: str, ports: list[int], ttl_s: int 548 ) -> AgentIngressPeer: 549 """Add *run_id*'s peer to the node's agent-ingress listener (#3020). 550 551 Only the public key crosses; the caller keeps the private half. 552 Raises on any non-2xx (the node's refusal is in the detail). 553 """ 554 body = AgentIngressPeerRequest( 555 run_id=run_id, public_key=public_key, ports=ports, ttl_s=ttl_s 556 ) 557 resp = self.request("POST", "/agent-ingress/peers", json=body.model_dump(mode="json")) 558 resp.raise_for_status() 559 return _parsed(AgentIngressPeer, resp) 560 561 def delete_agent_ingress_peer(self, run_id: str) -> bool: 562 """Revoke *run_id*'s peer; ``False`` when the node held none.""" 563 resp = self.request("DELETE", f"/agent-ingress/peers/{run_id}") 564 resp.raise_for_status() 565 return _parsed(AgentIngressPeerRemoved, resp).removed 566 567 def hold_instance(self, instance_id: str, mode: str) -> int: 568 """Pause or stop an instance, removing nothing. Returns containers held.""" 569 resp = self.request("POST", f"/instances/{instance_id}/hold", json={"mode": mode}) 570 resp.raise_for_status() 571 return _parsed(InstanceHeld, resp).count 572 573 def resume_instance(self, instance_id: str) -> int: 574 """Bring a held instance back. Returns containers brought back.""" 575 resp = self.request("POST", f"/instances/{instance_id}/resume") 576 resp.raise_for_status() 577 return _parsed(InstanceHeld, resp).count 578 579 def change_instance_internet( 580 self, instance_id: str, change: InstanceInternetChange 581 ) -> InstanceInternetChanged: 582 """Change a running box's internet verdict (#2067). 583 584 Raises :class:`NodeRequestError` on any refusal, carrying the node's 585 ``code`` (:data:`~ctfy.core.exceptions.NODE_INTERNET_CHANGE_FAILED` 586 when its firewall could not converge — the node has then put its 587 record back, so nothing changed). 588 """ 589 resp = self.request( 590 "POST", f"/instances/{instance_id}/internet", json=change.model_dump(mode="json") 591 ) 592 _raise_for_node_status(resp) 593 return _parsed(InstanceInternetChanged, resp) 594 595 def stop_all(self) -> None: 596 resp = self.request("POST", "/admin/stop-all") 597 resp.raise_for_status() 598 599 def put_authored_challenge(self, push: NodeAuthoredPush) -> NodeAuthoredResult: 600 """Ask the node to write an approved player upload into its catalog. 601 602 ⚠️ **The bytes travel here, unlike `put_generated_range`.** That 603 one sends a scenario because the node can compile it; a 604 player-authored tree has no compiler and no corpus entry, so the 605 archive is what there is to send. 606 607 The node answers **200 with ``ok: false``** for a refusal, so a 608 node that declined the archive and a node that could not be 609 reached stay different facts; only the second raises here. 610 """ 611 resp = self.request("POST", "/admin/authored", json=push.model_dump(mode="json")) 612 resp.raise_for_status() 613 return _parsed(NodeAuthoredResult, resp) 614 615 def smoke_authored_challenge( 616 self, push: NodeAuthoredSmokePush, *, timeout: int | None = None 617 ) -> NodeAuthoredSmokeResult: 618 """Ask the node to run an authored challenge's own reference exploit. 619 620 ⚠️ **Takes its own timeout.** A smoke run brings a whole estate 621 up; the client default is sized for a status call and would give 622 up while the node is still doing what it was asked. 623 """ 624 kwargs: dict[str, Any] = {"json": push.model_dump(mode="json")} 625 if timeout is not None: 626 kwargs["timeout"] = timeout 627 resp = self.request("POST", "/admin/authored/smoke", retry_on=RETRY_UNSENT, **kwargs) 628 resp.raise_for_status() 629 return _parsed(NodeAuthoredSmokeResult, resp) 630 631 def smoke_progress(self, run_id: str, since: int = 0) -> NodeSmokeProgress | None: 632 """The steps and lines a running smoke has produced since *since* (#2145). 633 634 ``None`` when the node holds no feed for *run_id* — a node older than 635 the feed, or a run that never started — which a watcher reads as 636 *unwatched*. Any other failure raises: the caller decides that a 637 watcher's trouble must never fail the run it watches. 638 """ 639 # ⚠️ A short timeout of its own: this is read once a second beside a 640 # run that may be minutes long, and a read that hangs on a busy worker 641 # must not hold the watcher past the run it watches. 642 resp = self.request( 643 "GET", 644 f"/admin/authored/smoke/{run_id}/progress", 645 params={"since": since}, 646 timeout=10, 647 ) 648 if resp.status_code == 404: 649 return None 650 resp.raise_for_status() 651 return _parsed(NodeSmokeProgress, resp) 652 653 def smoke_entrance(self, run_id: str) -> NodeSmokeEntrance: 654 """The player's entrance to the smoke box held for *run_id* (#2819 W2). 655 656 ``pending`` / ``ready`` / ``gone``; a 404 (a node older than the 657 route) raises, which the caller reads as *this node cannot hold*. 658 """ 659 resp = self.request("GET", f"/admin/authored/smoke/{run_id}/entrance", timeout=15) 660 resp.raise_for_status() 661 return _parsed(NodeSmokeEntrance, resp) 662 663 def post_smoke_exploit(self, run_id: str, outcome: NodeSmokeExploitOutcome) -> bool: 664 """Hand the held smoke box its exploit outcome (#2819 W2). 665 666 ``True`` when the node took it; ``False`` when it holds no box for 667 *run_id* any more (it tore down on its own timeout) or had one. 668 """ 669 resp = self.request( 670 "POST", 671 f"/admin/authored/smoke/{run_id}/exploit", 672 json=outcome.model_dump(mode="json"), 673 timeout=30, 674 # First outcome wins on the node, so a resend is harmless; but a 675 # read timeout is a post that may have landed (#3162). 676 retry_on=RETRY_UNSENT, 677 ) 678 if resp.status_code == 404: 679 return False 680 resp.raise_for_status() 681 return bool(resp.json().get("taken")) 682 683 def harness_log(self, run_id: str, after: int = 0) -> NodeAgentLog | None: 684 """An agent run's console lines numbered above *after* (#2401). 685 686 ``None`` when the node holds no console for *run_id* — a node older 687 than the feed, or a run that never started there — which a watcher 688 reads as *unwatched*. Any other failure raises: the caller decides 689 that a watcher's trouble must never fail the run it watches. 690 """ 691 # ⚠️ A short timeout of its own, as ``smoke_progress``: read once a 692 # second beside a run that may be hours long. 693 resp = self.request( 694 "GET", f"/harness/runs/{run_id}/log", params={"after": after}, timeout=10 695 ) 696 if resp.status_code == 404: 697 return None 698 resp.raise_for_status() 699 return _parsed(NodeAgentLog, resp) 700 701 def harness_result(self, run_id: str) -> HarnessRunResult | None: 702 """What the node knows of a run's harness call (#3021). 703 704 ``None`` when the node has no such route — a node older than the 705 result store, which can never return a run's outcome after its call 706 is gone. ``state="unknown"`` is the node answering that it holds 707 nothing for *run_id*. Any other failure raises: an unreachable node 708 is neither of those, and the caller bounds how long it waits on one. 709 """ 710 resp = self.request("GET", f"/harness/runs/{run_id}/result", timeout=30) 711 if resp.status_code == 404: 712 return None 713 resp.raise_for_status() 714 return _parsed(HarnessRunResult, resp) 715 716 def put_generated_range(self, push: NodeRangePush) -> NodeRangeResult: 717 """Ask the node to build a generated range from its scenario. 718 719 ⚠️ **The scenario travels, not the estate.** The corpus is 720 mounted on the node and the compiler ships inside it, so 70-odd 721 rendered files never cross this API — and the corpus commit that 722 rides along is what stops one scenario becoming two different 723 estates under one id across a fleet. 724 725 The node answers **200 with ``ok: false``** for a refusal, so a 726 node that declined and a node that could not be reached stay 727 different facts; only the second raises here. 728 """ 729 resp = self.request("POST", "/admin/ranges", json=push.model_dump(mode="json")) 730 resp.raise_for_status() 731 return _parsed(NodeRangeResult, resp) 732 733 def verify_generated_range( 734 self, push: NodeRangeVerifyPush, *, timeout: int | None = None 735 ) -> NodeRangeVerifyResult: 736 """Ask the node to build a scenario, solve it, and take it down. 737 738 ⚠️ **The longest call in this API**, so the caller passes its own 739 timeout: the node's budget is ``compose_timeout_s + 740 solve_timeout_s`` and a client that used the default would give 741 up while the node was still building — then retry, and start a 742 second estate beside the first. 743 744 ⚠️ A client timeout does **not** leave a range running: the node 745 tears down in its own ``finally``. What is lost is the answer, 746 not the host. 747 748 The node answers **200 with an ``error``** for a refusal, the 749 same split ``put_generated_range`` uses; only an unreachable node 750 raises. 751 """ 752 kwargs: dict[str, Any] = {"json": push.model_dump(mode="json")} 753 if timeout is not None: 754 # httpx takes a per-request override; the client-wide value 755 # stays whatever the caller constructed this with. 756 kwargs["timeout"] = timeout 757 resp = self.request("POST", "/admin/ranges/verify", retry_on=RETRY_UNSENT, **kwargs) 758 resp.raise_for_status() 759 return _parsed(NodeRangeVerifyResult, resp) 760 761 def cancel_generated_range_verify(self, run_id: str) -> bool: 762 """Tell the node to stop a verification it is running. 763 764 ⚠️ **A miss is success, not a 404 to report.** The cancel races 765 the run's own finish, so "no such run" means the run already 766 ended — which is what the operator asked for. The node answers 767 ``{"cancelled": false}`` for that case rather than raising, and 768 this returns it so a caller that wants to say "it had already 769 finished" can. 770 """ 771 resp = self.request("POST", f"/admin/ranges/verify/{run_id}/cancel") 772 resp.raise_for_status() 773 body = resp.json() 774 return bool(body.get("cancelled")) 775 776 def rescan_challenges(self) -> ChallengeReloadResult: 777 """Tell the node to drop its spec cache and re-scan challenges_dir. 778 779 Returns ``{total, added, removed}`` so the platform can report 780 the per-node outcome of a cluster-wide rescan.""" 781 resp = self.request("POST", "/admin/rescan-challenges") 782 resp.raise_for_status() 783 return _parsed(ChallengeReloadResult, resp) 784 785 # -- admin pre-build (image cache warming) ------------------------------ 786 787 def build_challenge( 788 self, 789 challenge_id: str, 790 *, 791 authored_revision: str = "", 792 resource_budget: ResourceBudget | None = None, 793 ) -> ChallengeBuildState: 794 """Ask the node to pre-build images for *challenge_id*. 795 796 Fires-and-returns: the node persists ``status="building"`` and 797 spawns a daemon thread; the body returned here is that initial 798 state row. Polling :meth:`get_build_state` is how the platform 799 learns when it lands on ``built`` / ``failed``. *authored_revision* 800 is #1835's: the tree the build must be of, fetched if not held. 801 """ 802 params = {"authored_revision": authored_revision} if authored_revision else None 803 # #2504: an authored tree pre-builds under this budget, or not at all. 804 kwargs: dict[str, Any] = {} 805 if resource_budget is not None: 806 kwargs["json"] = {"resource_budget": resource_budget.model_dump()} 807 resp = self.request( 808 "POST", f"/admin/challenges/{challenge_id}/build", params=params, **kwargs 809 ) 810 _raise_for_node_status(resp) 811 return _parsed(ChallengeBuildState, resp) 812 813 def build_all_challenges( 814 self, 815 challenge_ids: list[str] | None = None, 816 *, 817 resource_budget: ResourceBudget | None = None, 818 ) -> BuildAllQueued: 819 """Queue background pre-build on the node. 820 821 With ``challenge_ids=None`` the node builds every spec it knows. 822 With an explicit list (the platform scoping a bulk build to a 823 competition's challenge set) only those are built. Returns 824 ``{queued, skipped_built, skipped_in_progress}`` so the platform 825 can report per-node what got picked up. Sequential on the node 826 side — no fan-out across the corpus. 827 """ 828 kwargs: dict[str, Any] = {} 829 body: dict[str, Any] = {} 830 if challenge_ids is not None: 831 body["challenge_ids"] = challenge_ids 832 if resource_budget is not None: 833 # #2504: what an authored id in the scope pre-builds under. 834 body["resource_budget"] = resource_budget.model_dump() 835 if body: 836 kwargs["json"] = body 837 resp = self.request("POST", "/admin/challenges/build-all", **kwargs) 838 _raise_for_node_status(resp) 839 return _parsed(BuildAllQueued, resp) 840 841 def build_push_challenge( 842 self, 843 challenge_id: str, 844 *, 845 push_ticket: str = "", 846 deadline_s: int = 0, 847 cleanup: bool = False, 848 cache_max_bytes: int = 0, 849 confine_network: bool = False, 850 authored_revision: str = "", 851 run_id: str = "", 852 resource_budget: ResourceBudget | None = None, 853 ) -> ChallengeFreezeResult: 854 """Build one challenge's ``build:`` services and freeze them to the registry. 855 856 Layer 2 producer (P0). **Blocks** until the challenge is built + 857 pushed (or skipped as already frozen), unlike the fire-and-return 858 :meth:`build_challenge`. ⚠️ *deadline_s* bounds the node's whole 859 freeze (#3167, `ctfy.core.freeze_budget`; ``0`` sends the node's own 860 default), and the HTTP wait is derived from it — 861 `freeze_client_wait_s`, past the node's own answer — so the client 862 never abandons a freeze the node is still running. Sent once: a 863 ``ReadTimeout`` is a request the node has (#3162). Returns the per-service freeze result; 864 the platform's ``challenge_build_push`` task calls this one 865 challenge at a time. *push_ticket* is the platform's short-lived 866 registry credential the node's ``docker push`` authenticates with 867 — the node runs it in a container with no ambient login. 868 *cleanup* asks the node to remove what the build left and prune its 869 build cache to *cache_max_bytes* afterwards, and *confine_network* 870 keeps every ``RUN`` off the host's network (both the freeze pool, #1827). 871 *run_id* names this call for :meth:`cancel_build_push` and 872 :meth:`build_push_progress` while it is in flight (#1949). 873 """ 874 resp = self.request( 875 "POST", 876 f"/admin/challenges/{challenge_id}/build-push", 877 json={ 878 "push_ticket": push_ticket, 879 "cleanup": cleanup, 880 "cache_max_bytes": cache_max_bytes, 881 "confine_network": confine_network, 882 "authored_revision": authored_revision, 883 "run_id": run_id, 884 "deadline_s": deadline_s, 885 # #2504: the build limits an authored tree is frozen under; 886 # a node refuses one that arrives without them. 887 "resource_budget": ( 888 resource_budget.model_dump() if resource_budget is not None else None 889 ), 890 }, 891 timeout=freeze_client_wait_s(deadline_s or freeze_deadline_s()), 892 retry_on=RETRY_UNSENT, 893 ) 894 _raise_for_node_status(resp) 895 return _parsed(ChallengeFreezeResult, resp) 896 897 def cancel_build_push(self, run_id: str) -> BuildPushCancelled: 898 """Cancel the freeze :meth:`build_push_challenge` started under *run_id* (#1949). 899 900 Idempotent; ``found`` false means the node holds no such run. 901 """ 902 resp = self.request("POST", "/admin/build-push/cancel", json={"run_id": run_id}) 903 _raise_for_node_status(resp) 904 return _parsed(BuildPushCancelled, resp) 905 906 def build_push_progress(self, run_id: str) -> BuildPushProgress: 907 """What the freeze running under *run_id* is doing now (#1949).""" 908 resp = self.request("GET", f"/admin/build-push/{run_id}/progress") 909 _raise_for_node_status(resp) 910 return _parsed(BuildPushProgress, resp) 911 912 def get_disk_free(self) -> NodeDiskFree: 913 """Free space on the node's data filesystem, read now (#1827). 914 915 Raises on any failure — including a node predating the route, which 916 answers 404 — and the freeze reads every failure as *cannot tell*, 917 which stops it. 918 """ 919 resp = self.request("GET", "/admin/disk") 920 _raise_for_node_status(resp) 921 return _parsed(NodeDiskFree, resp) 922 923 def get_build_state(self) -> BuildStateRows: 924 """Fetch every per-challenge build-state row on this node. 925 926 Returns ``{"rows": [{challenge_id, status, built_at, error}, …]}``. 927 ``status`` is one of ``unbuilt`` / ``building`` / ``built`` / 928 ``failed``; ``unbuilt`` placeholders are synthesised for specs 929 the node has seen but never been asked to build. 930 """ 931 resp = self.request("GET", "/admin/challenges/build-state") 932 _raise_for_node_status(resp) 933 return _parsed(BuildStateRows, resp) 934 935 def pull_challenge(self, challenge_id: str) -> ChallengePullState: 936 """Ask the node to pre-pull registry images for *challenge_id*. 937 938 Pull-side twin of :meth:`build_challenge`: the node persists 939 ``status="pulling"`` and spawns a daemon thread; poll 940 :meth:`get_pull_state` for the ``pulled`` / ``failed`` landing. 941 """ 942 resp = self.request("POST", f"/admin/challenges/{challenge_id}/pull") 943 _raise_for_node_status(resp) 944 return _parsed(ChallengePullState, resp) 945 946 def pull_all_challenges(self, challenge_ids: list[str] | None = None) -> PullAllQueued: 947 """Queue background pre-pull on the node. 948 949 With ``challenge_ids=None`` the node pulls every spec it knows; 950 with an explicit list only those (the platform scoping to a 951 competition). Returns ``{queued, skipped_pulled, 952 skipped_in_progress}``. 953 """ 954 kwargs: dict[str, Any] = {} 955 if challenge_ids is not None: 956 kwargs["json"] = {"challenge_ids": challenge_ids} 957 resp = self.request("POST", "/admin/challenges/pull-all", **kwargs) 958 _raise_for_node_status(resp) 959 return _parsed(PullAllQueued, resp) 960 961 def get_pull_state(self) -> PullStateRows: 962 """Fetch every per-challenge pull-state row on this node. 963 964 Returns ``{"rows": [{challenge_id, status, pulled_at, error}, …]}``. 965 ``status`` is one of ``unpulled`` / ``pulling`` / ``pulled`` / 966 ``failed``; ``unpulled`` placeholders are synthesised for specs 967 the node has seen but never been asked to pull. 968 """ 969 resp = self.request("GET", "/admin/challenges/pull-state") 970 _raise_for_node_status(resp) 971 return _parsed(PullStateRows, resp) 972 973 # -- status / health ---------------------------------------------------- 974 975 def get_status(self, instance_id: str) -> InstanceStatusReport: 976 resp = self.request("GET", f"/instances/{instance_id}/status") 977 resp.raise_for_status() 978 return _parsed(InstanceStatusReport, resp) 979 980 def list_instances(self) -> list[NodeInstanceSummary]: 981 """Every instance the node still has bookkeeping for. 982 983 Used by the platform's boot re-adoption pass to decide which 984 durable claims still have containers behind them. ``get_status`` 985 answers the same question one id at a time; asking it per claim 986 would cost one round trip per instance to a node that may be 987 slow or down, on the path that gates startup. 988 """ 989 resp = self.request("GET", "/instances") 990 resp.raise_for_status() 991 return _parsed(NodeInstanceList, resp).items 992 993 def check_health(self, instance_id: str) -> bool: 994 return self.check_health_verbose(instance_id).healthy 995 996 def check_health_verbose(self, instance_id: str) -> HealthReading: 997 """Health plus whatever agent-deception telemetry the node read. 998 999 One call, because the platform already polls this endpoint for 1000 every live instance every tick and a second round trip per 1001 instance would be the whole cost of the feature. ``check_health`` 1002 stays a bool for the callers that only ever wanted one. 1003 1004 Never an error, whatever arrives: this rides the health poll, 1005 and telemetry must not be able to mark a healthy instance 1006 unhealthy. 1007 1008 ⚠️ **The two ways this can come back empty are different facts 1009 and used to be one.** An older node sends no ``deception`` key 1010 at all — it *did not say*, which is ``channel=None`` and 1011 authorises nothing. A body this platform cannot parse is 1012 something else: the node did say, and we could not read it. That 1013 is ``unreadable``, the same value the reader gives for a missing 1014 file, because it is the same fact — there is no usable channel 1015 here — arriving through a different door. 1016 1017 The parse failure that matters is version skew in the other 1018 direction: a **newer** node reporting an ``ObservationKind`` this 1019 platform does not have. ``Observation.kind`` is typed, so one 1020 unknown member fails the whole model rather than dropping one 1021 row — which is the right refusal (the node's word is not ours to 1022 edit) and exactly why it must not land as "reported nothing". 1023 """ 1024 resp = self.request("GET", f"/instances/{instance_id}/health") 1025 resp.raise_for_status() 1026 body = resp.json() 1027 raw = body.get("deception") 1028 if not raw: 1029 summary = DeceptionSummary() 1030 else: 1031 try: 1032 summary = DeceptionSummary.model_validate(raw) 1033 except ValidationError as exc: 1034 log.info( 1035 "unreadable deception telemetry from node", 1036 instance_id=instance_id, 1037 error=tail(str(exc), limit=200), 1038 ) 1039 summary = DeceptionSummary(channel="unreadable") 1040 raw_contact = body.get("contact") 1041 if not raw_contact: 1042 contact = ContactReading() 1043 else: 1044 try: 1045 contact = ContactReading.model_validate(raw_contact) 1046 except ValidationError as exc: 1047 log.info( 1048 "unreadable contact telemetry from node", 1049 instance_id=instance_id, 1050 error=tail(str(exc), limit=200), 1051 ) 1052 contact = ContactReading(channel="unreadable") 1053 raw_procs = body.get("new_processes") 1054 # ⚠️ Shape-checked rather than trusted: an older node sends 1055 # nothing and a newer one could send a shape this platform does 1056 # not model, and neither may reach a reader as *a container full 1057 # of intruders*. Anything unreadable is silence, which for a 1058 # signal built to under-report is the honest reading. 1059 procs: dict[str, list[str]] = {} 1060 if isinstance(raw_procs, dict): 1061 for container, names in raw_procs.items(): 1062 if isinstance(container, str) and isinstance(names, list): 1063 procs[container] = [str(n) for n in names] 1064 return HealthReading( 1065 healthy=bool(body.get("is_healthy")), 1066 deception=summary, 1067 contact=contact, 1068 new_processes=procs, 1069 ) 1070 1071 def node_health(self) -> dict[str, Any]: 1072 """Liveness + ``{running, capacity}`` for heartbeat.""" 1073 resp = self.request("GET", "/health") 1074 resp.raise_for_status() 1075 body: dict[str, Any] = resp.json() 1076 return body 1077 1078 # -- traffic / runtime -------------------------------------------------- 1079 1080 def get_traffic_page( 1081 self, instance_id: str, *, cursor: str = "", limit: int = 0 1082 ) -> InstanceTrafficPage: 1083 """One page of mitmproxy flows; the capture lives on the node's FS. 1084 1085 ⚠️ **The one method that must not use ``_parsed``.** A node from 1086 before paging answers with a bare *list* — it sent the whole 1087 capture and understands no cursor — and a strict 1088 ``model_validate`` turns that supported skew into a raised 1089 request. So the body goes through ``coerce_page``, which already 1090 owns every decision about an unexpected shape, and the caller 1091 gets the model. 1092 1093 This is the same move ``coerce_page`` was written for, one layer 1094 down. Its docstring used to say the parsing belonged 1095 "platform-side … so a route and this client cannot come to 1096 disagree" — and there were *three* platform-side calls doing it. 1097 There is one call now, at the seam that knows the request 1098 cursor, which is what the fallback needs; the routes hold the 1099 type instead of re-deciding its shape. 1100 1101 ⚠️ **An empty ``cursor`` means "from the beginning".** Passing 1102 one on every poll re-reads the whole capture, which is the cost 1103 the paged read exists to remove — arriving through the caller 1104 rather than through the node. 1105 """ 1106 params: dict[str, Any] = {} 1107 if cursor: 1108 params["cursor"] = cursor 1109 if limit > 0: 1110 params["limit"] = limit 1111 resp = self.request("GET", f"/instances/{instance_id}/traffic", params=params) 1112 resp.raise_for_status() 1113 page = coerce_page(resp.json(), cursor) 1114 return InstanceTrafficPage( 1115 flows=page.flows, 1116 cursor=page.cursor, 1117 truncated=page.truncated, 1118 capture=page.capture, 1119 ) 1120 1121 def get_traffic_witnesses( 1122 self, instance_id: str, *, cursor: str = "", limit: int = 0 1123 ) -> InstanceTrafficWitnesses: 1124 """Who spoke to this box since *cursor*, with no bodies moved. 1125 1126 §7.1's correlation reads one gamebox per team per round. Through 1127 :meth:`get_traffic_page` that is every flow, both bodies 1128 included (~100 kB apiece by ``CLAUDE.md``'s measurement), 1129 pulled across the wire to extract a handful of addresses; the 1130 node reduces instead and this carries the result. 1131 1132 ⚠️ **Strict parsing here, unlike its neighbour, and that is the 1133 difference between an old field and an old route.** 1134 ``get_traffic_page`` is lenient because a node from before 1135 paging answers the *same* path with a bare list, which is 1136 supported skew. This route did not exist on such a node at all, 1137 so the honest answer from one is a 404 — and a lenient parse of 1138 an error body would hand the round loop an empty witness set, 1139 which reads as *nobody was there*. The caller catches the 1140 request error and records the round as unknown. 1141 """ 1142 params: dict[str, Any] = {} 1143 if cursor: 1144 params["cursor"] = cursor 1145 if limit > 0: 1146 params["limit"] = limit 1147 resp = self.request("GET", f"/instances/{instance_id}/traffic-witnesses", params=params) 1148 resp.raise_for_status() 1149 return _parsed(InstanceTrafficWitnesses, resp) 1150 1151 def list_containers(self, instance_id: str) -> list[ComposeContainer]: 1152 """Enumerate every container in an instance's compose project. 1153 1154 Backs the admin-shell feature: the platform forwards a 1155 ``GET /admin/instances/{id}/containers`` to the assigned node, 1156 which returns one row per container (challenge services and 1157 platform-injected sidecars alike). The WebSocket reverse-proxy 1158 is opened separately and does not go through ``NodeClient``. 1159 """ 1160 resp = self.request("GET", f"/instances/{instance_id}/containers") 1161 _raise_for_node_status(resp) 1162 return _parsed_list(ComposeContainer, resp) 1163 1164 def run_checker( 1165 self, 1166 instance_id: str, 1167 *, 1168 service: str, 1169 cmd: list[str], 1170 timeout_s: int = DEFAULT_JUDGE_TIMEOUT_S, 1171 ) -> CheckResult: 1172 """Exec an author-supplied checker in a trusted judge sidecar. 1173 1174 Backs the checker / exec-judge feature: the platform forwards a 1175 verify request to the assigned node, which runs ``cmd`` inside the 1176 named sidecar and returns 1177 ``{exit_code, stdout, stderr, timed_out, error}``. 1178 1179 ⚠️ *timeout_s* is the author's, and the node clamps it (#3169): the 1180 clamped budget is what is sent and what the wait is derived from 1181 (`core.judge_budget.platform_wait_s`), so ``0`` no longer waits 10 s 1182 on a node running 30, and ``600`` no longer holds a threadpool slot 1183 for 610 s on a node that stops at 120. Sent once (``RETRY_UNSENT``). 1184 """ 1185 exec_s = judge_exec_s(timeout_s) 1186 resp = self.request( 1187 "POST", 1188 f"/instances/{instance_id}/check", 1189 json={"service": service, "cmd": cmd, "timeout_s": exec_s}, 1190 timeout=judge_platform_wait_s(exec_s), 1191 retry_on=RETRY_UNSENT, 1192 ) 1193 _raise_for_node_status(resp) 1194 return _parsed(CheckResult, resp) 1195 1196 def run_harness( 1197 self, 1198 *, 1199 image: str, 1200 run_id: str = "", 1201 env: dict[str, str], 1202 timeout_s: int = 1800, 1203 untrusted: bool = False, 1204 network: str = "", 1205 own_network: bool = False, 1206 match_network: str = "", 1207 match_address: str = "", 1208 brief: dict[str, Any] | None = None, 1209 target_instance: str = "", 1210 target_aliases: dict[str, str] | None = None, 1211 target_access: str = "", 1212 vpn_config: str = "", 1213 estate_zones: Sequence[str] = (), 1214 target_endpoints: Sequence[str] = (), 1215 target_hosts: Mapping[str, str] | None = None, 1216 target_datagram_endpoints: Sequence[str] = (), 1217 pull_ticket: str = "", 1218 registry_auth: HarnessRegistryAuth | None = None, 1219 limits: HarnessLimits | None = None, 1220 admission_profile: bool = False, 1221 egress_allow: list[str] | None = None, 1222 internet: bool = True, 1223 rootfs_budget_bytes: int = 0, 1224 unpack_budget_bytes: int = 0, 1225 disk_low_watermark_bytes: int = 0, 1226 ingress: bool = True, 1227 local_ingress: bool = False, 1228 platform_image: bool = False, 1229 image_policy: HarnessImagePolicy | None, 1230 attachments: dict[str, str] | None = None, 1231 keep_work: bool = False, 1232 resume_work: bool = False, 1233 exploit: dict[str, Any] | None = None, 1234 exploit_archive: Path | None = None, 1235 exploit_body: ExploitBody = "", 1236 ) -> HarnessRun: 1237 """Run a one-shot evaluation-harness container on the node. 1238 1239 ``exploit`` (#2819 W2) runs a smoke's reference exploit in the fence 1240 instead of an agent (``HarnessExploit``'s fields); sent only when set. 1241 ``exploit_archive`` is its packed tree on disk (#3628), streamed into 1242 the body (:func:`harness_run_content`) as the node's 1243 ``capabilities().exploit_body`` — passed as *exploit_body* — reads it. 1244 1245 ``image_policy`` (#2608) is **required, with no default**: every 1246 caller says whether this image is a user's (the registry rules the 1247 node re-checks before pulling) or the platform's own (``None``). An 1248 untrusted run without one is refused by the node. 1249 1250 The node ``docker run``s ``image`` with ``env`` injected, waits for it 1251 to exit (bounded by ``timeout_s``), and returns 1252 ``{exit_code, stdout, stderr, timed_out, error}`` — the same shape as 1253 :meth:`run_checker`. The harness writes its JSON rollup to stdout. The 1254 per-call HTTP timeout sits above the node's run budget so the client 1255 doesn't abandon the request before the (long-running) harness returns. 1256 1257 ``untrusted`` runs the image under the node's isolation profile — 1258 off host networking, bounded resources, no capabilities — for an 1259 image the platform did not build. It requires a network: the 1260 node answers 400 without one, because "isolate this" and "I will 1261 not say where the target lives" do not compose. 1262 1263 Any of ``network`` (the target instance's own, when the caller 1264 knows it), ``own_network`` or ``target_instance`` satisfies that. 1265 ⚠️ Most eval dispatches need the second: there the harness 1266 *starts* the target partway through its own run, so at ``docker 1267 run`` time no target network exists and there is no name to 1268 send. The node creates a fresh bridge and removes it afterwards. 1269 1270 ``target_instance`` reverses that ordering, and is what an 1271 `engagement` uses: the platform starts the estate first and names 1272 it here, and the node wires its published containers to the 1273 agent's bridge. ⚠️ An **id**, never a network name — the name is 1274 a fact only the node's daemon can read, and ``docker run`` 1275 *creates* whatever string it is handed, so a platform guessing 1276 one starts a run that reaches nothing. 1277 """ 1278 body: dict[str, Any] = { 1279 "image": image, 1280 "env": env, 1281 "timeout_s": timeout_s, 1282 "untrusted": untrusted, 1283 "network": network, 1284 "own_network": own_network, 1285 "match_network": match_network, 1286 # ⚠️ **The platform-assigned arena address.** The node 1287 # connects the agent to the match network with this 1288 # ``--ip``, so the address is known before the round loop 1289 # asks (§7.1). Empty means "let docker's IPAM pick" — an 1290 # older platform's behaviour, and what keeps a node reading 1291 # this field unchanged for every non-arena dispatch. 1292 "match_address": match_address, 1293 # ⚠️ Sent even when empty, so a node reading it gets the 1294 # same shape either way; the node's default is what makes 1295 # an older platform's dispatch unchanged. 1296 "pull_ticket": pull_ticket, 1297 # #3475: the owner's registry login, sent **only when set**, 1298 # so a node that predates the field sees the body it always did. 1299 **({"registry_auth": registry_auth.model_dump()} if registry_auth is not None else {}), 1300 # ⚠️ ``None`` leaves the node's own defaults in force, which is 1301 # what a dispatch said before the ceilings were settings. 1302 "limits": limits.model_dump() if limits is not None else None, 1303 # ⚠️ Same rule, and empty is a real answer here too: a 1304 # dispatch with no run row (the conformance probe, a dry 1305 # run) has nothing to label, and a label with an empty 1306 # value would make every one of them answer one query. 1307 "run_id": run_id, 1308 # ⚠️ Sent as the already-built manifest. The platform is 1309 # the side that knows the challenge, the competition and 1310 # the run mode; a node deriving its own would be a 1311 # second implementation of a published contract. 1312 "brief": brief, 1313 "target_instance": target_instance, 1314 # ⚠️ **The names the brief published, so they resolve on 1315 # the agent's bridge too.** An estate's hosts answer to a 1316 # per-instance FQDN minted by its own resolver; joined to 1317 # a new network a container answers only to its compose 1318 # *service* name. Sending the mapping is what keeps the 1319 # address the agent was told about true under either 1320 # placement — without it the agent is handed a hostname 1321 # that does not resolve, reaches nothing, and reports an 1322 # empty result, which reads as a model that gave up. 1323 # 1324 # ⚠️ The platform's to send: it computed the surface. A 1325 # node re-deriving it from the rendered compose would be 1326 # a second implementation of the address the brief has 1327 # already promised. 1328 "target_aliases": target_aliases or {}, 1329 # #2550: ``{name: base64}`` for ``/ctfy/work/attachments/``. 1330 # ⚠️ Sent only when there are some, so every other dispatch 1331 # is byte-identical to before. 1332 **({"attachments": attachments} if attachments else {}), 1333 # #2550 restarts: sent only when asked for, like the files. 1334 **({"keep_work": True} if keep_work else {}), 1335 **({"resume_work": True} if resume_work else {}), 1336 # #2861 slice B: the target access the platform read off the 1337 # target's node. ⚠️ Sent only when there is one, so every 1338 # other dispatch is byte-identical to before; and only to a 1339 # node whose ``capabilities().harness_access`` said it reads 1340 # them, or to the target's own node (where an older node's 1341 # local read is still right). 1342 **( 1343 { 1344 "target_access": target_access, 1345 "vpn_config": vpn_config, 1346 "estate_zones": list(estate_zones), 1347 "target_endpoints": list(target_endpoints), 1348 } 1349 if target_access 1350 else {} 1351 ), 1352 # #3020: names → the target node's ingress address, for a 1353 # published target handed over the agent-ingress tunnel. Sent 1354 # only when there are some, and only to a node whose 1355 # ``capabilities().harness_ingress_access`` said it reads them. 1356 **({"target_hosts": dict(target_hosts)} if target_hosts else {}), 1357 # #3446: the published endpoints that are UDP, which the node 1358 # never TCP-probes. Sent only when there are some. 1359 **( 1360 {"target_datagram_endpoints": list(target_datagram_endpoints)} 1361 if target_datagram_endpoints 1362 else {} 1363 ), 1364 # #2356: ⚠️ sent only when asked for, so a dispatch that does 1365 # not ask is byte-identical to an older platform's — and an 1366 # older node, which would ignore the fields, is never sent 1367 # them: the caller checks ``capabilities().harness_admission``. 1368 **( 1369 { 1370 "admission_profile": True, 1371 "egress_allow": list(egress_allow or []), 1372 "internet": internet, 1373 "rootfs_budget_bytes": rootfs_budget_bytes, 1374 "unpack_budget_bytes": unpack_budget_bytes, 1375 "disk_low_watermark_bytes": disk_low_watermark_bytes, 1376 "ingress": ingress, 1377 # #2819 W1, F2: sent only when asked for. 1378 **({"local_ingress": True} if local_ingress else {}), 1379 } 1380 if admission_profile 1381 else {} 1382 ), 1383 "image_policy": image_policy.model_dump() if image_policy is not None else None, 1384 # #2608 N4: only for a row with no owner; see the node's request. 1385 **({"platform_image": True} if platform_image else {}), 1386 **({"exploit": exploit} if exploit is not None else {}), 1387 } 1388 resp = self.request( 1389 "POST", 1390 "/harness/run", 1391 **( 1392 {"json": body} 1393 if exploit_archive is None 1394 else harness_run_content(body, exploit_archive, exploit_body=exploit_body) 1395 ), 1396 timeout=( 1397 timeout_s 1398 # #2819 W2: the exploit's `solution/Dockerfile` builds first. 1399 + (SOLUTION_BUILD_TIMEOUT_S if exploit is not None else 0) 1400 + IMAGE_PULL_TIMEOUT_S 1401 + HARNESS_IMAGE_INSPECT_TIMEOUT_S 1402 + HARNESS_CREATE_TIMEOUT_S 1403 + 30 1404 ), 1405 retry_on=RETRY_UNSENT, 1406 ) 1407 _raise_for_node_status(resp) 1408 return _parsed(HarnessRun, resp) 1409 1410 def cancel_harness(self, *, run_id: str) -> int: 1411 """Stop whatever this node is running for ``run_id``; returns how many. 1412 1413 Until this existed a dispatched container was reclaimed by 1414 **nothing but its own timeout** — ``_harness_timeout``'s docstring 1415 says exactly that — so an operator pressing cancel on a 1416 match-long run was asking for something the platform had no way 1417 to deliver. 1418 1419 ⚠️ **Zero is an ordinary answer, not a failure.** The run may have 1420 finished on its own, been dispatched to a different node, or been 1421 lost to a node restart. A caller that read zero as an error would 1422 report a broken platform every time a cancel arrived a second 1423 late. 1424 """ 1425 resp = self.request("POST", "/harness/cancel", json={"run_id": run_id}) 1426 body = resp.json() 1427 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0 1428 1429 def verify_patch( 1430 self, challenge_id: str, files: dict[str, bytes], *, deadline_s: int 1431 ) -> PatchVerifyResult: 1432 """Build a submitted patch on the node and return its verdict. 1433 1434 ``files`` maps a challenge-relative path to its new bytes; base64 1435 is applied here because a patch target may legitimately be 1436 binary. Returns ``{verdict, detail, applied, steps, error}``. 1437 1438 **An empty ``verdict`` with a populated ``error`` is not a 1439 judgement** — it means the node refused the submission, the 1440 verifier crashed, or the run's deadline ran out. The caller must 1441 retry or retire the lease rather than write a score, since failing 1442 to judge a patch is not the same as judging it unfixed. 1443 1444 ⚠️ *deadline_s* bounds the node's whole run (#3164, 1445 `ctfy.core.patch_budget`), and the HTTP wait is derived from it — 1446 `patch_client_wait_s`, past the node's own answer — so the client 1447 never abandons a request the node is still working on. Sent once: 1448 a ``ReadTimeout`` is a request the node has (#3162). 1449 """ 1450 resp = self.request( 1451 "POST", 1452 "/patches/verify", 1453 json={ 1454 "challenge_id": challenge_id, 1455 "files": { 1456 path: base64.b64encode(content).decode() for path, content in files.items() 1457 }, 1458 "deadline_s": deadline_s, 1459 }, 1460 timeout=patch_client_wait_s(deadline_s), 1461 retry_on=RETRY_UNSENT, 1462 ) 1463 _raise_for_node_status(resp) 1464 return _parsed(PatchVerifyResult, resp) 1465 1466 def collect_patch_files( 1467 self, instance_id: str, service: str, paths: list[str] 1468 ) -> dict[str, bytes]: 1469 """Read a player's SSH edits back out of their running box. 1470 1471 ``paths`` are absolute in-container paths the *platform* derived 1472 from the pristine source tree. Returns only what could be read: 1473 a path missing from the reply means the player did not change it, 1474 and the caller falls back to the shipped file rather than 1475 recording a deletion they never made. 1476 """ 1477 resp = self.request( 1478 "POST", 1479 f"/instances/{instance_id}/patch-collect", 1480 json={"service": service, "paths": paths}, 1481 ) 1482 _raise_for_node_status(resp) 1483 body: dict[str, str] = resp.json() 1484 return {path: base64.b64decode(blob) for path, blob in body.items()} 1485 1486 def write_awd_answers(self, boxes: dict[str, dict[str, str]]) -> dict[str, str]: 1487 """Rotate a round's flags into every box of this node, in one call. 1488 1489 ⚠️ **One call for the whole node, never one per box.** §5.2's 1490 capacity red line is 1000 teams x 3 services injected inside 1491 120 s; per-box that is 3000 round trips, batched it is about 1492 fourteen. The signature is the enforcement — a caller cannot 1493 accidentally loop. 1494 1495 Returns ``{instance_id: ""}`` for the boxes written and a reason 1496 for the ones that were not, because one team's unreachable box 1497 must not cost every other team on the node its rotation. An 1498 unrotated box keeps serving last round's flag, which anyone 1499 holding the old value can replay. 1500 """ 1501 resp = self.request("POST", "/awd/answers", json={"boxes": boxes}) 1502 _raise_for_node_status(resp) 1503 result: dict[str, str] = resp.json() 1504 return result 1505 1506 def probe_awd_service( 1507 self, 1508 *, 1509 instance_id: str, 1510 service_id: str, 1511 tick: int, 1512 flag: str, 1513 previous_flag: str = "", 1514 previous_flag_id: str = "", 1515 ) -> dict[str, str]: 1516 """Run one round's SLA probes against one box, from outside it. 1517 1518 The flags travel *to* the node: a checker that sourced its 1519 expected value from the box it is checking would pass on any box 1520 that returns whatever it was handed. 1521 """ 1522 resp = self.request( 1523 "POST", 1524 "/awd/probe", 1525 json={ 1526 "instance_id": instance_id, 1527 "service_id": service_id, 1528 "tick": tick, 1529 "flag": flag, 1530 "previous_flag": previous_flag, 1531 "previous_flag_id": previous_flag_id, 1532 }, 1533 ) 1534 _raise_for_node_status(resp) 1535 result: dict[str, str] = resp.json() 1536 return result 1537 1538 def attack_awd_box( 1539 self, 1540 *, 1541 instance_id: str, 1542 tick: int, 1543 timeout_s: int = 60, 1544 agent_image: str = "", 1545 counter_flag: str = "", 1546 forensic_marker: str = "", 1547 llm_api_key: str = "", 1548 ) -> AwdAttackResult: 1549 """Run this box's own reference exploit against it, once. 1550 1551 Per **box**, not per service: one `run_exploit` discovers every 1552 answer the challenge declares and prints them all. 1553 1554 ``timeout_s`` is sent because the platform is what knows how long 1555 a round is; the node clamps it, because a container held open for 1556 an hour is the node's problem whoever asked for it. 1557 1558 ``forensic_marker`` is §4.3.1's, carried only by the agent 1559 branch: `build_attack_argv` passes no environment at all, so a 1560 marker on the reference exploit would be the one value that 1561 voids `EXPLOIT007`'s guarantee. 1562 1563 ``agent_image`` + ``counter_flag`` switch the node to §4.2b's 1564 agent attacker. ⚠️ **Both or neither** — the node refuses a half 1565 request rather than falling back to the reference exploit, which 1566 would run a different format than the one configured while the 1567 board looked entirely normal. 1568 """ 1569 resp = self.request( 1570 "POST", 1571 "/awd/attack", 1572 json={ 1573 "instance_id": instance_id, 1574 "tick": tick, 1575 "timeout_s": timeout_s, 1576 "agent_image": agent_image, 1577 "counter_flag": counter_flag, 1578 "forensic_marker": forensic_marker, 1579 "llm_api_key": llm_api_key, 1580 }, 1581 ) 1582 _raise_for_node_status(resp) 1583 return _parsed(AwdAttackResult, resp) 1584 1585 def get_container_logs(self, instance_id: str) -> str: 1586 """Fetch combined container stdout/stderr for archival.""" 1587 resp = self.request("GET", f"/instances/{instance_id}/container-logs") 1588 resp.raise_for_status() 1589 return str(resp.json().get("logs") or "") 1590 1591 def get_pcap(self, instance_id: str) -> PcapCapture: 1592 """Fetch the merged tcpdump capture for *instance_id*. 1593 1594 ``data`` is empty when no capture exists (sidecar disabled, 1595 instance never reached the running state, etc.) so callers can 1596 persist conditionally without try/except. 1597 1598 ⚠️ **It also says what the per-instance cap already dropped** 1599 (#1714), off the node's response headers, and ``None`` when the 1600 node did not say — an older node, which is *not reported*, never 1601 a clean capture. 1602 """ 1603 resp = self.request("GET", f"/instances/{instance_id}/pcap") 1604 if resp.status_code == 404: 1605 return PcapCapture(data=b"") 1606 resp.raise_for_status() 1607 return PcapCapture( 1608 data=resp.content, 1609 dropped_bytes=_header_int(resp, CAPTURE_DROPPED_BYTES_HEADER), 1610 dropped_segments=_header_int(resp, CAPTURE_DROPPED_SEGMENTS_HEADER), 1611 ) 1612 1613 def get_harness_artifact(self, artifact_id: str) -> bytes: 1614 """One finished run's collected archive, or ``b""``. 1615 1616 ⚠️ **Empty rather than an exception for a 404**, following 1617 :meth:`get_pcap`. The node reaps uncollected archives, and a 1618 platform that comes back after a restart is exactly the caller 1619 that meets one that is gone — a state its own record already 1620 describes, not a transport failure. 1621 """ 1622 resp = self.request("GET", f"/harness/artifacts/{artifact_id}") 1623 if resp.status_code == 404: 1624 return b"" 1625 resp.raise_for_status() 1626 return resp.content 1627 1628 def delete_harness_artifact(self, artifact_id: str) -> bool: 1629 """Tell the node the archive has been stored and can go. 1630 1631 ⚠️ **Never raises on a transport failure**, because it is called 1632 after the bytes are safely in object storage: turning a cleanup 1633 error into the run's error would replace a success with a 1634 janitorial complaint. The node's reaper collects whatever this 1635 misses. 1636 """ 1637 try: 1638 resp = self.request("DELETE", f"/harness/artifacts/{artifact_id}") 1639 except Exception: 1640 return False 1641 return resp.status_code == 200 1642 1643 def get_agent_runtime(self, instance_id: str) -> AgentRuntime: 1644 """Provider-agnostic runtime hints for attaching an agent (proxy URL, 1645 CA PEM, optional Docker-specific names). Replaces the old 1646 sandbox-network shape.""" 1647 resp = self.request("GET", f"/instances/{instance_id}/agent-runtime") 1648 resp.raise_for_status() 1649 return _parsed(AgentRuntime, resp) 1650 1651 # -- per-instance rendered attachments --------------------------------- 1652 1653 def list_instance_attachments(self, instance_id: str) -> AttachmentList: 1654 """List per-instance attachments rendered into the node's workdir. 1655 1656 Backs the platform's per-instance attachment endpoint, which 1657 surfaces the team-specific rendered file listing. 1658 1659 ⚠️ This used to hand back the raw dict, under a docstring saying 1660 "caller projects through :class:`AttachmentList` for typing" — 1661 the node's route already declared that model, so the type existed 1662 and this method's signature was the one place it was dropped. 1663 Projecting *here* means there is one place a malformed answer is 1664 caught rather than one per caller.""" 1665 resp = self.request("GET", f"/instances/{instance_id}/attachments") 1666 resp.raise_for_status() 1667 return _parsed(AttachmentList, resp) 1668 1669 def get_vpn_config(self, instance_id: str) -> bytes: 1670 """Fetch the per-instance VPN client config from the node. 1671 1672 The node reads the backend's client config out of the 1673 instance's VPN service container (generated on first boot by 1674 the base image's bootstrap) and rewrites its endpoint to the 1675 node's public host:port. Returns the body verbatim — the 1676 platform-side route adds the ``Content-Disposition`` header 1677 before re-emitting to the player, because only it knows the 1678 backend and therefore the filename the player needs. 1679 1680 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1681 proxy route catches 404 and re-emits to the player, anything 1682 else is treated as a 502. 1683 """ 1684 resp = self.request("GET", f"/instances/{instance_id}/vpn-config") 1685 resp.raise_for_status() 1686 return resp.content 1687 1688 def get_vpn_access(self, instance_id: str) -> tuple[bytes, tuple[str, ...] | None]: 1689 """The player's VPN config plus the estate's resolver zones (#2861 B). 1690 1691 The config is :meth:`get_vpn_config`'s, byte for byte; the zones ride 1692 a response header the node adds only when asked. ``None`` for the 1693 zones is a node that did not say (older, or docker unreadable there) 1694 — never "no zones". Raises like :meth:`get_vpn_config`. 1695 """ 1696 resp = self.request( 1697 "GET", f"/instances/{instance_id}/vpn-config", params={"estate_zones": "true"} 1698 ) 1699 resp.raise_for_status() 1700 raw = resp.headers.get("X-Ctfy-Estate-Zones") 1701 return resp.content, (tuple(raw.split()) if raw is not None else None) 1702 1703 def download_instance_attachment(self, instance_id: str, filename: str) -> tuple[bytes, str]: 1704 """Download one per-instance attachment as ``(bytes, content_type)``. 1705 1706 Buffers the whole body — attachments are bounded (typical case 1707 is a 10 KB binary or a small text file). For huge captures the 1708 caller should hand the player a CDN URL instead. 1709 1710 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1711 proxy route catches 404 and re-emits to the player, anything 1712 else is a 502. Invalid names or instance keys raise 1713 ``InvalidAttachmentName`` before any request is sent.""" 1714 # The instance is a single route key, never part of the file name. 1715 if component_refusal(instance_id) is not None: 1716 raise InvalidAttachmentName("Invalid attachment instance") 1717 resp = self.request( 1718 "GET", 1719 f"/instances/{quote(instance_id, safe='')}/attachments/{attachment_url_path(filename)}", 1720 ) 1721 resp.raise_for_status() 1722 return resp.content, resp.headers.get("content-type", "application/octet-stream")
Thin sync HTTP client; one instance per node URL.
321 def __init__( 322 self, 323 node_url: str, 324 token: str, 325 *, 326 timeout: int = DEFAULT_CLIENT_TIMEOUT, 327 max_retries: int = 2, 328 transport: httpx.BaseTransport | None = None, 329 disabled_features: Iterable[str] = (), 330 ) -> None: 331 """*disabled_features* are the features an admin switched off on this 332 node (#3037, `ctfy.core.node_features`): :meth:`capabilities` answers 333 ``False`` for each, whatever the node says, so a caller reads the 334 effective value and cannot forget the switch. ``()`` is the raw answer 335 — every platform construction passes the node row's set 336 (`test_every_node_client_carries_the_switches`). 337 338 *transport* is `BaseHttpClient`'s own seam, passed through so a 339 test can drive a real node app over the real client — the hop the 340 fakes on either side of it cannot see. 341 342 *max_retries* is passed through too: a best-effort read or a stop 343 is tried once (#2812), because a retry on a timeout multiplies the 344 one number that has to stay small. 345 346 ⚠️ **A call that starts long work retries only a request that never 347 left** (#3162, :data:`~ctfy.sdk.base.RETRY_UNSENT`): every POST here 348 that names its own HTTP timeout says so per call, because a 349 ``ReadTimeout`` is a request the node has and is still running. 350 ``start_instance`` keeps the default — the node replays it from the 351 instance id. Guarded by `ctfy/tests/test_long_node_work_is_sent_once.py`.""" 352 super().__init__( 353 f"{node_url.rstrip('/')}/api/v1", 354 token, 355 timeout=timeout, 356 max_retries=max_retries, 357 transport=transport, 358 ) 359 self.disabled_features = frozenset(disabled_features)
disabled_features are the features an admin switched off on this
node (#3037, ctfy.core.node_features): capabilities() answers
False for each, whatever the node says, so a caller reads the
effective value and cannot forget the switch. () is the raw answer
— every platform construction passes the node row's set
(test_every_node_client_carries_the_switches).
transport is BaseHttpClient's own seam, passed through so a
test can drive a real node app over the real client — the hop the
fakes on either side of it cannot see.
max_retries is passed through too: a best-effort read or a stop is tried once (#2812), because a retry on a timeout multiplies the one number that has to stay small.
⚠️ A call that starts long work retries only a request that never
left (#3162, ~ctfy.sdk.base.RETRY_UNSENT): every POST here
that names its own HTTP timeout says so per call, because a
ReadTimeout is a request the node has and is still running.
start_instance keeps the default — the node replays it from the
instance id. Guarded by ctfy/tests/test_long_node_work_is_sent_once.py.
363 def start_instance( 364 self, 365 *, 366 challenge_id: str, 367 instance_id: str, 368 ttl: int, 369 answers: dict[str, str], 370 proxy_output_dir: str | None = None, 371 env: dict[str, str] | None = None, 372 publish_gamebox: bool = False, 373 match_network: MatchNetwork | None = None, 374 open_shell_password: str = "", 375 authored_revision: str = "", 376 internet: InternetAccess = InternetAccess.ALLOW, 377 tcp_access: TcpAccess = TcpAccess.TLS_SNI, 378 egress_allow_hosts: list[str] | None = None, 379 resource_budget: ResourceBudget | None = None, 380 compose_up_timeout_s: int = 0, 381 vpn_callback: bool = False, 382 ) -> InstanceStarted: 383 resp = self.request( 384 "POST", 385 "/instances", 386 json={ 387 # #1835: the authored tree's revision this start must run; 388 # a node holding another (or none) fetches it first. 389 "authored_revision": authored_revision, 390 "challenge_id": challenge_id, 391 "instance_id": instance_id, 392 "ttl": ttl, 393 "answers": answers, 394 "proxy_output_dir": proxy_output_dir, 395 "env": env or {}, 396 "publish_gamebox": publish_gamebox, 397 # ``None`` rather than an omitted key: the node's model 398 # defaults to None either way, and sending it explicitly 399 # keeps the body's shape stable across both branches. 400 "match_network": (dataclasses.asdict(match_network) if match_network else None), 401 # Classic-AWD open shell (#1725): the box's starting root 402 # password, empty for every managed / non-AWD start. 403 "open_shell_password": open_shell_password, 404 # #1969: ``deny`` holds the box off the internet; the hosts 405 # are the platform-internal ones it still reaches. 406 "internet": str(internet), 407 # #2082: how a player reaches the box's TCP services. 408 "tcp_access": str(tcp_access), 409 "egress_allow_hosts": list(egress_allow_hosts or []), 410 # The CPU / memory a player-authored box is held to; ``None`` 411 # for the corpus and from an older platform. 412 "resource_budget": ( 413 resource_budget.model_dump() if resource_budget is not None else None 414 ), 415 # #3165: the platform's ``compose_up_timeout_s``, so the node 416 # spends the budget the platform waits on; ``0`` = the node's own. 417 "compose_up_timeout_s": compose_up_timeout_s, 418 # #3598: arm the tunnel's callback forward (one-team boxes only). 419 "vpn_callback": vpn_callback, 420 }, 421 ) 422 _raise_for_node_status(resp) 423 return _parsed(InstanceStarted, resp)
429 def apply_fabric( 430 self, 431 *, 432 index: int, 433 interface: dict[str, Any], 434 match_network: str = "", 435 ) -> FabricStatus: 436 """Put this node on one match's WireGuard fabric. 437 438 ⚠️ **Returns the model, never ``resp.json()``.** The platform 439 reads the verdict field by field, and on a dict a renamed field 440 is ``None`` — falsy — which reads as "the arena did not open", 441 so a wire change would quietly report every node as broken. 442 443 Returns the node's verdict rather than raising on a refusal: the 444 route answers **200 with a body** precisely so that "this node is 445 unreachable" and "this node rejected the plan" stay different 446 facts, and a caller fanning out over an arena needs to tell them 447 apart — one is waited on, the other is looked at. 448 449 *match_network* lets the node check the tunnel landed in the 450 namespace its boxes are in, and open the bridge's one hole. It is 451 the platform's own fact (`awd_network.network_name`), so the node 452 is told rather than guessing. 453 """ 454 resp = self.request( 455 "POST", 456 "/fabric", 457 json={ 458 "index": index, 459 "interface": interface, 460 "match_network": match_network, 461 }, 462 ) 463 resp.raise_for_status() 464 return _parsed(FabricStatus, resp)
Put this node on one match's WireGuard fabric.
⚠️ Returns the model, never resp.json(). The platform
reads the verdict field by field, and on a dict a renamed field
is None — falsy — which reads as "the arena did not open",
so a wire change would quietly report every node as broken.
Returns the node's verdict rather than raising on a refusal: the route answers 200 with a body precisely so that "this node is unreachable" and "this node rejected the plan" stay different facts, and a caller fanning out over an arena needs to tell them apart — one is waited on, the other is looked at.
match_network lets the node check the tunnel landed in the
namespace its boxes are in, and open the bridge's one hole. It is
the platform's own fact (awd_network.network_name), so the node
is told rather than guessing.
466 def probe_fabric( 467 self, 468 *, 469 index: int, 470 peers: list[dict[str, str]], 471 mtu: int = 0, 472 ) -> FabricProbeReport: 473 """Ask named peers the three link questions. Applies nothing. 474 475 ⚠️ **Returns the model, never ``resp.json()``** — same reason 476 `apply_fabric` gives: on a dict a renamed field reads as falsy, 477 which here means "your tunnel is down" about a wire change. 478 """ 479 resp = self.request( 480 "POST", 481 "/fabric/probe", 482 json={"index": index, "peers": peers, "mtu": mtu}, 483 ) 484 resp.raise_for_status() 485 return _parsed(FabricProbeReport, resp)
Ask named peers the three link questions. Applies nothing.
⚠️ Returns the model, never resp.json() — same reason
apply_fabric gives: on a dict a renamed field reads as falsy,
which here means "your tunnel is down" about a wire change.
487 def remove_fabric(self, *, index: int, match_network: str = "") -> FabricStatus: 488 """Take this node off one match's fabric and close its hole. 489 490 ⚠️ *match_network* is what lets the node resolve the bridge and 491 delete the ``DOCKER-USER`` rules by name. Without it the tunnel 492 goes and the hole stays — open on whatever docker gives that 493 bridge name next. 494 """ 495 resp = self.request( 496 "DELETE", 497 f"/fabric/{index}", 498 params={"match_network": match_network}, 499 ) 500 resp.raise_for_status() 501 return _parsed(FabricStatus, resp)
Take this node off one match's fabric and close its hole.
⚠️ match_network is what lets the node resolve the bridge and
delete the DOCKER-USER rules by name. Without it the tunnel
goes and the hole stays — open on whatever docker gives that
bridge name next.
503 def stop_instance_service(self, instance_id: str, service: str) -> int: 504 """Stop one compose service, leaving the instance running. 505 506 The exercise format's session close (§4b.4). Returns how many 507 containers the node stopped — 0 means the challenge declares no 508 such service, which is a real answer rather than a failure, so 509 the caller can distinguish it from a cut tunnel. 510 """ 511 resp = self.request( 512 "POST", 513 f"/instances/{instance_id}/stop-service", 514 json={"service": service}, 515 ) 516 resp.raise_for_status() 517 body = resp.json() 518 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0
Stop one compose service, leaving the instance running.
The exercise format's session close (§4b.4). Returns how many containers the node stopped — 0 means the challenge declares no such service, which is a real answer rather than a failure, so the caller can distinguish it from a cut tunnel.
520 def capabilities( 521 self, *, harness_admission: bool = False, agent_ingress: bool = False 522 ) -> NodeCapabilities: 523 """What this node can do beyond the original verbs. 524 525 ⚠️ **A 404 is an answer, not an error**: a node from before hold / 526 resume has no such route, and "cannot hold" is exactly what the 527 platform needs to hear -- the caller then falls back to deleting. 528 Any other failure raises, because an unreachable node is not a node 529 that cannot hold. 530 """ 531 # ⚠️ #2356: ``harness_admission`` makes the node prove it can hold 532 # an admitted run, which writes its host firewall — asked only by 533 # the admission paths, never by hold / internet. 534 # #3020: ``agent_ingress`` makes the node converge its listener, 535 # asked only before handing a published target over WireGuard. 536 params = { 537 **({"harness_admission": "true"} if harness_admission else {}), 538 **({"agent_ingress": "true"} if agent_ingress else {}), 539 } 540 resp = self.request("GET", "/capabilities", params=params or None) 541 if resp.status_code == 404: 542 return NodeCapabilities() 543 resp.raise_for_status() 544 return masked_capabilities(_parsed(NodeCapabilities, resp), self.disabled_features)
What this node can do beyond the original verbs.
⚠️ A 404 is an answer, not an error: a node from before hold / resume has no such route, and "cannot hold" is exactly what the platform needs to hear -- the caller then falls back to deleting. Any other failure raises, because an unreachable node is not a node that cannot hold.
546 def create_agent_ingress_peer( 547 self, *, run_id: str, public_key: str, ports: list[int], ttl_s: int 548 ) -> AgentIngressPeer: 549 """Add *run_id*'s peer to the node's agent-ingress listener (#3020). 550 551 Only the public key crosses; the caller keeps the private half. 552 Raises on any non-2xx (the node's refusal is in the detail). 553 """ 554 body = AgentIngressPeerRequest( 555 run_id=run_id, public_key=public_key, ports=ports, ttl_s=ttl_s 556 ) 557 resp = self.request("POST", "/agent-ingress/peers", json=body.model_dump(mode="json")) 558 resp.raise_for_status() 559 return _parsed(AgentIngressPeer, resp)
Add run_id's peer to the node's agent-ingress listener (#3020).
Only the public key crosses; the caller keeps the private half. Raises on any non-2xx (the node's refusal is in the detail).
561 def delete_agent_ingress_peer(self, run_id: str) -> bool: 562 """Revoke *run_id*'s peer; ``False`` when the node held none.""" 563 resp = self.request("DELETE", f"/agent-ingress/peers/{run_id}") 564 resp.raise_for_status() 565 return _parsed(AgentIngressPeerRemoved, resp).removed
Revoke run_id's peer; False when the node held none.
567 def hold_instance(self, instance_id: str, mode: str) -> int: 568 """Pause or stop an instance, removing nothing. Returns containers held.""" 569 resp = self.request("POST", f"/instances/{instance_id}/hold", json={"mode": mode}) 570 resp.raise_for_status() 571 return _parsed(InstanceHeld, resp).count
Pause or stop an instance, removing nothing. Returns containers held.
573 def resume_instance(self, instance_id: str) -> int: 574 """Bring a held instance back. Returns containers brought back.""" 575 resp = self.request("POST", f"/instances/{instance_id}/resume") 576 resp.raise_for_status() 577 return _parsed(InstanceHeld, resp).count
Bring a held instance back. Returns containers brought back.
579 def change_instance_internet( 580 self, instance_id: str, change: InstanceInternetChange 581 ) -> InstanceInternetChanged: 582 """Change a running box's internet verdict (#2067). 583 584 Raises :class:`NodeRequestError` on any refusal, carrying the node's 585 ``code`` (:data:`~ctfy.core.exceptions.NODE_INTERNET_CHANGE_FAILED` 586 when its firewall could not converge — the node has then put its 587 record back, so nothing changed). 588 """ 589 resp = self.request( 590 "POST", f"/instances/{instance_id}/internet", json=change.model_dump(mode="json") 591 ) 592 _raise_for_node_status(resp) 593 return _parsed(InstanceInternetChanged, resp)
Change a running box's internet verdict (#2067).
Raises NodeRequestError on any refusal, carrying the node's
code (~ctfy.core.exceptions.NODE_INTERNET_CHANGE_FAILED
when its firewall could not converge — the node has then put its
record back, so nothing changed).
631 def smoke_progress(self, run_id: str, since: int = 0) -> NodeSmokeProgress | None: 632 """The steps and lines a running smoke has produced since *since* (#2145). 633 634 ``None`` when the node holds no feed for *run_id* — a node older than 635 the feed, or a run that never started — which a watcher reads as 636 *unwatched*. Any other failure raises: the caller decides that a 637 watcher's trouble must never fail the run it watches. 638 """ 639 # ⚠️ A short timeout of its own: this is read once a second beside a 640 # run that may be minutes long, and a read that hangs on a busy worker 641 # must not hold the watcher past the run it watches. 642 resp = self.request( 643 "GET", 644 f"/admin/authored/smoke/{run_id}/progress", 645 params={"since": since}, 646 timeout=10, 647 ) 648 if resp.status_code == 404: 649 return None 650 resp.raise_for_status() 651 return _parsed(NodeSmokeProgress, resp)
The steps and lines a running smoke has produced since since (#2145).
None when the node holds no feed for run_id — a node older than
the feed, or a run that never started — which a watcher reads as
unwatched. Any other failure raises: the caller decides that a
watcher's trouble must never fail the run it watches.
653 def smoke_entrance(self, run_id: str) -> NodeSmokeEntrance: 654 """The player's entrance to the smoke box held for *run_id* (#2819 W2). 655 656 ``pending`` / ``ready`` / ``gone``; a 404 (a node older than the 657 route) raises, which the caller reads as *this node cannot hold*. 658 """ 659 resp = self.request("GET", f"/admin/authored/smoke/{run_id}/entrance", timeout=15) 660 resp.raise_for_status() 661 return _parsed(NodeSmokeEntrance, resp)
The player's entrance to the smoke box held for run_id (#2819 W2).
pending / ready / gone; a 404 (a node older than the
route) raises, which the caller reads as this node cannot hold.
663 def post_smoke_exploit(self, run_id: str, outcome: NodeSmokeExploitOutcome) -> bool: 664 """Hand the held smoke box its exploit outcome (#2819 W2). 665 666 ``True`` when the node took it; ``False`` when it holds no box for 667 *run_id* any more (it tore down on its own timeout) or had one. 668 """ 669 resp = self.request( 670 "POST", 671 f"/admin/authored/smoke/{run_id}/exploit", 672 json=outcome.model_dump(mode="json"), 673 timeout=30, 674 # First outcome wins on the node, so a resend is harmless; but a 675 # read timeout is a post that may have landed (#3162). 676 retry_on=RETRY_UNSENT, 677 ) 678 if resp.status_code == 404: 679 return False 680 resp.raise_for_status() 681 return bool(resp.json().get("taken"))
Hand the held smoke box its exploit outcome (#2819 W2).
True when the node took it; False when it holds no box for
run_id any more (it tore down on its own timeout) or had one.
683 def harness_log(self, run_id: str, after: int = 0) -> NodeAgentLog | None: 684 """An agent run's console lines numbered above *after* (#2401). 685 686 ``None`` when the node holds no console for *run_id* — a node older 687 than the feed, or a run that never started there — which a watcher 688 reads as *unwatched*. Any other failure raises: the caller decides 689 that a watcher's trouble must never fail the run it watches. 690 """ 691 # ⚠️ A short timeout of its own, as ``smoke_progress``: read once a 692 # second beside a run that may be hours long. 693 resp = self.request( 694 "GET", f"/harness/runs/{run_id}/log", params={"after": after}, timeout=10 695 ) 696 if resp.status_code == 404: 697 return None 698 resp.raise_for_status() 699 return _parsed(NodeAgentLog, resp)
An agent run's console lines numbered above after (#2401).
None when the node holds no console for run_id — a node older
than the feed, or a run that never started there — which a watcher
reads as unwatched. Any other failure raises: the caller decides
that a watcher's trouble must never fail the run it watches.
701 def harness_result(self, run_id: str) -> HarnessRunResult | None: 702 """What the node knows of a run's harness call (#3021). 703 704 ``None`` when the node has no such route — a node older than the 705 result store, which can never return a run's outcome after its call 706 is gone. ``state="unknown"`` is the node answering that it holds 707 nothing for *run_id*. Any other failure raises: an unreachable node 708 is neither of those, and the caller bounds how long it waits on one. 709 """ 710 resp = self.request("GET", f"/harness/runs/{run_id}/result", timeout=30) 711 if resp.status_code == 404: 712 return None 713 resp.raise_for_status() 714 return _parsed(HarnessRunResult, resp)
What the node knows of a run's harness call (#3021).
None when the node has no such route — a node older than the
result store, which can never return a run's outcome after its call
is gone. state="unknown" is the node answering that it holds
nothing for run_id. Any other failure raises: an unreachable node
is neither of those, and the caller bounds how long it waits on one.
716 def put_generated_range(self, push: NodeRangePush) -> NodeRangeResult: 717 """Ask the node to build a generated range from its scenario. 718 719 ⚠️ **The scenario travels, not the estate.** The corpus is 720 mounted on the node and the compiler ships inside it, so 70-odd 721 rendered files never cross this API — and the corpus commit that 722 rides along is what stops one scenario becoming two different 723 estates under one id across a fleet. 724 725 The node answers **200 with ``ok: false``** for a refusal, so a 726 node that declined and a node that could not be reached stay 727 different facts; only the second raises here. 728 """ 729 resp = self.request("POST", "/admin/ranges", json=push.model_dump(mode="json")) 730 resp.raise_for_status() 731 return _parsed(NodeRangeResult, resp)
Ask the node to build a generated range from its scenario.
⚠️ The scenario travels, not the estate. The corpus is mounted on the node and the compiler ships inside it, so 70-odd rendered files never cross this API — and the corpus commit that rides along is what stops one scenario becoming two different estates under one id across a fleet.
The node answers 200 with ok: false for a refusal, so a
node that declined and a node that could not be reached stay
different facts; only the second raises here.
733 def verify_generated_range( 734 self, push: NodeRangeVerifyPush, *, timeout: int | None = None 735 ) -> NodeRangeVerifyResult: 736 """Ask the node to build a scenario, solve it, and take it down. 737 738 ⚠️ **The longest call in this API**, so the caller passes its own 739 timeout: the node's budget is ``compose_timeout_s + 740 solve_timeout_s`` and a client that used the default would give 741 up while the node was still building — then retry, and start a 742 second estate beside the first. 743 744 ⚠️ A client timeout does **not** leave a range running: the node 745 tears down in its own ``finally``. What is lost is the answer, 746 not the host. 747 748 The node answers **200 with an ``error``** for a refusal, the 749 same split ``put_generated_range`` uses; only an unreachable node 750 raises. 751 """ 752 kwargs: dict[str, Any] = {"json": push.model_dump(mode="json")} 753 if timeout is not None: 754 # httpx takes a per-request override; the client-wide value 755 # stays whatever the caller constructed this with. 756 kwargs["timeout"] = timeout 757 resp = self.request("POST", "/admin/ranges/verify", retry_on=RETRY_UNSENT, **kwargs) 758 resp.raise_for_status() 759 return _parsed(NodeRangeVerifyResult, resp)
Ask the node to build a scenario, solve it, and take it down.
⚠️ The longest call in this API, so the caller passes its own
timeout: the node's budget is compose_timeout_s +
solve_timeout_s and a client that used the default would give
up while the node was still building — then retry, and start a
second estate beside the first.
⚠️ A client timeout does not leave a range running: the node
tears down in its own finally. What is lost is the answer,
not the host.
The node answers 200 with an error for a refusal, the
same split put_generated_range uses; only an unreachable node
raises.
761 def cancel_generated_range_verify(self, run_id: str) -> bool: 762 """Tell the node to stop a verification it is running. 763 764 ⚠️ **A miss is success, not a 404 to report.** The cancel races 765 the run's own finish, so "no such run" means the run already 766 ended — which is what the operator asked for. The node answers 767 ``{"cancelled": false}`` for that case rather than raising, and 768 this returns it so a caller that wants to say "it had already 769 finished" can. 770 """ 771 resp = self.request("POST", f"/admin/ranges/verify/{run_id}/cancel") 772 resp.raise_for_status() 773 body = resp.json() 774 return bool(body.get("cancelled"))
Tell the node to stop a verification it is running.
⚠️ A miss is success, not a 404 to report. The cancel races
the run's own finish, so "no such run" means the run already
ended — which is what the operator asked for. The node answers
{"cancelled": false} for that case rather than raising, and
this returns it so a caller that wants to say "it had already
finished" can.
776 def rescan_challenges(self) -> ChallengeReloadResult: 777 """Tell the node to drop its spec cache and re-scan challenges_dir. 778 779 Returns ``{total, added, removed}`` so the platform can report 780 the per-node outcome of a cluster-wide rescan.""" 781 resp = self.request("POST", "/admin/rescan-challenges") 782 resp.raise_for_status() 783 return _parsed(ChallengeReloadResult, resp)
Tell the node to drop its spec cache and re-scan challenges_dir.
Returns {total, added, removed} so the platform can report
the per-node outcome of a cluster-wide rescan.
787 def build_challenge( 788 self, 789 challenge_id: str, 790 *, 791 authored_revision: str = "", 792 resource_budget: ResourceBudget | None = None, 793 ) -> ChallengeBuildState: 794 """Ask the node to pre-build images for *challenge_id*. 795 796 Fires-and-returns: the node persists ``status="building"`` and 797 spawns a daemon thread; the body returned here is that initial 798 state row. Polling :meth:`get_build_state` is how the platform 799 learns when it lands on ``built`` / ``failed``. *authored_revision* 800 is #1835's: the tree the build must be of, fetched if not held. 801 """ 802 params = {"authored_revision": authored_revision} if authored_revision else None 803 # #2504: an authored tree pre-builds under this budget, or not at all. 804 kwargs: dict[str, Any] = {} 805 if resource_budget is not None: 806 kwargs["json"] = {"resource_budget": resource_budget.model_dump()} 807 resp = self.request( 808 "POST", f"/admin/challenges/{challenge_id}/build", params=params, **kwargs 809 ) 810 _raise_for_node_status(resp) 811 return _parsed(ChallengeBuildState, resp)
Ask the node to pre-build images for challenge_id.
Fires-and-returns: the node persists status="building" and
spawns a daemon thread; the body returned here is that initial
state row. Polling get_build_state() is how the platform
learns when it lands on built / failed. authored_revision
is #1835's: the tree the build must be of, fetched if not held.
813 def build_all_challenges( 814 self, 815 challenge_ids: list[str] | None = None, 816 *, 817 resource_budget: ResourceBudget | None = None, 818 ) -> BuildAllQueued: 819 """Queue background pre-build on the node. 820 821 With ``challenge_ids=None`` the node builds every spec it knows. 822 With an explicit list (the platform scoping a bulk build to a 823 competition's challenge set) only those are built. Returns 824 ``{queued, skipped_built, skipped_in_progress}`` so the platform 825 can report per-node what got picked up. Sequential on the node 826 side — no fan-out across the corpus. 827 """ 828 kwargs: dict[str, Any] = {} 829 body: dict[str, Any] = {} 830 if challenge_ids is not None: 831 body["challenge_ids"] = challenge_ids 832 if resource_budget is not None: 833 # #2504: what an authored id in the scope pre-builds under. 834 body["resource_budget"] = resource_budget.model_dump() 835 if body: 836 kwargs["json"] = body 837 resp = self.request("POST", "/admin/challenges/build-all", **kwargs) 838 _raise_for_node_status(resp) 839 return _parsed(BuildAllQueued, resp)
Queue background pre-build on the node.
With challenge_ids=None the node builds every spec it knows.
With an explicit list (the platform scoping a bulk build to a
competition's challenge set) only those are built. Returns
{queued, skipped_built, skipped_in_progress} so the platform
can report per-node what got picked up. Sequential on the node
side — no fan-out across the corpus.
841 def build_push_challenge( 842 self, 843 challenge_id: str, 844 *, 845 push_ticket: str = "", 846 deadline_s: int = 0, 847 cleanup: bool = False, 848 cache_max_bytes: int = 0, 849 confine_network: bool = False, 850 authored_revision: str = "", 851 run_id: str = "", 852 resource_budget: ResourceBudget | None = None, 853 ) -> ChallengeFreezeResult: 854 """Build one challenge's ``build:`` services and freeze them to the registry. 855 856 Layer 2 producer (P0). **Blocks** until the challenge is built + 857 pushed (or skipped as already frozen), unlike the fire-and-return 858 :meth:`build_challenge`. ⚠️ *deadline_s* bounds the node's whole 859 freeze (#3167, `ctfy.core.freeze_budget`; ``0`` sends the node's own 860 default), and the HTTP wait is derived from it — 861 `freeze_client_wait_s`, past the node's own answer — so the client 862 never abandons a freeze the node is still running. Sent once: a 863 ``ReadTimeout`` is a request the node has (#3162). Returns the per-service freeze result; 864 the platform's ``challenge_build_push`` task calls this one 865 challenge at a time. *push_ticket* is the platform's short-lived 866 registry credential the node's ``docker push`` authenticates with 867 — the node runs it in a container with no ambient login. 868 *cleanup* asks the node to remove what the build left and prune its 869 build cache to *cache_max_bytes* afterwards, and *confine_network* 870 keeps every ``RUN`` off the host's network (both the freeze pool, #1827). 871 *run_id* names this call for :meth:`cancel_build_push` and 872 :meth:`build_push_progress` while it is in flight (#1949). 873 """ 874 resp = self.request( 875 "POST", 876 f"/admin/challenges/{challenge_id}/build-push", 877 json={ 878 "push_ticket": push_ticket, 879 "cleanup": cleanup, 880 "cache_max_bytes": cache_max_bytes, 881 "confine_network": confine_network, 882 "authored_revision": authored_revision, 883 "run_id": run_id, 884 "deadline_s": deadline_s, 885 # #2504: the build limits an authored tree is frozen under; 886 # a node refuses one that arrives without them. 887 "resource_budget": ( 888 resource_budget.model_dump() if resource_budget is not None else None 889 ), 890 }, 891 timeout=freeze_client_wait_s(deadline_s or freeze_deadline_s()), 892 retry_on=RETRY_UNSENT, 893 ) 894 _raise_for_node_status(resp) 895 return _parsed(ChallengeFreezeResult, resp)
Build one challenge's build: services and freeze them to the registry.
Layer 2 producer (P0). Blocks until the challenge is built +
pushed (or skipped as already frozen), unlike the fire-and-return
build_challenge(). ⚠️ deadline_s bounds the node's whole
freeze (#3167, ctfy.core.freeze_budget; 0 sends the node's own
default), and the HTTP wait is derived from it —
freeze_client_wait_s, past the node's own answer — so the client
never abandons a freeze the node is still running. Sent once: a
ReadTimeout is a request the node has (#3162). Returns the per-service freeze result;
the platform's challenge_build_push task calls this one
challenge at a time. push_ticket is the platform's short-lived
registry credential the node's docker push authenticates with
— the node runs it in a container with no ambient login.
cleanup asks the node to remove what the build left and prune its
build cache to cache_max_bytes afterwards, and confine_network
keeps every RUN off the host's network (both the freeze pool, #1827).
run_id names this call for cancel_build_push() and
build_push_progress() while it is in flight (#1949).
897 def cancel_build_push(self, run_id: str) -> BuildPushCancelled: 898 """Cancel the freeze :meth:`build_push_challenge` started under *run_id* (#1949). 899 900 Idempotent; ``found`` false means the node holds no such run. 901 """ 902 resp = self.request("POST", "/admin/build-push/cancel", json={"run_id": run_id}) 903 _raise_for_node_status(resp) 904 return _parsed(BuildPushCancelled, resp)
Cancel the freeze build_push_challenge() started under run_id (#1949).
Idempotent; found false means the node holds no such run.
906 def build_push_progress(self, run_id: str) -> BuildPushProgress: 907 """What the freeze running under *run_id* is doing now (#1949).""" 908 resp = self.request("GET", f"/admin/build-push/{run_id}/progress") 909 _raise_for_node_status(resp) 910 return _parsed(BuildPushProgress, resp)
What the freeze running under run_id is doing now (#1949).
912 def get_disk_free(self) -> NodeDiskFree: 913 """Free space on the node's data filesystem, read now (#1827). 914 915 Raises on any failure — including a node predating the route, which 916 answers 404 — and the freeze reads every failure as *cannot tell*, 917 which stops it. 918 """ 919 resp = self.request("GET", "/admin/disk") 920 _raise_for_node_status(resp) 921 return _parsed(NodeDiskFree, resp)
Free space on the node's data filesystem, read now (#1827).
Raises on any failure — including a node predating the route, which answers 404 — and the freeze reads every failure as cannot tell, which stops it.
923 def get_build_state(self) -> BuildStateRows: 924 """Fetch every per-challenge build-state row on this node. 925 926 Returns ``{"rows": [{challenge_id, status, built_at, error}, …]}``. 927 ``status`` is one of ``unbuilt`` / ``building`` / ``built`` / 928 ``failed``; ``unbuilt`` placeholders are synthesised for specs 929 the node has seen but never been asked to build. 930 """ 931 resp = self.request("GET", "/admin/challenges/build-state") 932 _raise_for_node_status(resp) 933 return _parsed(BuildStateRows, resp)
Fetch every per-challenge build-state row on this node.
Returns {"rows": [{challenge_id, status, built_at, error}, …]}.
status is one of unbuilt / building / built /
failed; unbuilt placeholders are synthesised for specs
the node has seen but never been asked to build.
935 def pull_challenge(self, challenge_id: str) -> ChallengePullState: 936 """Ask the node to pre-pull registry images for *challenge_id*. 937 938 Pull-side twin of :meth:`build_challenge`: the node persists 939 ``status="pulling"`` and spawns a daemon thread; poll 940 :meth:`get_pull_state` for the ``pulled`` / ``failed`` landing. 941 """ 942 resp = self.request("POST", f"/admin/challenges/{challenge_id}/pull") 943 _raise_for_node_status(resp) 944 return _parsed(ChallengePullState, resp)
Ask the node to pre-pull registry images for challenge_id.
Pull-side twin of build_challenge(): the node persists
status="pulling" and spawns a daemon thread; poll
get_pull_state() for the pulled / failed landing.
946 def pull_all_challenges(self, challenge_ids: list[str] | None = None) -> PullAllQueued: 947 """Queue background pre-pull on the node. 948 949 With ``challenge_ids=None`` the node pulls every spec it knows; 950 with an explicit list only those (the platform scoping to a 951 competition). Returns ``{queued, skipped_pulled, 952 skipped_in_progress}``. 953 """ 954 kwargs: dict[str, Any] = {} 955 if challenge_ids is not None: 956 kwargs["json"] = {"challenge_ids": challenge_ids} 957 resp = self.request("POST", "/admin/challenges/pull-all", **kwargs) 958 _raise_for_node_status(resp) 959 return _parsed(PullAllQueued, resp)
Queue background pre-pull on the node.
With challenge_ids=None the node pulls every spec it knows;
with an explicit list only those (the platform scoping to a
competition). Returns {queued, skipped_pulled,
skipped_in_progress}.
961 def get_pull_state(self) -> PullStateRows: 962 """Fetch every per-challenge pull-state row on this node. 963 964 Returns ``{"rows": [{challenge_id, status, pulled_at, error}, …]}``. 965 ``status`` is one of ``unpulled`` / ``pulling`` / ``pulled`` / 966 ``failed``; ``unpulled`` placeholders are synthesised for specs 967 the node has seen but never been asked to pull. 968 """ 969 resp = self.request("GET", "/admin/challenges/pull-state") 970 _raise_for_node_status(resp) 971 return _parsed(PullStateRows, resp)
Fetch every per-challenge pull-state row on this node.
Returns {"rows": [{challenge_id, status, pulled_at, error}, …]}.
status is one of unpulled / pulling / pulled /
failed; unpulled placeholders are synthesised for specs
the node has seen but never been asked to pull.
980 def list_instances(self) -> list[NodeInstanceSummary]: 981 """Every instance the node still has bookkeeping for. 982 983 Used by the platform's boot re-adoption pass to decide which 984 durable claims still have containers behind them. ``get_status`` 985 answers the same question one id at a time; asking it per claim 986 would cost one round trip per instance to a node that may be 987 slow or down, on the path that gates startup. 988 """ 989 resp = self.request("GET", "/instances") 990 resp.raise_for_status() 991 return _parsed(NodeInstanceList, resp).items
Every instance the node still has bookkeeping for.
Used by the platform's boot re-adoption pass to decide which
durable claims still have containers behind them. get_status
answers the same question one id at a time; asking it per claim
would cost one round trip per instance to a node that may be
slow or down, on the path that gates startup.
996 def check_health_verbose(self, instance_id: str) -> HealthReading: 997 """Health plus whatever agent-deception telemetry the node read. 998 999 One call, because the platform already polls this endpoint for 1000 every live instance every tick and a second round trip per 1001 instance would be the whole cost of the feature. ``check_health`` 1002 stays a bool for the callers that only ever wanted one. 1003 1004 Never an error, whatever arrives: this rides the health poll, 1005 and telemetry must not be able to mark a healthy instance 1006 unhealthy. 1007 1008 ⚠️ **The two ways this can come back empty are different facts 1009 and used to be one.** An older node sends no ``deception`` key 1010 at all — it *did not say*, which is ``channel=None`` and 1011 authorises nothing. A body this platform cannot parse is 1012 something else: the node did say, and we could not read it. That 1013 is ``unreadable``, the same value the reader gives for a missing 1014 file, because it is the same fact — there is no usable channel 1015 here — arriving through a different door. 1016 1017 The parse failure that matters is version skew in the other 1018 direction: a **newer** node reporting an ``ObservationKind`` this 1019 platform does not have. ``Observation.kind`` is typed, so one 1020 unknown member fails the whole model rather than dropping one 1021 row — which is the right refusal (the node's word is not ours to 1022 edit) and exactly why it must not land as "reported nothing". 1023 """ 1024 resp = self.request("GET", f"/instances/{instance_id}/health") 1025 resp.raise_for_status() 1026 body = resp.json() 1027 raw = body.get("deception") 1028 if not raw: 1029 summary = DeceptionSummary() 1030 else: 1031 try: 1032 summary = DeceptionSummary.model_validate(raw) 1033 except ValidationError as exc: 1034 log.info( 1035 "unreadable deception telemetry from node", 1036 instance_id=instance_id, 1037 error=tail(str(exc), limit=200), 1038 ) 1039 summary = DeceptionSummary(channel="unreadable") 1040 raw_contact = body.get("contact") 1041 if not raw_contact: 1042 contact = ContactReading() 1043 else: 1044 try: 1045 contact = ContactReading.model_validate(raw_contact) 1046 except ValidationError as exc: 1047 log.info( 1048 "unreadable contact telemetry from node", 1049 instance_id=instance_id, 1050 error=tail(str(exc), limit=200), 1051 ) 1052 contact = ContactReading(channel="unreadable") 1053 raw_procs = body.get("new_processes") 1054 # ⚠️ Shape-checked rather than trusted: an older node sends 1055 # nothing and a newer one could send a shape this platform does 1056 # not model, and neither may reach a reader as *a container full 1057 # of intruders*. Anything unreadable is silence, which for a 1058 # signal built to under-report is the honest reading. 1059 procs: dict[str, list[str]] = {} 1060 if isinstance(raw_procs, dict): 1061 for container, names in raw_procs.items(): 1062 if isinstance(container, str) and isinstance(names, list): 1063 procs[container] = [str(n) for n in names] 1064 return HealthReading( 1065 healthy=bool(body.get("is_healthy")), 1066 deception=summary, 1067 contact=contact, 1068 new_processes=procs, 1069 )
Health plus whatever agent-deception telemetry the node read.
One call, because the platform already polls this endpoint for
every live instance every tick and a second round trip per
instance would be the whole cost of the feature. check_health
stays a bool for the callers that only ever wanted one.
Never an error, whatever arrives: this rides the health poll, and telemetry must not be able to mark a healthy instance unhealthy.
⚠️ The two ways this can come back empty are different facts
and used to be one. An older node sends no deception key
at all — it did not say, which is channel=None and
authorises nothing. A body this platform cannot parse is
something else: the node did say, and we could not read it. That
is unreadable, the same value the reader gives for a missing
file, because it is the same fact — there is no usable channel
here — arriving through a different door.
The parse failure that matters is version skew in the other
direction: a newer node reporting an ObservationKind this
platform does not have. Observation.kind is typed, so one
unknown member fails the whole model rather than dropping one
row — which is the right refusal (the node's word is not ours to
edit) and exactly why it must not land as "reported nothing".
1071 def node_health(self) -> dict[str, Any]: 1072 """Liveness + ``{running, capacity}`` for heartbeat.""" 1073 resp = self.request("GET", "/health") 1074 resp.raise_for_status() 1075 body: dict[str, Any] = resp.json() 1076 return body
Liveness + {running, capacity} for heartbeat.
1080 def get_traffic_page( 1081 self, instance_id: str, *, cursor: str = "", limit: int = 0 1082 ) -> InstanceTrafficPage: 1083 """One page of mitmproxy flows; the capture lives on the node's FS. 1084 1085 ⚠️ **The one method that must not use ``_parsed``.** A node from 1086 before paging answers with a bare *list* — it sent the whole 1087 capture and understands no cursor — and a strict 1088 ``model_validate`` turns that supported skew into a raised 1089 request. So the body goes through ``coerce_page``, which already 1090 owns every decision about an unexpected shape, and the caller 1091 gets the model. 1092 1093 This is the same move ``coerce_page`` was written for, one layer 1094 down. Its docstring used to say the parsing belonged 1095 "platform-side … so a route and this client cannot come to 1096 disagree" — and there were *three* platform-side calls doing it. 1097 There is one call now, at the seam that knows the request 1098 cursor, which is what the fallback needs; the routes hold the 1099 type instead of re-deciding its shape. 1100 1101 ⚠️ **An empty ``cursor`` means "from the beginning".** Passing 1102 one on every poll re-reads the whole capture, which is the cost 1103 the paged read exists to remove — arriving through the caller 1104 rather than through the node. 1105 """ 1106 params: dict[str, Any] = {} 1107 if cursor: 1108 params["cursor"] = cursor 1109 if limit > 0: 1110 params["limit"] = limit 1111 resp = self.request("GET", f"/instances/{instance_id}/traffic", params=params) 1112 resp.raise_for_status() 1113 page = coerce_page(resp.json(), cursor) 1114 return InstanceTrafficPage( 1115 flows=page.flows, 1116 cursor=page.cursor, 1117 truncated=page.truncated, 1118 capture=page.capture, 1119 )
One page of mitmproxy flows; the capture lives on the node's FS.
⚠️ The one method that must not use _parsed. A node from
before paging answers with a bare list — it sent the whole
capture and understands no cursor — and a strict
model_validate turns that supported skew into a raised
request. So the body goes through coerce_page, which already
owns every decision about an unexpected shape, and the caller
gets the model.
This is the same move coerce_page was written for, one layer
down. Its docstring used to say the parsing belonged
"platform-side … so a route and this client cannot come to
disagree" — and there were three platform-side calls doing it.
There is one call now, at the seam that knows the request
cursor, which is what the fallback needs; the routes hold the
type instead of re-deciding its shape.
⚠️ An empty cursor means "from the beginning". Passing
one on every poll re-reads the whole capture, which is the cost
the paged read exists to remove — arriving through the caller
rather than through the node.
1121 def get_traffic_witnesses( 1122 self, instance_id: str, *, cursor: str = "", limit: int = 0 1123 ) -> InstanceTrafficWitnesses: 1124 """Who spoke to this box since *cursor*, with no bodies moved. 1125 1126 §7.1's correlation reads one gamebox per team per round. Through 1127 :meth:`get_traffic_page` that is every flow, both bodies 1128 included (~100 kB apiece by ``CLAUDE.md``'s measurement), 1129 pulled across the wire to extract a handful of addresses; the 1130 node reduces instead and this carries the result. 1131 1132 ⚠️ **Strict parsing here, unlike its neighbour, and that is the 1133 difference between an old field and an old route.** 1134 ``get_traffic_page`` is lenient because a node from before 1135 paging answers the *same* path with a bare list, which is 1136 supported skew. This route did not exist on such a node at all, 1137 so the honest answer from one is a 404 — and a lenient parse of 1138 an error body would hand the round loop an empty witness set, 1139 which reads as *nobody was there*. The caller catches the 1140 request error and records the round as unknown. 1141 """ 1142 params: dict[str, Any] = {} 1143 if cursor: 1144 params["cursor"] = cursor 1145 if limit > 0: 1146 params["limit"] = limit 1147 resp = self.request("GET", f"/instances/{instance_id}/traffic-witnesses", params=params) 1148 resp.raise_for_status() 1149 return _parsed(InstanceTrafficWitnesses, resp)
Who spoke to this box since cursor, with no bodies moved.
§7.1's correlation reads one gamebox per team per round. Through
get_traffic_page() that is every flow, both bodies
included (~100 kB apiece by CLAUDE.md's measurement),
pulled across the wire to extract a handful of addresses; the
node reduces instead and this carries the result.
⚠️ Strict parsing here, unlike its neighbour, and that is the
difference between an old field and an old route.
get_traffic_page is lenient because a node from before
paging answers the same path with a bare list, which is
supported skew. This route did not exist on such a node at all,
so the honest answer from one is a 404 — and a lenient parse of
an error body would hand the round loop an empty witness set,
which reads as nobody was there. The caller catches the
request error and records the round as unknown.
1151 def list_containers(self, instance_id: str) -> list[ComposeContainer]: 1152 """Enumerate every container in an instance's compose project. 1153 1154 Backs the admin-shell feature: the platform forwards a 1155 ``GET /admin/instances/{id}/containers`` to the assigned node, 1156 which returns one row per container (challenge services and 1157 platform-injected sidecars alike). The WebSocket reverse-proxy 1158 is opened separately and does not go through ``NodeClient``. 1159 """ 1160 resp = self.request("GET", f"/instances/{instance_id}/containers") 1161 _raise_for_node_status(resp) 1162 return _parsed_list(ComposeContainer, resp)
Enumerate every container in an instance's compose project.
Backs the admin-shell feature: the platform forwards a
GET /admin/instances/{id}/containers to the assigned node,
which returns one row per container (challenge services and
platform-injected sidecars alike). The WebSocket reverse-proxy
is opened separately and does not go through NodeClient.
1164 def run_checker( 1165 self, 1166 instance_id: str, 1167 *, 1168 service: str, 1169 cmd: list[str], 1170 timeout_s: int = DEFAULT_JUDGE_TIMEOUT_S, 1171 ) -> CheckResult: 1172 """Exec an author-supplied checker in a trusted judge sidecar. 1173 1174 Backs the checker / exec-judge feature: the platform forwards a 1175 verify request to the assigned node, which runs ``cmd`` inside the 1176 named sidecar and returns 1177 ``{exit_code, stdout, stderr, timed_out, error}``. 1178 1179 ⚠️ *timeout_s* is the author's, and the node clamps it (#3169): the 1180 clamped budget is what is sent and what the wait is derived from 1181 (`core.judge_budget.platform_wait_s`), so ``0`` no longer waits 10 s 1182 on a node running 30, and ``600`` no longer holds a threadpool slot 1183 for 610 s on a node that stops at 120. Sent once (``RETRY_UNSENT``). 1184 """ 1185 exec_s = judge_exec_s(timeout_s) 1186 resp = self.request( 1187 "POST", 1188 f"/instances/{instance_id}/check", 1189 json={"service": service, "cmd": cmd, "timeout_s": exec_s}, 1190 timeout=judge_platform_wait_s(exec_s), 1191 retry_on=RETRY_UNSENT, 1192 ) 1193 _raise_for_node_status(resp) 1194 return _parsed(CheckResult, resp)
Exec an author-supplied checker in a trusted judge sidecar.
Backs the checker / exec-judge feature: the platform forwards a
verify request to the assigned node, which runs cmd inside the
named sidecar and returns
{exit_code, stdout, stderr, timed_out, error}.
⚠️ timeout_s is the author's, and the node clamps it (#3169): the
clamped budget is what is sent and what the wait is derived from
(core.judge_budget.platform_wait_s), so 0 no longer waits 10 s
on a node running 30, and 600 no longer holds a threadpool slot
for 610 s on a node that stops at 120. Sent once (RETRY_UNSENT).
1196 def run_harness( 1197 self, 1198 *, 1199 image: str, 1200 run_id: str = "", 1201 env: dict[str, str], 1202 timeout_s: int = 1800, 1203 untrusted: bool = False, 1204 network: str = "", 1205 own_network: bool = False, 1206 match_network: str = "", 1207 match_address: str = "", 1208 brief: dict[str, Any] | None = None, 1209 target_instance: str = "", 1210 target_aliases: dict[str, str] | None = None, 1211 target_access: str = "", 1212 vpn_config: str = "", 1213 estate_zones: Sequence[str] = (), 1214 target_endpoints: Sequence[str] = (), 1215 target_hosts: Mapping[str, str] | None = None, 1216 target_datagram_endpoints: Sequence[str] = (), 1217 pull_ticket: str = "", 1218 registry_auth: HarnessRegistryAuth | None = None, 1219 limits: HarnessLimits | None = None, 1220 admission_profile: bool = False, 1221 egress_allow: list[str] | None = None, 1222 internet: bool = True, 1223 rootfs_budget_bytes: int = 0, 1224 unpack_budget_bytes: int = 0, 1225 disk_low_watermark_bytes: int = 0, 1226 ingress: bool = True, 1227 local_ingress: bool = False, 1228 platform_image: bool = False, 1229 image_policy: HarnessImagePolicy | None, 1230 attachments: dict[str, str] | None = None, 1231 keep_work: bool = False, 1232 resume_work: bool = False, 1233 exploit: dict[str, Any] | None = None, 1234 exploit_archive: Path | None = None, 1235 exploit_body: ExploitBody = "", 1236 ) -> HarnessRun: 1237 """Run a one-shot evaluation-harness container on the node. 1238 1239 ``exploit`` (#2819 W2) runs a smoke's reference exploit in the fence 1240 instead of an agent (``HarnessExploit``'s fields); sent only when set. 1241 ``exploit_archive`` is its packed tree on disk (#3628), streamed into 1242 the body (:func:`harness_run_content`) as the node's 1243 ``capabilities().exploit_body`` — passed as *exploit_body* — reads it. 1244 1245 ``image_policy`` (#2608) is **required, with no default**: every 1246 caller says whether this image is a user's (the registry rules the 1247 node re-checks before pulling) or the platform's own (``None``). An 1248 untrusted run without one is refused by the node. 1249 1250 The node ``docker run``s ``image`` with ``env`` injected, waits for it 1251 to exit (bounded by ``timeout_s``), and returns 1252 ``{exit_code, stdout, stderr, timed_out, error}`` — the same shape as 1253 :meth:`run_checker`. The harness writes its JSON rollup to stdout. The 1254 per-call HTTP timeout sits above the node's run budget so the client 1255 doesn't abandon the request before the (long-running) harness returns. 1256 1257 ``untrusted`` runs the image under the node's isolation profile — 1258 off host networking, bounded resources, no capabilities — for an 1259 image the platform did not build. It requires a network: the 1260 node answers 400 without one, because "isolate this" and "I will 1261 not say where the target lives" do not compose. 1262 1263 Any of ``network`` (the target instance's own, when the caller 1264 knows it), ``own_network`` or ``target_instance`` satisfies that. 1265 ⚠️ Most eval dispatches need the second: there the harness 1266 *starts* the target partway through its own run, so at ``docker 1267 run`` time no target network exists and there is no name to 1268 send. The node creates a fresh bridge and removes it afterwards. 1269 1270 ``target_instance`` reverses that ordering, and is what an 1271 `engagement` uses: the platform starts the estate first and names 1272 it here, and the node wires its published containers to the 1273 agent's bridge. ⚠️ An **id**, never a network name — the name is 1274 a fact only the node's daemon can read, and ``docker run`` 1275 *creates* whatever string it is handed, so a platform guessing 1276 one starts a run that reaches nothing. 1277 """ 1278 body: dict[str, Any] = { 1279 "image": image, 1280 "env": env, 1281 "timeout_s": timeout_s, 1282 "untrusted": untrusted, 1283 "network": network, 1284 "own_network": own_network, 1285 "match_network": match_network, 1286 # ⚠️ **The platform-assigned arena address.** The node 1287 # connects the agent to the match network with this 1288 # ``--ip``, so the address is known before the round loop 1289 # asks (§7.1). Empty means "let docker's IPAM pick" — an 1290 # older platform's behaviour, and what keeps a node reading 1291 # this field unchanged for every non-arena dispatch. 1292 "match_address": match_address, 1293 # ⚠️ Sent even when empty, so a node reading it gets the 1294 # same shape either way; the node's default is what makes 1295 # an older platform's dispatch unchanged. 1296 "pull_ticket": pull_ticket, 1297 # #3475: the owner's registry login, sent **only when set**, 1298 # so a node that predates the field sees the body it always did. 1299 **({"registry_auth": registry_auth.model_dump()} if registry_auth is not None else {}), 1300 # ⚠️ ``None`` leaves the node's own defaults in force, which is 1301 # what a dispatch said before the ceilings were settings. 1302 "limits": limits.model_dump() if limits is not None else None, 1303 # ⚠️ Same rule, and empty is a real answer here too: a 1304 # dispatch with no run row (the conformance probe, a dry 1305 # run) has nothing to label, and a label with an empty 1306 # value would make every one of them answer one query. 1307 "run_id": run_id, 1308 # ⚠️ Sent as the already-built manifest. The platform is 1309 # the side that knows the challenge, the competition and 1310 # the run mode; a node deriving its own would be a 1311 # second implementation of a published contract. 1312 "brief": brief, 1313 "target_instance": target_instance, 1314 # ⚠️ **The names the brief published, so they resolve on 1315 # the agent's bridge too.** An estate's hosts answer to a 1316 # per-instance FQDN minted by its own resolver; joined to 1317 # a new network a container answers only to its compose 1318 # *service* name. Sending the mapping is what keeps the 1319 # address the agent was told about true under either 1320 # placement — without it the agent is handed a hostname 1321 # that does not resolve, reaches nothing, and reports an 1322 # empty result, which reads as a model that gave up. 1323 # 1324 # ⚠️ The platform's to send: it computed the surface. A 1325 # node re-deriving it from the rendered compose would be 1326 # a second implementation of the address the brief has 1327 # already promised. 1328 "target_aliases": target_aliases or {}, 1329 # #2550: ``{name: base64}`` for ``/ctfy/work/attachments/``. 1330 # ⚠️ Sent only when there are some, so every other dispatch 1331 # is byte-identical to before. 1332 **({"attachments": attachments} if attachments else {}), 1333 # #2550 restarts: sent only when asked for, like the files. 1334 **({"keep_work": True} if keep_work else {}), 1335 **({"resume_work": True} if resume_work else {}), 1336 # #2861 slice B: the target access the platform read off the 1337 # target's node. ⚠️ Sent only when there is one, so every 1338 # other dispatch is byte-identical to before; and only to a 1339 # node whose ``capabilities().harness_access`` said it reads 1340 # them, or to the target's own node (where an older node's 1341 # local read is still right). 1342 **( 1343 { 1344 "target_access": target_access, 1345 "vpn_config": vpn_config, 1346 "estate_zones": list(estate_zones), 1347 "target_endpoints": list(target_endpoints), 1348 } 1349 if target_access 1350 else {} 1351 ), 1352 # #3020: names → the target node's ingress address, for a 1353 # published target handed over the agent-ingress tunnel. Sent 1354 # only when there are some, and only to a node whose 1355 # ``capabilities().harness_ingress_access`` said it reads them. 1356 **({"target_hosts": dict(target_hosts)} if target_hosts else {}), 1357 # #3446: the published endpoints that are UDP, which the node 1358 # never TCP-probes. Sent only when there are some. 1359 **( 1360 {"target_datagram_endpoints": list(target_datagram_endpoints)} 1361 if target_datagram_endpoints 1362 else {} 1363 ), 1364 # #2356: ⚠️ sent only when asked for, so a dispatch that does 1365 # not ask is byte-identical to an older platform's — and an 1366 # older node, which would ignore the fields, is never sent 1367 # them: the caller checks ``capabilities().harness_admission``. 1368 **( 1369 { 1370 "admission_profile": True, 1371 "egress_allow": list(egress_allow or []), 1372 "internet": internet, 1373 "rootfs_budget_bytes": rootfs_budget_bytes, 1374 "unpack_budget_bytes": unpack_budget_bytes, 1375 "disk_low_watermark_bytes": disk_low_watermark_bytes, 1376 "ingress": ingress, 1377 # #2819 W1, F2: sent only when asked for. 1378 **({"local_ingress": True} if local_ingress else {}), 1379 } 1380 if admission_profile 1381 else {} 1382 ), 1383 "image_policy": image_policy.model_dump() if image_policy is not None else None, 1384 # #2608 N4: only for a row with no owner; see the node's request. 1385 **({"platform_image": True} if platform_image else {}), 1386 **({"exploit": exploit} if exploit is not None else {}), 1387 } 1388 resp = self.request( 1389 "POST", 1390 "/harness/run", 1391 **( 1392 {"json": body} 1393 if exploit_archive is None 1394 else harness_run_content(body, exploit_archive, exploit_body=exploit_body) 1395 ), 1396 timeout=( 1397 timeout_s 1398 # #2819 W2: the exploit's `solution/Dockerfile` builds first. 1399 + (SOLUTION_BUILD_TIMEOUT_S if exploit is not None else 0) 1400 + IMAGE_PULL_TIMEOUT_S 1401 + HARNESS_IMAGE_INSPECT_TIMEOUT_S 1402 + HARNESS_CREATE_TIMEOUT_S 1403 + 30 1404 ), 1405 retry_on=RETRY_UNSENT, 1406 ) 1407 _raise_for_node_status(resp) 1408 return _parsed(HarnessRun, resp)
Run a one-shot evaluation-harness container on the node.
exploit (#2819 W2) runs a smoke's reference exploit in the fence
instead of an agent (HarnessExploit's fields); sent only when set.
exploit_archive is its packed tree on disk (#3628), streamed into
the body (harness_run_content()) as the node's
capabilities().exploit_body — passed as exploit_body — reads it.
image_policy (#2608) is required, with no default: every
caller says whether this image is a user's (the registry rules the
node re-checks before pulling) or the platform's own (None). An
untrusted run without one is refused by the node.
The node docker runs image with env injected, waits for it
to exit (bounded by timeout_s), and returns
{exit_code, stdout, stderr, timed_out, error} — the same shape as
run_checker(). The harness writes its JSON rollup to stdout. The
per-call HTTP timeout sits above the node's run budget so the client
doesn't abandon the request before the (long-running) harness returns.
untrusted runs the image under the node's isolation profile —
off host networking, bounded resources, no capabilities — for an
image the platform did not build. It requires a network: the
node answers 400 without one, because "isolate this" and "I will
not say where the target lives" do not compose.
Any of network (the target instance's own, when the caller
knows it), own_network or target_instance satisfies that.
⚠️ Most eval dispatches need the second: there the harness
starts the target partway through its own run, so at docker
run time no target network exists and there is no name to
send. The node creates a fresh bridge and removes it afterwards.
target_instance reverses that ordering, and is what an
engagement uses: the platform starts the estate first and names
it here, and the node wires its published containers to the
agent's bridge. ⚠️ An id, never a network name — the name is
a fact only the node's daemon can read, and docker run
creates whatever string it is handed, so a platform guessing
one starts a run that reaches nothing.
1410 def cancel_harness(self, *, run_id: str) -> int: 1411 """Stop whatever this node is running for ``run_id``; returns how many. 1412 1413 Until this existed a dispatched container was reclaimed by 1414 **nothing but its own timeout** — ``_harness_timeout``'s docstring 1415 says exactly that — so an operator pressing cancel on a 1416 match-long run was asking for something the platform had no way 1417 to deliver. 1418 1419 ⚠️ **Zero is an ordinary answer, not a failure.** The run may have 1420 finished on its own, been dispatched to a different node, or been 1421 lost to a node restart. A caller that read zero as an error would 1422 report a broken platform every time a cancel arrived a second 1423 late. 1424 """ 1425 resp = self.request("POST", "/harness/cancel", json={"run_id": run_id}) 1426 body = resp.json() 1427 return int(body.get("stopped", 0)) if isinstance(body, dict) else 0
Stop whatever this node is running for run_id; returns how many.
Until this existed a dispatched container was reclaimed by
nothing but its own timeout — _harness_timeout's docstring
says exactly that — so an operator pressing cancel on a
match-long run was asking for something the platform had no way
to deliver.
⚠️ Zero is an ordinary answer, not a failure. The run may have finished on its own, been dispatched to a different node, or been lost to a node restart. A caller that read zero as an error would report a broken platform every time a cancel arrived a second late.
1429 def verify_patch( 1430 self, challenge_id: str, files: dict[str, bytes], *, deadline_s: int 1431 ) -> PatchVerifyResult: 1432 """Build a submitted patch on the node and return its verdict. 1433 1434 ``files`` maps a challenge-relative path to its new bytes; base64 1435 is applied here because a patch target may legitimately be 1436 binary. Returns ``{verdict, detail, applied, steps, error}``. 1437 1438 **An empty ``verdict`` with a populated ``error`` is not a 1439 judgement** — it means the node refused the submission, the 1440 verifier crashed, or the run's deadline ran out. The caller must 1441 retry or retire the lease rather than write a score, since failing 1442 to judge a patch is not the same as judging it unfixed. 1443 1444 ⚠️ *deadline_s* bounds the node's whole run (#3164, 1445 `ctfy.core.patch_budget`), and the HTTP wait is derived from it — 1446 `patch_client_wait_s`, past the node's own answer — so the client 1447 never abandons a request the node is still working on. Sent once: 1448 a ``ReadTimeout`` is a request the node has (#3162). 1449 """ 1450 resp = self.request( 1451 "POST", 1452 "/patches/verify", 1453 json={ 1454 "challenge_id": challenge_id, 1455 "files": { 1456 path: base64.b64encode(content).decode() for path, content in files.items() 1457 }, 1458 "deadline_s": deadline_s, 1459 }, 1460 timeout=patch_client_wait_s(deadline_s), 1461 retry_on=RETRY_UNSENT, 1462 ) 1463 _raise_for_node_status(resp) 1464 return _parsed(PatchVerifyResult, resp)
Build a submitted patch on the node and return its verdict.
files maps a challenge-relative path to its new bytes; base64
is applied here because a patch target may legitimately be
binary. Returns {verdict, detail, applied, steps, error}.
An empty verdict with a populated error is not a
judgement — it means the node refused the submission, the
verifier crashed, or the run's deadline ran out. The caller must
retry or retire the lease rather than write a score, since failing
to judge a patch is not the same as judging it unfixed.
⚠️ deadline_s bounds the node's whole run (#3164,
ctfy.core.patch_budget), and the HTTP wait is derived from it —
patch_client_wait_s, past the node's own answer — so the client
never abandons a request the node is still working on. Sent once:
a ReadTimeout is a request the node has (#3162).
1466 def collect_patch_files( 1467 self, instance_id: str, service: str, paths: list[str] 1468 ) -> dict[str, bytes]: 1469 """Read a player's SSH edits back out of their running box. 1470 1471 ``paths`` are absolute in-container paths the *platform* derived 1472 from the pristine source tree. Returns only what could be read: 1473 a path missing from the reply means the player did not change it, 1474 and the caller falls back to the shipped file rather than 1475 recording a deletion they never made. 1476 """ 1477 resp = self.request( 1478 "POST", 1479 f"/instances/{instance_id}/patch-collect", 1480 json={"service": service, "paths": paths}, 1481 ) 1482 _raise_for_node_status(resp) 1483 body: dict[str, str] = resp.json() 1484 return {path: base64.b64decode(blob) for path, blob in body.items()}
Read a player's SSH edits back out of their running box.
paths are absolute in-container paths the platform derived
from the pristine source tree. Returns only what could be read:
a path missing from the reply means the player did not change it,
and the caller falls back to the shipped file rather than
recording a deletion they never made.
1486 def write_awd_answers(self, boxes: dict[str, dict[str, str]]) -> dict[str, str]: 1487 """Rotate a round's flags into every box of this node, in one call. 1488 1489 ⚠️ **One call for the whole node, never one per box.** §5.2's 1490 capacity red line is 1000 teams x 3 services injected inside 1491 120 s; per-box that is 3000 round trips, batched it is about 1492 fourteen. The signature is the enforcement — a caller cannot 1493 accidentally loop. 1494 1495 Returns ``{instance_id: ""}`` for the boxes written and a reason 1496 for the ones that were not, because one team's unreachable box 1497 must not cost every other team on the node its rotation. An 1498 unrotated box keeps serving last round's flag, which anyone 1499 holding the old value can replay. 1500 """ 1501 resp = self.request("POST", "/awd/answers", json={"boxes": boxes}) 1502 _raise_for_node_status(resp) 1503 result: dict[str, str] = resp.json() 1504 return result
Rotate a round's flags into every box of this node, in one call.
⚠️ One call for the whole node, never one per box. §5.2's capacity red line is 1000 teams x 3 services injected inside 120 s; per-box that is 3000 round trips, batched it is about fourteen. The signature is the enforcement — a caller cannot accidentally loop.
Returns {instance_id: ""} for the boxes written and a reason
for the ones that were not, because one team's unreachable box
must not cost every other team on the node its rotation. An
unrotated box keeps serving last round's flag, which anyone
holding the old value can replay.
1506 def probe_awd_service( 1507 self, 1508 *, 1509 instance_id: str, 1510 service_id: str, 1511 tick: int, 1512 flag: str, 1513 previous_flag: str = "", 1514 previous_flag_id: str = "", 1515 ) -> dict[str, str]: 1516 """Run one round's SLA probes against one box, from outside it. 1517 1518 The flags travel *to* the node: a checker that sourced its 1519 expected value from the box it is checking would pass on any box 1520 that returns whatever it was handed. 1521 """ 1522 resp = self.request( 1523 "POST", 1524 "/awd/probe", 1525 json={ 1526 "instance_id": instance_id, 1527 "service_id": service_id, 1528 "tick": tick, 1529 "flag": flag, 1530 "previous_flag": previous_flag, 1531 "previous_flag_id": previous_flag_id, 1532 }, 1533 ) 1534 _raise_for_node_status(resp) 1535 result: dict[str, str] = resp.json() 1536 return result
Run one round's SLA probes against one box, from outside it.
The flags travel to the node: a checker that sourced its expected value from the box it is checking would pass on any box that returns whatever it was handed.
1538 def attack_awd_box( 1539 self, 1540 *, 1541 instance_id: str, 1542 tick: int, 1543 timeout_s: int = 60, 1544 agent_image: str = "", 1545 counter_flag: str = "", 1546 forensic_marker: str = "", 1547 llm_api_key: str = "", 1548 ) -> AwdAttackResult: 1549 """Run this box's own reference exploit against it, once. 1550 1551 Per **box**, not per service: one `run_exploit` discovers every 1552 answer the challenge declares and prints them all. 1553 1554 ``timeout_s`` is sent because the platform is what knows how long 1555 a round is; the node clamps it, because a container held open for 1556 an hour is the node's problem whoever asked for it. 1557 1558 ``forensic_marker`` is §4.3.1's, carried only by the agent 1559 branch: `build_attack_argv` passes no environment at all, so a 1560 marker on the reference exploit would be the one value that 1561 voids `EXPLOIT007`'s guarantee. 1562 1563 ``agent_image`` + ``counter_flag`` switch the node to §4.2b's 1564 agent attacker. ⚠️ **Both or neither** — the node refuses a half 1565 request rather than falling back to the reference exploit, which 1566 would run a different format than the one configured while the 1567 board looked entirely normal. 1568 """ 1569 resp = self.request( 1570 "POST", 1571 "/awd/attack", 1572 json={ 1573 "instance_id": instance_id, 1574 "tick": tick, 1575 "timeout_s": timeout_s, 1576 "agent_image": agent_image, 1577 "counter_flag": counter_flag, 1578 "forensic_marker": forensic_marker, 1579 "llm_api_key": llm_api_key, 1580 }, 1581 ) 1582 _raise_for_node_status(resp) 1583 return _parsed(AwdAttackResult, resp)
Run this box's own reference exploit against it, once.
Per box, not per service: one run_exploit discovers every
answer the challenge declares and prints them all.
timeout_s is sent because the platform is what knows how long
a round is; the node clamps it, because a container held open for
an hour is the node's problem whoever asked for it.
forensic_marker is §4.3.1's, carried only by the agent
branch: build_attack_argv passes no environment at all, so a
marker on the reference exploit would be the one value that
voids EXPLOIT007's guarantee.
agent_image + counter_flag switch the node to §4.2b's
agent attacker. ⚠️ Both or neither — the node refuses a half
request rather than falling back to the reference exploit, which
would run a different format than the one configured while the
board looked entirely normal.
1585 def get_container_logs(self, instance_id: str) -> str: 1586 """Fetch combined container stdout/stderr for archival.""" 1587 resp = self.request("GET", f"/instances/{instance_id}/container-logs") 1588 resp.raise_for_status() 1589 return str(resp.json().get("logs") or "")
Fetch combined container stdout/stderr for archival.
1591 def get_pcap(self, instance_id: str) -> PcapCapture: 1592 """Fetch the merged tcpdump capture for *instance_id*. 1593 1594 ``data`` is empty when no capture exists (sidecar disabled, 1595 instance never reached the running state, etc.) so callers can 1596 persist conditionally without try/except. 1597 1598 ⚠️ **It also says what the per-instance cap already dropped** 1599 (#1714), off the node's response headers, and ``None`` when the 1600 node did not say — an older node, which is *not reported*, never 1601 a clean capture. 1602 """ 1603 resp = self.request("GET", f"/instances/{instance_id}/pcap") 1604 if resp.status_code == 404: 1605 return PcapCapture(data=b"") 1606 resp.raise_for_status() 1607 return PcapCapture( 1608 data=resp.content, 1609 dropped_bytes=_header_int(resp, CAPTURE_DROPPED_BYTES_HEADER), 1610 dropped_segments=_header_int(resp, CAPTURE_DROPPED_SEGMENTS_HEADER), 1611 )
Fetch the merged tcpdump capture for instance_id.
data is empty when no capture exists (sidecar disabled,
instance never reached the running state, etc.) so callers can
persist conditionally without try/except.
⚠️ It also says what the per-instance cap already dropped
(#1714), off the node's response headers, and None when the
node did not say — an older node, which is not reported, never
a clean capture.
1613 def get_harness_artifact(self, artifact_id: str) -> bytes: 1614 """One finished run's collected archive, or ``b""``. 1615 1616 ⚠️ **Empty rather than an exception for a 404**, following 1617 :meth:`get_pcap`. The node reaps uncollected archives, and a 1618 platform that comes back after a restart is exactly the caller 1619 that meets one that is gone — a state its own record already 1620 describes, not a transport failure. 1621 """ 1622 resp = self.request("GET", f"/harness/artifacts/{artifact_id}") 1623 if resp.status_code == 404: 1624 return b"" 1625 resp.raise_for_status() 1626 return resp.content
One finished run's collected archive, or b"".
⚠️ Empty rather than an exception for a 404, following
get_pcap(). The node reaps uncollected archives, and a
platform that comes back after a restart is exactly the caller
that meets one that is gone — a state its own record already
describes, not a transport failure.
1628 def delete_harness_artifact(self, artifact_id: str) -> bool: 1629 """Tell the node the archive has been stored and can go. 1630 1631 ⚠️ **Never raises on a transport failure**, because it is called 1632 after the bytes are safely in object storage: turning a cleanup 1633 error into the run's error would replace a success with a 1634 janitorial complaint. The node's reaper collects whatever this 1635 misses. 1636 """ 1637 try: 1638 resp = self.request("DELETE", f"/harness/artifacts/{artifact_id}") 1639 except Exception: 1640 return False 1641 return resp.status_code == 200
Tell the node the archive has been stored and can go.
⚠️ Never raises on a transport failure, because it is called after the bytes are safely in object storage: turning a cleanup error into the run's error would replace a success with a janitorial complaint. The node's reaper collects whatever this misses.
1643 def get_agent_runtime(self, instance_id: str) -> AgentRuntime: 1644 """Provider-agnostic runtime hints for attaching an agent (proxy URL, 1645 CA PEM, optional Docker-specific names). Replaces the old 1646 sandbox-network shape.""" 1647 resp = self.request("GET", f"/instances/{instance_id}/agent-runtime") 1648 resp.raise_for_status() 1649 return _parsed(AgentRuntime, resp)
Provider-agnostic runtime hints for attaching an agent (proxy URL, CA PEM, optional Docker-specific names). Replaces the old sandbox-network shape.
1653 def list_instance_attachments(self, instance_id: str) -> AttachmentList: 1654 """List per-instance attachments rendered into the node's workdir. 1655 1656 Backs the platform's per-instance attachment endpoint, which 1657 surfaces the team-specific rendered file listing. 1658 1659 ⚠️ This used to hand back the raw dict, under a docstring saying 1660 "caller projects through :class:`AttachmentList` for typing" — 1661 the node's route already declared that model, so the type existed 1662 and this method's signature was the one place it was dropped. 1663 Projecting *here* means there is one place a malformed answer is 1664 caught rather than one per caller.""" 1665 resp = self.request("GET", f"/instances/{instance_id}/attachments") 1666 resp.raise_for_status() 1667 return _parsed(AttachmentList, resp)
List per-instance attachments rendered into the node's workdir.
Backs the platform's per-instance attachment endpoint, which surfaces the team-specific rendered file listing.
⚠️ This used to hand back the raw dict, under a docstring saying
"caller projects through AttachmentList for typing" —
the node's route already declared that model, so the type existed
and this method's signature was the one place it was dropped.
Projecting here means there is one place a malformed answer is
caught rather than one per caller.
1669 def get_vpn_config(self, instance_id: str) -> bytes: 1670 """Fetch the per-instance VPN client config from the node. 1671 1672 The node reads the backend's client config out of the 1673 instance's VPN service container (generated on first boot by 1674 the base image's bootstrap) and rewrites its endpoint to the 1675 node's public host:port. Returns the body verbatim — the 1676 platform-side route adds the ``Content-Disposition`` header 1677 before re-emitting to the player, because only it knows the 1678 backend and therefore the filename the player needs. 1679 1680 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1681 proxy route catches 404 and re-emits to the player, anything 1682 else is treated as a 502. 1683 """ 1684 resp = self.request("GET", f"/instances/{instance_id}/vpn-config") 1685 resp.raise_for_status() 1686 return resp.content
Fetch the per-instance VPN client config from the node.
The node reads the backend's client config out of the
instance's VPN service container (generated on first boot by
the base image's bootstrap) and rewrites its endpoint to the
node's public host:port. Returns the body verbatim — the
platform-side route adds the Content-Disposition header
before re-emitting to the player, because only it knows the
backend and therefore the filename the player needs.
Raises httpx.HTTPStatusError on non-2xx — the platform's
proxy route catches 404 and re-emits to the player, anything
else is treated as a 502.
1688 def get_vpn_access(self, instance_id: str) -> tuple[bytes, tuple[str, ...] | None]: 1689 """The player's VPN config plus the estate's resolver zones (#2861 B). 1690 1691 The config is :meth:`get_vpn_config`'s, byte for byte; the zones ride 1692 a response header the node adds only when asked. ``None`` for the 1693 zones is a node that did not say (older, or docker unreadable there) 1694 — never "no zones". Raises like :meth:`get_vpn_config`. 1695 """ 1696 resp = self.request( 1697 "GET", f"/instances/{instance_id}/vpn-config", params={"estate_zones": "true"} 1698 ) 1699 resp.raise_for_status() 1700 raw = resp.headers.get("X-Ctfy-Estate-Zones") 1701 return resp.content, (tuple(raw.split()) if raw is not None else None)
The player's VPN config plus the estate's resolver zones (#2861 B).
The config is get_vpn_config()'s, byte for byte; the zones ride
a response header the node adds only when asked. None for the
zones is a node that did not say (older, or docker unreadable there)
— never "no zones". Raises like get_vpn_config().
1703 def download_instance_attachment(self, instance_id: str, filename: str) -> tuple[bytes, str]: 1704 """Download one per-instance attachment as ``(bytes, content_type)``. 1705 1706 Buffers the whole body — attachments are bounded (typical case 1707 is a 10 KB binary or a small text file). For huge captures the 1708 caller should hand the player a CDN URL instead. 1709 1710 Raises ``httpx.HTTPStatusError`` on non-2xx — the platform's 1711 proxy route catches 404 and re-emits to the player, anything 1712 else is a 502. Invalid names or instance keys raise 1713 ``InvalidAttachmentName`` before any request is sent.""" 1714 # The instance is a single route key, never part of the file name. 1715 if component_refusal(instance_id) is not None: 1716 raise InvalidAttachmentName("Invalid attachment instance") 1717 resp = self.request( 1718 "GET", 1719 f"/instances/{quote(instance_id, safe='')}/attachments/{attachment_url_path(filename)}", 1720 ) 1721 resp.raise_for_status() 1722 return resp.content, resp.headers.get("content-type", "application/octet-stream")
Download one per-instance attachment as (bytes, content_type).
Buffers the whole body — attachments are bounded (typical case is a 10 KB binary or a small text file). For huge captures the caller should hand the player a CDN URL instead.
Raises httpx.HTTPStatusError on non-2xx — the platform's
proxy route catches 404 and re-emits to the player, anything
else is a 502. Invalid names or instance keys raise
InvalidAttachmentName before any request is sent.