ctfy.sdk
Python SDK for the ctfy platform.
Drives the platform's /api/v1/* REST API from Python with typed Pydantic
returns and auto-retry on transient errors. Two clients, split by audience —
the same line the ctfy / ctfy-admin CLI binaries draw:
~ctfy.sdk.client.PlatformClient— the player client. This is what agents and players want. Methods are grouped into resource namespaces (client.teams,client.instances, …) plus a per-competition handle viaclient.competition(id).~ctfy.sdk.admin.AdminClient— the operator client (/api/v1/admin/*and fleet management). Reached viaclient.adminorAdminClient.connect(). Kept separate so the player reference never surfaces admin endpoints they can't call.
Install
The full ctfy package pulls in the server too. For an agent /
harness that only needs the client, use the client extra::
pip install "ctfy[client]"
Authenticate
Sign in to the platform in the browser, then go to Settings → API
tokens and mint a fine-grained token (prefix pf_). These tokens
launch instances and submit answers on the team's behalf but cannot
mint more tokens, re-link OAuth providers, or change team
membership — so a leaked token never costs you the account.
Export it as CTFY_TOKEN for the CLI / MCP server, or pass it
directly to PlatformClient.
Quick start
End-to-end: discover a competition, register, list its challenges, launch one, read the attack surface, submit a captured flag::
from ctfy.sdk import PlatformClient
client = PlatformClient("https://ctfy.example.com", token="pf_xxx")
# 1) Find a running competition
comps = client.competitions.list(phase="running")
comp = comps[0]
print(comp.id, comp.title)
# 2) Scope to the competition, then register Solo (skip if already on a
# team: inspect ``client.me.get().competition_teams`` first)
comp_api = client.competition(comp.id)
team = comp_api.register(mode="solo")
print(team.id)
# 3) List the challenges scoped to this competition (curated order)
challenges = comp_api.challenges()
for ch in challenges:
print(f" {ch.id} [{ch.category.value}/{ch.difficulty}] {ch.name}")
# 4) Launch the first challenge — blocks until ready
ready = client.instances.start(
challenges[0].id, competition_id=comp.id
)
print(f"instance {ready.id}")
# 5) Read the attack surface (services + credentials, plus VPN for
# engagement-mode challenges)
for svc in ready.surface.services:
print(f" [{svc.service_type.value}] {svc.url}")
if svc.credentials:
print(f" {svc.credentials.username}/{svc.credentials.password}")
if ready.surface.vpn:
print(f" VPN: {ready.surface.vpn.host}:{ready.surface.vpn.port}")
# 6) Submit a captured flag (oracle-probe via
# ``client.submissions.verify()`` first if you don't want to burn
# an audit row)
result = client.submissions.submit(ready.id, "FLAG{your_flag_here}")
print(f"correct={result.correct} solved={result.challenge_fully_solved}")
# 7) Tear down (or let TTL expire — default 24h, admin-tunable)
client.instances.stop(ready.id)
A runnable, interactive copy of this script lives at
examples/quickstart.py.
Player surface
Global / account namespaces on ~ctfy.sdk.client.PlatformClient:
client.teams/client.users— public team + user profile reads.client.me— the caller's profile, inbox, account export/delete, achievements, solve + milestone progress.client.auth— password register/login, OAuth identities, API token CRUD, sign-in discovery.client.competitions— discover competitions (list/get).client.challenges— global catalog, attachments, facets, feedback chips.client.instances—start(blocks until ready),status,stop,renew,list(by instance id; the competition is inferred).client.submissions—submit(graded),verify(oracle probe, no record),list, and QA challenges.client.achievements/client.activities/client.nodes— public badge catalog, activity log, worker-node list.
Per-competition scope — client.competition(id) returns a
~ctfy.sdk.competition.Competition handle for the operations that are
inherently competition-scoped, so competition_id is named once:
comp.register(mode="solo" | "create" | "join", …)— get on a team.comp.team— your team:rename/leave/kick, pluscomp.team.invites(codes + email invites) andcomp.team.requests(approve / reject join requests).comp.challenges()/comp.search_teams()and the standings (comp.scoreboard()/score_history/score_distribution/solve_matrix/challenge_breakdown).
Top-level convenience methods stay flat: client.health(),
client.get_meta(), client.cluster_info(), client.events(),
client.check_server_compatibility().
Admin surface
client.admin (an ~ctfy.sdk.admin.AdminClient) carries the
operator endpoints, grouped the same way: admin.users,
admin.competitions, admin.announcements, admin.achievements,
admin.challenges, admin.instances, admin.records (instance
forensics), admin.nodes, admin.observability, admin.settings,
admin.competition_admins. Operator tooling without a player client can use
AdminClient.connect(url, token=...).
Realtime
~~~~
PlatformClient.events() yields an auto-reconnecting
~ctfy.sdk.events.EventStream over the SSE endpoint —
solve broadcasts, instance state changes, scoreboard refreshes.
See also
PlatformClient— the player client; every namespace method has full docstrings.AdminClient— the operator client.ctfy.server.models— the typed response shapes (ChallengeInfo,InstanceInfo,SubmissionResponse, …) that SDK methods return. Re-using the server's Pydantic models means the wire shape can never drift between the two sides.<platform>/docs— auto-generated FastAPI Swagger UI for the raw REST API (language-agnostic).<platform>/api/v1/mcp/— streamable-HTTP MCP endpoint with the same operations as MCP tools, if the agent speaks MCP instead of Python.~ctfy.sdk.node_client.NodeClient— separate client for worker-node ↔ platform RPCs; not what agent harnesses want.
1"""Python SDK for the ctfy platform. 2 3Drives the platform's ``/api/v1/*`` REST API from Python with typed Pydantic 4returns and auto-retry on transient errors. Two clients, split by audience — 5the same line the ``ctfy`` / ``ctfy-admin`` CLI binaries draw: 6 7- :class:`~ctfy.sdk.client.PlatformClient` — the **player** client. This is 8 what agents and players want. Methods are grouped into resource namespaces 9 (``client.teams``, ``client.instances``, …) plus a per-competition handle 10 via ``client.competition(id)``. 11- :class:`~ctfy.sdk.admin.AdminClient` — the **operator** client 12 (``/api/v1/admin/*`` and fleet management). Reached via ``client.admin`` or 13 :meth:`AdminClient.connect`. Kept separate so the player reference never 14 surfaces admin endpoints they can't call. 15 16Install 17------- 18 19The full ``ctfy`` package pulls in the server too. For an agent / 20harness that only needs the client, use the ``client`` extra:: 21 22 pip install "ctfy[client]" 23 24Authenticate 25------------ 26 27Sign in to the platform in the browser, then go to **Settings → API 28tokens** and mint a fine-grained token (prefix ``pf_``). These tokens 29launch instances and submit answers on the team's behalf but cannot 30mint more tokens, re-link OAuth providers, or change team 31membership — so a leaked token never costs you the account. 32 33Export it as ``CTFY_TOKEN`` for the CLI / MCP server, or pass it 34directly to :class:`PlatformClient`. 35 36Quick start 37----------- 38 39End-to-end: discover a competition, register, list its challenges, 40launch one, read the attack surface, submit a captured flag:: 41 42 from ctfy.sdk import PlatformClient 43 44 client = PlatformClient("https://ctfy.example.com", token="pf_xxx") 45 46 # 1) Find a running competition 47 comps = client.competitions.list(phase="running") 48 comp = comps[0] 49 print(comp.id, comp.title) 50 51 # 2) Scope to the competition, then register Solo (skip if already on a 52 # team: inspect ``client.me.get().competition_teams`` first) 53 comp_api = client.competition(comp.id) 54 team = comp_api.register(mode="solo") 55 print(team.id) 56 57 # 3) List the challenges scoped to this competition (curated order) 58 challenges = comp_api.challenges() 59 for ch in challenges: 60 print(f" {ch.id} [{ch.category.value}/{ch.difficulty}] {ch.name}") 61 62 # 4) Launch the first challenge — blocks until ready 63 ready = client.instances.start( 64 challenges[0].id, competition_id=comp.id 65 ) 66 print(f"instance {ready.id}") 67 68 # 5) Read the attack surface (services + credentials, plus VPN for 69 # engagement-mode challenges) 70 for svc in ready.surface.services: 71 print(f" [{svc.service_type.value}] {svc.url}") 72 if svc.credentials: 73 print(f" {svc.credentials.username}/{svc.credentials.password}") 74 if ready.surface.vpn: 75 print(f" VPN: {ready.surface.vpn.host}:{ready.surface.vpn.port}") 76 77 # 6) Submit a captured flag (oracle-probe via 78 # ``client.submissions.verify()`` first if you don't want to burn 79 # an audit row) 80 result = client.submissions.submit(ready.id, "FLAG{your_flag_here}") 81 print(f"correct={result.correct} solved={result.challenge_fully_solved}") 82 83 # 7) Tear down (or let TTL expire — default 24h, admin-tunable) 84 client.instances.stop(ready.id) 85 86A runnable, interactive copy of this script lives at 87``examples/quickstart.py``. 88 89Player surface 90-------------- 91 92Global / account namespaces on :class:`~ctfy.sdk.client.PlatformClient`: 93 94- ``client.teams`` / ``client.users`` — public team + user profile reads. 95- ``client.me`` — the caller's profile, inbox, account export/delete, 96 achievements, solve + milestone progress. 97- ``client.auth`` — password register/login, OAuth identities, API token 98 CRUD, sign-in discovery. 99- ``client.competitions`` — discover competitions (``list`` / ``get``). 100- ``client.challenges`` — global catalog, attachments, facets, feedback chips. 101- ``client.instances`` — ``start`` (blocks until ready), ``status``, ``stop``, 102 ``renew``, ``list`` (by instance id; the competition is inferred). 103- ``client.submissions`` — ``submit`` (graded), ``verify`` (oracle probe, 104 no record), ``list``, and QA challenges. 105- ``client.achievements`` / ``client.activities`` / ``client.nodes`` — public 106 badge catalog, activity log, worker-node list. 107 108Per-competition scope — ``client.competition(id)`` returns a 109:class:`~ctfy.sdk.competition.Competition` handle for the operations that are 110*inherently* competition-scoped, so ``competition_id`` is named once: 111 112- ``comp.register(mode="solo" | "create" | "join", …)`` — get on a team. 113- ``comp.team`` — your team: ``rename`` / ``leave`` / ``kick``, plus 114 ``comp.team.invites`` (codes + email invites) and ``comp.team.requests`` 115 (approve / reject join requests). 116- ``comp.challenges()`` / ``comp.search_teams()`` and the standings 117 (``comp.scoreboard()`` / ``score_history`` / ``score_distribution`` / 118 ``solve_matrix`` / ``challenge_breakdown``). 119 120Top-level convenience methods stay flat: ``client.health()``, 121``client.get_meta()``, ``client.cluster_info()``, ``client.events()``, 122``client.check_server_compatibility()``. 123 124Admin surface 125------------- 126 127``client.admin`` (an :class:`~ctfy.sdk.admin.AdminClient`) carries the 128operator endpoints, grouped the same way: ``admin.users``, 129``admin.competitions``, ``admin.announcements``, ``admin.achievements``, 130``admin.challenges``, ``admin.instances``, ``admin.records`` (instance 131forensics), ``admin.nodes``, ``admin.observability``, ``admin.settings``, 132``admin.competition_admins``. Operator tooling without a player client can use 133``AdminClient.connect(url, token=...)``. 134 135Realtime 136~~~~~~~~ 137 138:meth:`PlatformClient.events` yields an auto-reconnecting 139:class:`~ctfy.sdk.events.EventStream` over the SSE endpoint — 140solve broadcasts, instance state changes, scoreboard refreshes. 141 142See also 143-------- 144 145- :class:`PlatformClient` — the player client; every namespace method has 146 full docstrings. 147- :class:`AdminClient` — the operator client. 148- ``ctfy.server.models`` — the typed response shapes 149 (``ChallengeInfo``, ``InstanceInfo``, ``SubmissionResponse``, …) 150 that SDK methods return. Re-using the server's Pydantic models means 151 the wire shape can never drift between the two sides. 152- ``<platform>/docs`` — auto-generated FastAPI Swagger UI for the 153 raw REST API (language-agnostic). 154- ``<platform>/api/v1/mcp/`` — streamable-HTTP MCP endpoint with 155 the same operations as MCP tools, if the agent speaks MCP 156 instead of Python. 157- :class:`~ctfy.sdk.node_client.NodeClient` — separate client for 158 worker-node ↔ platform RPCs; not what agent harnesses want. 159""" 160 161from ctfy.sdk.admin import AdminClient 162from ctfy.sdk.client import PlatformClient 163from ctfy.sdk.node_client import NodeClient 164 165__all__ = ["AdminClient", "NodeClient", "PlatformClient"]
108class AdminClient: 109 """Admin / operator surface, grouped into resource namespaces. 110 111 Namespaces: :attr:`users`, :attr:`competitions`, :attr:`suites`, :attr:`announcements`, 112 :attr:`achievements`, :attr:`challenges`, :attr:`gauntlet`, 113 :attr:`instances`, 114 :attr:`records`, :attr:`nodes`, :attr:`observability`, :attr:`settings`, 115 :attr:`competition_admins`. 116 """ 117 118 def __init__(self, http: BaseHttpClient) -> None: 119 #: Shared transport (the parent PlatformClient when reached via 120 #: ``client.admin``, or an owned client when built via ``connect``). 121 self._http = http 122 123 @classmethod 124 def connect( 125 cls, 126 server_url: str, 127 token: str = "", 128 *, 129 max_retries: int = 2, 130 timeout: int = DEFAULT_CLIENT_TIMEOUT, 131 ) -> AdminClient: 132 """Build an ``AdminClient`` that owns its own transport. 133 134 For operator tooling that doesn't already hold a 135 :class:`PlatformClient`. The returned client is a context manager 136 that closes its transport on exit. 137 """ 138 base = server_url.rstrip("/") 139 http = BaseHttpClient(f"{base}/api/v1", token, timeout=timeout, max_retries=max_retries) 140 return cls(http) 141 142 @cached_property 143 def users(self) -> AdminUsersResource: 144 return AdminUsersResource(self._http) 145 146 @cached_property 147 def competitions(self) -> AdminCompetitionsResource: 148 return AdminCompetitionsResource(self._http) 149 150 @cached_property 151 def suites(self) -> AdminSuitesResource: 152 """A suite through its own door: its own fields only (#2896).""" 153 return AdminSuitesResource(self._http) 154 155 @cached_property 156 def announcements(self) -> AdminAnnouncementsResource: 157 return AdminAnnouncementsResource(self._http) 158 159 @cached_property 160 def changelog(self) -> AdminChangelogResource: 161 return AdminChangelogResource(self._http) 162 163 @cached_property 164 def contact_messages(self) -> AdminContactMessagesResource: 165 """What visitors wrote on the Contact page (#3414).""" 166 return AdminContactMessagesResource(self._http) 167 168 @cached_property 169 def institutions(self) -> AdminInstitutionsResource: 170 return AdminInstitutionsResource(self._http) 171 172 @cached_property 173 def exclusion_groups(self) -> AdminExclusionGroupsResource: 174 return AdminExclusionGroupsResource(self._http) 175 176 @cached_property 177 def achievements(self) -> AdminAchievementsResource: 178 return AdminAchievementsResource(self._http) 179 180 @cached_property 181 def challenges(self) -> AdminChallengesResource: 182 return AdminChallengesResource(self._http) 183 184 @cached_property 185 def gauntlet(self) -> AdminGauntletResource: 186 return AdminGauntletResource(self._http) 187 188 @cached_property 189 def email(self) -> AdminEmailResource: 190 return AdminEmailResource(self._http) 191 192 @cached_property 193 def ip_location(self) -> AdminIpLocationResource: 194 return AdminIpLocationResource(self._http) 195 196 @cached_property 197 def llm_calls(self) -> AdminLlmCallsResource: 198 return AdminLlmCallsResource(self._http) 199 200 @cached_property 201 def llm_providers(self) -> AdminLlmProvidersResource: 202 return AdminLlmProvidersResource(self._http) 203 204 @cached_property 205 def patches(self) -> AdminPatchesResource: 206 return AdminPatchesResource(self._http) 207 208 @cached_property 209 def reports(self) -> AdminReportsResource: 210 return AdminReportsResource(self._http) 211 212 @cached_property 213 def awd(self) -> AdminAwdResource: 214 return AdminAwdResource(self._http) 215 216 @cached_property 217 def series(self) -> AdminSeriesResource: 218 return AdminSeriesResource(self._http) 219 220 @cached_property 221 def instances(self) -> AdminInstancesResource: 222 return AdminInstancesResource(self._http) 223 224 @cached_property 225 def records(self) -> AdminRecordsResource: 226 return AdminRecordsResource(self._http) 227 228 @cached_property 229 def nodes(self) -> AdminNodesResource: 230 return AdminNodesResource(self._http) 231 232 @cached_property 233 def observability(self) -> AdminObservabilityResource: 234 return AdminObservabilityResource(self._http) 235 236 @cached_property 237 def settings(self) -> AdminSettingsResource: 238 return AdminSettingsResource(self._http) 239 240 @cached_property 241 def competition_admins(self) -> AdminCompetitionAdminsResource: 242 return AdminCompetitionAdminsResource(self._http) 243 244 @cached_property 245 def admin_invites(self) -> AdminAdminInvitesResource: 246 """Invite an address with no account yet to be an administrator.""" 247 return AdminAdminInvitesResource(self._http) 248 249 @cached_property 250 def competition_invites(self) -> AdminCompetitionInvitesResource: 251 return AdminCompetitionInvitesResource(self._http) 252 253 @cached_property 254 def competition_applications(self) -> AdminCompetitionApplicationsResource: 255 """Applications to a private competition, and the verdict on each.""" 256 return AdminCompetitionApplicationsResource(self._http) 257 258 @cached_property 259 def competition_attachments(self) -> AdminCompetitionAttachmentsResource: 260 """A competition's rules / handbook / notice files (#1808).""" 261 return AdminCompetitionAttachmentsResource(self._http) 262 263 @cached_property 264 def competition_boards(self) -> AdminCompetitionBoardsResource: 265 """A competition's extra boards — published and shadow (#1965 G).""" 266 return AdminCompetitionBoardsResource(self._http) 267 268 @cached_property 269 def recap(self) -> AdminRecapResource: 270 """A competition's recap, its publication and its report email (#3023).""" 271 return AdminRecapResource(self._http) 272 273 @cached_property 274 def challenge_schedule(self) -> AdminChallengeScheduleResource: 275 """When each challenge of a competition appears and shuts (#2093).""" 276 return AdminChallengeScheduleResource(self._http) 277 278 @cached_property 279 def release_plan(self) -> AdminReleasePlanResource: 280 """Waves, per-challenge rules and hints: drafts, publish, release (#2093, #2101).""" 281 return AdminReleasePlanResource(self._http) 282 283 @cached_property 284 def env_sharing(self) -> AdminEnvSharingResource: 285 """How many teams stand on one environment, the groups behind it and 286 the health of the shared environments (#2129 B).""" 287 return AdminEnvSharingResource(self._http) 288 289 @cached_property 290 def machines(self) -> AdminMachinesResource: 291 """Machine logins handed to teams, captain-only (#2132).""" 292 return AdminMachinesResource(self._http) 293 294 @cached_property 295 def messages(self) -> AdminMessagesResource: 296 """Site messages from an event's organisers or the platform (#2073).""" 297 return AdminMessagesResource(self._http) 298 299 @cached_property 300 def prewarm(self) -> AdminPrewarmResource: 301 """Whether a competition's images are warm on its nodes (#2129).""" 302 return AdminPrewarmResource(self._http) 303 304 @cached_property 305 def competition_topics(self) -> AdminCompetitionTopicsResource: 306 """A competition's scheduled topics, released by the clock (#1965).""" 307 return AdminCompetitionTopicsResource(self._http) 308 309 @cached_property 310 def registrations(self) -> AdminRegistrationsResource: 311 """Entrant roster, eligibility review, and CSV export.""" 312 return AdminRegistrationsResource(self._http) 313 314 @cached_property 315 def teams(self) -> AdminTeamsResource: 316 """Enforcement against a squad — disqualify and reinstate. 317 318 Separate from ``registrations`` on purpose: that one rules on 319 eligibility (which decides prizes), this one decides whether the 320 team is in the event at all. 321 """ 322 return AdminTeamsResource(self._http) 323 324 @cached_property 325 def challenge_stats(self) -> AdminChallengeStatsResource: 326 """How players did against an event's challenges: the organiser's 327 table and the single-challenge reading (#2146).""" 328 return AdminChallengeStatsResource(self._http) 329 330 @cached_property 331 def risk(self) -> AdminRiskResource: 332 """Risk control: the case queue (organisers) and an account's sealed 333 sightings (platform administrators). Detection reports; people decide.""" 334 return AdminRiskResource(self._http) 335 336 @cached_property 337 def tasks(self) -> AdminTasksResource: 338 return AdminTasksResource(self._http) 339 340 @cached_property 341 def scheduled_jobs(self) -> AdminScheduledJobsResource: 342 return AdminScheduledJobsResource(self._http) 343 344 @cached_property 345 def authored_challenges(self) -> AdminAuthoredChallengesResource: 346 """The review queue for player-authored challenges.""" 347 return AdminAuthoredChallengesResource(self._http) 348 349 @cached_property 350 def authoring_reviewers(self) -> AdminAuthoringReviewersResource: 351 """Who may rule on one competition's uploads (super-admin).""" 352 return AdminAuthoringReviewersResource(self._http) 353 354 @cached_property 355 def competition_authored_challenges(self) -> AdminCompetitionAuthoredChallengesResource: 356 """One competition's uploads, for its delegated reviewer: read, 357 audit and rule — never publish.""" 358 return AdminCompetitionAuthoredChallengesResource(self._http) 359 360 @cached_property 361 def llm_models(self) -> AdminLlmModelsResource: 362 return AdminLlmModelsResource(self._http) 363 364 @cached_property 365 def eval_vendors(self) -> AdminEvalVendorsResource: 366 return AdminEvalVendorsResource(self._http) 367 368 @cached_property 369 def eval_harnesses(self) -> AdminEvalHarnessesResource: 370 return AdminEvalHarnessesResource(self._http) 371 372 @property 373 def eval_allowances(self) -> AdminEvalAllowancesResource: 374 return AdminEvalAllowancesResource(self._http) 375 376 @property 377 def registry(self) -> AdminRegistryResource: 378 """Registry storage: the usage report and the manual reclaim.""" 379 return AdminRegistryResource(self._http) 380 381 @cached_property 382 def eval_runs(self) -> AdminEvalRunsResource: 383 return AdminEvalRunsResource(self._http) 384 385 @cached_property 386 def eval_campaigns(self) -> AdminEvalCampaignsResource: 387 return AdminEvalCampaignsResource(self._http) 388 389 def close(self) -> None: 390 """Close the underlying transport. 391 392 Only call this on a standalone client built via :meth:`connect`; 393 when reached via ``PlatformClient.admin`` the transport is shared 394 with — and closed by — the parent player client. 395 """ 396 self._http.close() 397 398 def __enter__(self) -> Self: 399 return self 400 401 def __exit__( 402 self, 403 exc_type: type[BaseException] | None, 404 exc: BaseException | None, 405 tb: TracebackType | None, 406 ) -> None: 407 self.close()
Admin / operator surface, grouped into resource namespaces.
Namespaces: users, competitions, suites, announcements,
achievements, challenges, gauntlet,
instances,
records, nodes, observability, settings,
competition_admins.
123 @classmethod 124 def connect( 125 cls, 126 server_url: str, 127 token: str = "", 128 *, 129 max_retries: int = 2, 130 timeout: int = DEFAULT_CLIENT_TIMEOUT, 131 ) -> AdminClient: 132 """Build an ``AdminClient`` that owns its own transport. 133 134 For operator tooling that doesn't already hold a 135 :class:`PlatformClient`. The returned client is a context manager 136 that closes its transport on exit. 137 """ 138 base = server_url.rstrip("/") 139 http = BaseHttpClient(f"{base}/api/v1", token, timeout=timeout, max_retries=max_retries) 140 return cls(http)
Build an AdminClient that owns its own transport.
For operator tooling that doesn't already hold a
PlatformClient. The returned client is a context manager
that closes its transport on exit.
150 @cached_property 151 def suites(self) -> AdminSuitesResource: 152 """A suite through its own door: its own fields only (#2896).""" 153 return AdminSuitesResource(self._http)
A suite through its own door: its own fields only (#2896).
163 @cached_property 164 def contact_messages(self) -> AdminContactMessagesResource: 165 """What visitors wrote on the Contact page (#3414).""" 166 return AdminContactMessagesResource(self._http)
What visitors wrote on the Contact page (#3414).
244 @cached_property 245 def admin_invites(self) -> AdminAdminInvitesResource: 246 """Invite an address with no account yet to be an administrator.""" 247 return AdminAdminInvitesResource(self._http)
Invite an address with no account yet to be an administrator.
253 @cached_property 254 def competition_applications(self) -> AdminCompetitionApplicationsResource: 255 """Applications to a private competition, and the verdict on each.""" 256 return AdminCompetitionApplicationsResource(self._http)
Applications to a private competition, and the verdict on each.
258 @cached_property 259 def competition_attachments(self) -> AdminCompetitionAttachmentsResource: 260 """A competition's rules / handbook / notice files (#1808).""" 261 return AdminCompetitionAttachmentsResource(self._http)
A competition's rules / handbook / notice files (#1808).
263 @cached_property 264 def competition_boards(self) -> AdminCompetitionBoardsResource: 265 """A competition's extra boards — published and shadow (#1965 G).""" 266 return AdminCompetitionBoardsResource(self._http)
A competition's extra boards — published and shadow (#1965 G).
268 @cached_property 269 def recap(self) -> AdminRecapResource: 270 """A competition's recap, its publication and its report email (#3023).""" 271 return AdminRecapResource(self._http)
A competition's recap, its publication and its report email (#3023).
273 @cached_property 274 def challenge_schedule(self) -> AdminChallengeScheduleResource: 275 """When each challenge of a competition appears and shuts (#2093).""" 276 return AdminChallengeScheduleResource(self._http)
When each challenge of a competition appears and shuts (#2093).
278 @cached_property 279 def release_plan(self) -> AdminReleasePlanResource: 280 """Waves, per-challenge rules and hints: drafts, publish, release (#2093, #2101).""" 281 return AdminReleasePlanResource(self._http)
Waves, per-challenge rules and hints: drafts, publish, release (#2093, #2101).
283 @cached_property 284 def env_sharing(self) -> AdminEnvSharingResource: 285 """How many teams stand on one environment, the groups behind it and 286 the health of the shared environments (#2129 B).""" 287 return AdminEnvSharingResource(self._http)
How many teams stand on one environment, the groups behind it and the health of the shared environments (#2129 B).
289 @cached_property 290 def machines(self) -> AdminMachinesResource: 291 """Machine logins handed to teams, captain-only (#2132).""" 292 return AdminMachinesResource(self._http)
Machine logins handed to teams, captain-only (#2132).
294 @cached_property 295 def messages(self) -> AdminMessagesResource: 296 """Site messages from an event's organisers or the platform (#2073).""" 297 return AdminMessagesResource(self._http)
Site messages from an event's organisers or the platform (#2073).
299 @cached_property 300 def prewarm(self) -> AdminPrewarmResource: 301 """Whether a competition's images are warm on its nodes (#2129).""" 302 return AdminPrewarmResource(self._http)
Whether a competition's images are warm on its nodes (#2129).
304 @cached_property 305 def competition_topics(self) -> AdminCompetitionTopicsResource: 306 """A competition's scheduled topics, released by the clock (#1965).""" 307 return AdminCompetitionTopicsResource(self._http)
A competition's scheduled topics, released by the clock (#1965).
309 @cached_property 310 def registrations(self) -> AdminRegistrationsResource: 311 """Entrant roster, eligibility review, and CSV export.""" 312 return AdminRegistrationsResource(self._http)
Entrant roster, eligibility review, and CSV export.
314 @cached_property 315 def teams(self) -> AdminTeamsResource: 316 """Enforcement against a squad — disqualify and reinstate. 317 318 Separate from ``registrations`` on purpose: that one rules on 319 eligibility (which decides prizes), this one decides whether the 320 team is in the event at all. 321 """ 322 return AdminTeamsResource(self._http)
Enforcement against a squad — disqualify and reinstate.
Separate from registrations on purpose: that one rules on
eligibility (which decides prizes), this one decides whether the
team is in the event at all.
324 @cached_property 325 def challenge_stats(self) -> AdminChallengeStatsResource: 326 """How players did against an event's challenges: the organiser's 327 table and the single-challenge reading (#2146).""" 328 return AdminChallengeStatsResource(self._http)
How players did against an event's challenges: the organiser's table and the single-challenge reading (#2146).
330 @cached_property 331 def risk(self) -> AdminRiskResource: 332 """Risk control: the case queue (organisers) and an account's sealed 333 sightings (platform administrators). Detection reports; people decide.""" 334 return AdminRiskResource(self._http)
Risk control: the case queue (organisers) and an account's sealed sightings (platform administrators). Detection reports; people decide.
376 @property 377 def registry(self) -> AdminRegistryResource: 378 """Registry storage: the usage report and the manual reclaim.""" 379 return AdminRegistryResource(self._http)
Registry storage: the usage report and the manual reclaim.
389 def close(self) -> None: 390 """Close the underlying transport. 391 392 Only call this on a standalone client built via :meth:`connect`; 393 when reached via ``PlatformClient.admin`` the transport is shared 394 with — and closed by — the parent player client. 395 """ 396 self._http.close()
Close the underlying transport.
Only call this on a standalone client built via connect();
when reached via PlatformClient.admin the transport is shared
with — and closed by — the parent player client.
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.
99class PlatformClient(BaseHttpClient): 100 """Player-facing HTTP client for the ctfy platform. 101 102 Methods are grouped into resource namespaces (``client.teams.list()``, …) 103 plus a per-competition scope via ``client.competition(id)``. The admin 104 surface is a separate :class:`~ctfy.sdk.admin.AdminClient` reached via 105 :attr:`admin`. Used by the CLI, the SDK, the MCP server, and external callers. 106 """ 107 108 def __init__( 109 self, 110 server_url: str, 111 token: str = "", 112 max_retries: int = 2, 113 timeout: int = DEFAULT_PLATFORM_TIMEOUT, 114 transport: httpx.BaseTransport | None = None, 115 unavailable_budget_s: float = UNAVAILABLE_BUDGET_S, 116 request_hooks: Sequence[Callable[[httpx.Request], None]] = (), 117 ): 118 """``unavailable_budget_s``: how long one call waits out a ``503`` + 119 ``Retry-After`` (#3312: a redeploy is a wait, not a failed tool 120 call). ``0`` never waits — the platform's own MCP endpoint calling 121 itself, whose tool thread holds one of the pool's slots (#3504).""" 122 self._url = server_url.rstrip("/") 123 super().__init__( 124 f"{self._url}/api/v1", 125 token, 126 timeout=timeout, 127 max_retries=max_retries, 128 transport=transport, 129 unavailable_budget_s=unavailable_budget_s, 130 request_hooks=request_hooks, 131 ) 132 133 @property 134 def server_url(self) -> str: 135 """The platform root, without the ``/api/v1`` suffix. 136 137 Exposed for callers that must build a non-``/api/v1`` URL of 138 their own — today the shell WebSocket, whose ticket carries a 139 platform-relative path the client has to absolutise against the 140 scheme and host *it* reached us on. 141 """ 142 return self._url 143 144 # -- resource namespaces ------------------------------------------------ 145 146 @cached_property 147 def registration(self) -> RegistrationResource: 148 """The caller's own per-competition registration + team logo.""" 149 return RegistrationResource(self) 150 151 @property 152 def authoring(self) -> AuthoringResource: 153 """Upload a challenge your team wrote, for a peer-authored event.""" 154 return AuthoringResource(self) 155 156 @cached_property 157 def teams(self) -> TeamsResource: 158 """Public team discovery + profile reads.""" 159 return TeamsResource(self) 160 161 @cached_property 162 def users(self) -> UsersResource: 163 """Public per-user profile reads.""" 164 return UsersResource(self) 165 166 @cached_property 167 def me(self) -> MeResource: 168 """The calling user's profile, inbox, account, and progress.""" 169 return MeResource(self) 170 171 @cached_property 172 def messages(self) -> MessagesResource: 173 """Site messages and the inbox stream (#2073).""" 174 return MessagesResource(self) 175 176 @cached_property 177 def auth(self) -> AuthResource: 178 """Password auth, OAuth identities, API tokens, sign-in discovery.""" 179 return AuthResource(self) 180 181 @cached_property 182 def achievements(self) -> AchievementsResource: 183 """Public badge catalog, recent-unlock feed, easter eggs.""" 184 return AchievementsResource(self) 185 186 @cached_property 187 def challenges(self) -> ChallengesResource: 188 """Global challenge catalog, attachments, facets, feedback chips.""" 189 return ChallengesResource(self) 190 191 @cached_property 192 def site(self) -> SiteResource: 193 """The operator's site pages and their Contact form (#3414).""" 194 return SiteResource(self) 195 196 @cached_property 197 def hints(self) -> HintsResource: 198 """A challenge's hint tiers in a competition: read, and open (#2101).""" 199 return HintsResource(self) 200 201 @cached_property 202 def changelog(self) -> ChangelogResource: 203 """Public "What's New" feed, plus this account's seen marker.""" 204 return ChangelogResource(self) 205 206 @cached_property 207 def competitions(self) -> CompetitionsResource: 208 """Discover competitions (``list`` / ``get``). To act within one, use 209 :meth:`competition`.""" 210 return CompetitionsResource(self) 211 212 def competition(self, competition_id: str) -> Competition: 213 """Scope to one competition. The inherently competition-scoped 214 operations — register, your team (captain tooling + invites + 215 join-requests), the comp's challenges, team search, and standings — 216 hang off the returned :class:`~ctfy.sdk.competition.Competition` 217 handle, so ``competition_id`` is named once instead of on every call. 218 (Instance lifecycle and answer submission stay on :attr:`instances` / 219 :attr:`submissions`, keyed by ``instance_id``.)""" 220 return Competition(self, competition_id) 221 222 @cached_property 223 def series(self) -> SeriesResource: 224 """A recurring contest's ladder (public), not its schedule — 225 configuring a series is ``client.admin.series``.""" 226 return SeriesResource(self) 227 228 @property 229 def suites(self) -> SuitesResource: 230 """The benchmark suites -- public challenge sets anybody practises or 231 evaluates against at any time (#2097). Playing one is 232 ``client.competition(id)``, like any competition.""" 233 return SuitesResource(self) 234 235 @cached_property 236 def eval(self) -> EvalResource: 237 """Public model-evaluation leaderboard (ranking + dimensional breakdowns).""" 238 return EvalResource(self) 239 240 @property 241 def registry(self) -> RegistryResource: 242 """The container registry's token endpoint (docker follows it itself).""" 243 return RegistryResource(self) 244 245 @cached_property 246 def vendor(self) -> VendorResource: 247 """Vendor tenancy — the calling vendor's own models / runs (``pv_`` bearer).""" 248 return VendorResource(self) 249 250 @cached_property 251 def instances(self) -> InstancesResource: 252 """Launch / control / inspect challenge instances by instance id 253 (the competition is inferred server-side).""" 254 return InstancesResource(self) 255 256 @cached_property 257 def submissions(self) -> SubmissionsResource: 258 """Submit / verify answers + list submissions (by instance id), plus 259 the instance-less QA challenges.""" 260 return SubmissionsResource(self) 261 262 @cached_property 263 def patches(self) -> PatchesResource: 264 """AWD+ defence: submit a patch, then watch for its verdict.""" 265 return PatchesResource(self) 266 267 @cached_property 268 def awd(self) -> AwdResource: 269 """Classic AWD: submit a round's captured flags in one batch.""" 270 return AwdResource(self) 271 272 @cached_property 273 def reports(self) -> ReportsResource: 274 """The engagement report: save a version, read the current one.""" 275 return ReportsResource(self) 276 277 @cached_property 278 def search(self) -> SearchResource: 279 """Global search: competitions, challenges and teams by name.""" 280 return SearchResource(self) 281 282 @cached_property 283 def llm_sessions(self) -> LlmSessionsResource: 284 """Your local agent sessions on the platform's model gateway (#3307).""" 285 return LlmSessionsResource(self) 286 287 @cached_property 288 def tasks(self) -> TasksResource: 289 """The background tasks you may see: when each waited, ran and ended.""" 290 return TasksResource(self) 291 292 @cached_property 293 def activities(self) -> ActivitiesResource: 294 """Platform activity log + histogram.""" 295 return ActivitiesResource(self) 296 297 @cached_property 298 def nodes(self) -> NodesResource: 299 """Public worker-node list (operator node mgmt is on ``admin.nodes``).""" 300 return NodesResource(self) 301 302 @cached_property 303 def admin(self) -> AdminClient: 304 """Admin / operator surface (separate, role-gated server-side). 305 306 Shares this client's transport. See :class:`~ctfy.sdk.admin.AdminClient`. 307 """ 308 return AdminClient(self) 309 310 # -- top-level convenience: server status / realtime / version ---------- 311 312 def health(self) -> HealthResponse: 313 resp = self.request("GET", "/health") 314 _raise_for_status(resp) 315 return HealthResponse.model_validate(resp.json()) 316 317 def get_meta(self) -> MetaResponse: 318 """Server identity + challenge repo SHA + build version. 319 Admin tokens additionally see cluster capacity + team / solve 320 counts in the same payload.""" 321 resp = self.request("GET", "/meta") 322 _raise_for_status(resp) 323 return MetaResponse.model_validate(resp.json()) 324 325 def get_landing(self) -> LandingResponse: 326 """What the public home page shows: the featured event (``None`` 327 when nothing featured may be shown) and the catalog by domain.""" 328 resp = self.request("GET", "/landing") 329 _raise_for_status(resp) 330 return LandingResponse.model_validate(resp.json()) 331 332 def get_public_stats(self) -> PublicStatsResponse: 333 """The home page's live eval numbers and rounded platform scale 334 (#3413). Public and the same for every caller.""" 335 resp = self.request("GET", "/stats/public") 336 _raise_for_status(resp) 337 return PublicStatsResponse.model_validate(resp.json()) 338 339 def cluster_info(self) -> ClusterInfo: 340 """Aggregate worker-node capacity / utilisation (the public 341 capacity banner; no per-node detail).""" 342 resp = self.request("GET", "/cluster-info") 343 _raise_for_status(resp) 344 return ClusterInfo.model_validate(resp.json()) 345 346 def check_server_compatibility(self, *, health: HealthResponse | None = None) -> VersionCheck: 347 """Compare this client's ``ctfy`` version against the server's. 348 349 Uses the cheap unauthenticated ``/health`` probe (pass an 350 already-fetched :class:`HealthResponse` to avoid a second round 351 trip). Pure classification — never prints, never raises on a 352 mismatch, never mutates anything. The caller (CLI, MCP, harness) 353 decides what to do with :class:`~ctfy.core.version.VersionCheck` 354 (typically: print ``.message`` to stderr when not ``.quiet``). 355 356 A server too old to report its version yields 357 :attr:`Compatibility.UNKNOWN` (``health.version == ""``), which 358 is ``.quiet`` — so this stays silent against legacy servers 359 rather than crying wolf. 360 """ 361 h = health if health is not None else self.health() 362 return check_compatibility(package_version(), h.version) 363 364 def events(self, *, auto_reconnect: bool = True) -> EventStream: 365 """Open the platform SSE event stream. 366 367 Yields ``{"event": <name>, "data": <dict>}`` for each frame. 368 Filters: team-scoped events for every team the caller's user is 369 on (across every per-comp competition), plus all global events; 370 admin tokens additionally see admin-only frames. 371 372 Usage:: 373 374 with client.events() as stream: 375 for event in stream: 376 if event["event"] == "solve": 377 ... 378 379 Auto-reconnects on transient network errors with exponential 380 backoff (1s → 30s capped). Set ``auto_reconnect=False`` to make 381 the iterator raise instead. 382 """ 383 token = self._token 384 385 def _factory() -> httpx.Client: 386 # New client per session so a reconnect after a stale 387 # connection drops fresh sockets, not warmed-over ones. 388 return httpx.Client(base_url=self._base_url, timeout=None) 389 390 return EventStream( 391 client_factory=_factory, 392 path="/events", 393 token=token, 394 auto_reconnect=auto_reconnect, 395 )
Player-facing HTTP client for the ctfy platform.
Methods are grouped into resource namespaces (client.teams.list(), …)
plus a per-competition scope via client.competition(id). The admin
surface is a separate ~ctfy.sdk.admin.AdminClient reached via
admin. Used by the CLI, the SDK, the MCP server, and external callers.
108 def __init__( 109 self, 110 server_url: str, 111 token: str = "", 112 max_retries: int = 2, 113 timeout: int = DEFAULT_PLATFORM_TIMEOUT, 114 transport: httpx.BaseTransport | None = None, 115 unavailable_budget_s: float = UNAVAILABLE_BUDGET_S, 116 request_hooks: Sequence[Callable[[httpx.Request], None]] = (), 117 ): 118 """``unavailable_budget_s``: how long one call waits out a ``503`` + 119 ``Retry-After`` (#3312: a redeploy is a wait, not a failed tool 120 call). ``0`` never waits — the platform's own MCP endpoint calling 121 itself, whose tool thread holds one of the pool's slots (#3504).""" 122 self._url = server_url.rstrip("/") 123 super().__init__( 124 f"{self._url}/api/v1", 125 token, 126 timeout=timeout, 127 max_retries=max_retries, 128 transport=transport, 129 unavailable_budget_s=unavailable_budget_s, 130 request_hooks=request_hooks, 131 )
unavailable_budget_s: how long one call waits out a 503 +
Retry-After (#3312: a redeploy is a wait, not a failed tool
call). 0 never waits — the platform's own MCP endpoint calling
itself, whose tool thread holds one of the pool's slots (#3504).
133 @property 134 def server_url(self) -> str: 135 """The platform root, without the ``/api/v1`` suffix. 136 137 Exposed for callers that must build a non-``/api/v1`` URL of 138 their own — today the shell WebSocket, whose ticket carries a 139 platform-relative path the client has to absolutise against the 140 scheme and host *it* reached us on. 141 """ 142 return self._url
The platform root, without the /api/v1 suffix.
Exposed for callers that must build a non-/api/v1 URL of
their own — today the shell WebSocket, whose ticket carries a
platform-relative path the client has to absolutise against the
scheme and host it reached us on.
146 @cached_property 147 def registration(self) -> RegistrationResource: 148 """The caller's own per-competition registration + team logo.""" 149 return RegistrationResource(self)
The caller's own per-competition registration + team logo.
156 @cached_property 157 def teams(self) -> TeamsResource: 158 """Public team discovery + profile reads.""" 159 return TeamsResource(self)
Public team discovery + profile reads.
161 @cached_property 162 def users(self) -> UsersResource: 163 """Public per-user profile reads.""" 164 return UsersResource(self)
Public per-user profile reads.
166 @cached_property 167 def me(self) -> MeResource: 168 """The calling user's profile, inbox, account, and progress.""" 169 return MeResource(self)
The calling user's profile, inbox, account, and progress.
171 @cached_property 172 def messages(self) -> MessagesResource: 173 """Site messages and the inbox stream (#2073).""" 174 return MessagesResource(self)
Site messages and the inbox stream (#2073).
176 @cached_property 177 def auth(self) -> AuthResource: 178 """Password auth, OAuth identities, API tokens, sign-in discovery.""" 179 return AuthResource(self)
Password auth, OAuth identities, API tokens, sign-in discovery.
181 @cached_property 182 def achievements(self) -> AchievementsResource: 183 """Public badge catalog, recent-unlock feed, easter eggs.""" 184 return AchievementsResource(self)
Public badge catalog, recent-unlock feed, easter eggs.
186 @cached_property 187 def challenges(self) -> ChallengesResource: 188 """Global challenge catalog, attachments, facets, feedback chips.""" 189 return ChallengesResource(self)
Global challenge catalog, attachments, facets, feedback chips.
191 @cached_property 192 def site(self) -> SiteResource: 193 """The operator's site pages and their Contact form (#3414).""" 194 return SiteResource(self)
The operator's site pages and their Contact form (#3414).
196 @cached_property 197 def hints(self) -> HintsResource: 198 """A challenge's hint tiers in a competition: read, and open (#2101).""" 199 return HintsResource(self)
A challenge's hint tiers in a competition: read, and open (#2101).
201 @cached_property 202 def changelog(self) -> ChangelogResource: 203 """Public "What's New" feed, plus this account's seen marker.""" 204 return ChangelogResource(self)
Public "What's New" feed, plus this account's seen marker.
206 @cached_property 207 def competitions(self) -> CompetitionsResource: 208 """Discover competitions (``list`` / ``get``). To act within one, use 209 :meth:`competition`.""" 210 return CompetitionsResource(self)
Discover competitions (list / get). To act within one, use
competition().
212 def competition(self, competition_id: str) -> Competition: 213 """Scope to one competition. The inherently competition-scoped 214 operations — register, your team (captain tooling + invites + 215 join-requests), the comp's challenges, team search, and standings — 216 hang off the returned :class:`~ctfy.sdk.competition.Competition` 217 handle, so ``competition_id`` is named once instead of on every call. 218 (Instance lifecycle and answer submission stay on :attr:`instances` / 219 :attr:`submissions`, keyed by ``instance_id``.)""" 220 return Competition(self, competition_id)
Scope to one competition. The inherently competition-scoped
operations — register, your team (captain tooling + invites +
join-requests), the comp's challenges, team search, and standings —
hang off the returned ~ctfy.sdk.competition.Competition
handle, so competition_id is named once instead of on every call.
(Instance lifecycle and answer submission stay on instances /
submissions, keyed by instance_id.)
222 @cached_property 223 def series(self) -> SeriesResource: 224 """A recurring contest's ladder (public), not its schedule — 225 configuring a series is ``client.admin.series``.""" 226 return SeriesResource(self)
A recurring contest's ladder (public), not its schedule —
configuring a series is client.admin.series.
228 @property 229 def suites(self) -> SuitesResource: 230 """The benchmark suites -- public challenge sets anybody practises or 231 evaluates against at any time (#2097). Playing one is 232 ``client.competition(id)``, like any competition.""" 233 return SuitesResource(self)
The benchmark suites -- public challenge sets anybody practises or
evaluates against at any time (#2097). Playing one is
client.competition(id), like any competition.
235 @cached_property 236 def eval(self) -> EvalResource: 237 """Public model-evaluation leaderboard (ranking + dimensional breakdowns).""" 238 return EvalResource(self)
Public model-evaluation leaderboard (ranking + dimensional breakdowns).
240 @property 241 def registry(self) -> RegistryResource: 242 """The container registry's token endpoint (docker follows it itself).""" 243 return RegistryResource(self)
The container registry's token endpoint (docker follows it itself).
245 @cached_property 246 def vendor(self) -> VendorResource: 247 """Vendor tenancy — the calling vendor's own models / runs (``pv_`` bearer).""" 248 return VendorResource(self)
Vendor tenancy — the calling vendor's own models / runs (pv_ bearer).
250 @cached_property 251 def instances(self) -> InstancesResource: 252 """Launch / control / inspect challenge instances by instance id 253 (the competition is inferred server-side).""" 254 return InstancesResource(self)
Launch / control / inspect challenge instances by instance id (the competition is inferred server-side).
256 @cached_property 257 def submissions(self) -> SubmissionsResource: 258 """Submit / verify answers + list submissions (by instance id), plus 259 the instance-less QA challenges.""" 260 return SubmissionsResource(self)
Submit / verify answers + list submissions (by instance id), plus the instance-less QA challenges.
262 @cached_property 263 def patches(self) -> PatchesResource: 264 """AWD+ defence: submit a patch, then watch for its verdict.""" 265 return PatchesResource(self)
AWD+ defence: submit a patch, then watch for its verdict.
267 @cached_property 268 def awd(self) -> AwdResource: 269 """Classic AWD: submit a round's captured flags in one batch.""" 270 return AwdResource(self)
Classic AWD: submit a round's captured flags in one batch.
272 @cached_property 273 def reports(self) -> ReportsResource: 274 """The engagement report: save a version, read the current one.""" 275 return ReportsResource(self)
The engagement report: save a version, read the current one.
277 @cached_property 278 def search(self) -> SearchResource: 279 """Global search: competitions, challenges and teams by name.""" 280 return SearchResource(self)
Global search: competitions, challenges and teams by name.
282 @cached_property 283 def llm_sessions(self) -> LlmSessionsResource: 284 """Your local agent sessions on the platform's model gateway (#3307).""" 285 return LlmSessionsResource(self)
Your local agent sessions on the platform's model gateway (#3307).
287 @cached_property 288 def tasks(self) -> TasksResource: 289 """The background tasks you may see: when each waited, ran and ended.""" 290 return TasksResource(self)
The background tasks you may see: when each waited, ran and ended.
292 @cached_property 293 def activities(self) -> ActivitiesResource: 294 """Platform activity log + histogram.""" 295 return ActivitiesResource(self)
Platform activity log + histogram.
297 @cached_property 298 def nodes(self) -> NodesResource: 299 """Public worker-node list (operator node mgmt is on ``admin.nodes``).""" 300 return NodesResource(self)
Public worker-node list (operator node mgmt is on admin.nodes).
302 @cached_property 303 def admin(self) -> AdminClient: 304 """Admin / operator surface (separate, role-gated server-side). 305 306 Shares this client's transport. See :class:`~ctfy.sdk.admin.AdminClient`. 307 """ 308 return AdminClient(self)
Admin / operator surface (separate, role-gated server-side).
Shares this client's transport. See ~ctfy.sdk.admin.AdminClient.
317 def get_meta(self) -> MetaResponse: 318 """Server identity + challenge repo SHA + build version. 319 Admin tokens additionally see cluster capacity + team / solve 320 counts in the same payload.""" 321 resp = self.request("GET", "/meta") 322 _raise_for_status(resp) 323 return MetaResponse.model_validate(resp.json())
Server identity + challenge repo SHA + build version. Admin tokens additionally see cluster capacity + team / solve counts in the same payload.
325 def get_landing(self) -> LandingResponse: 326 """What the public home page shows: the featured event (``None`` 327 when nothing featured may be shown) and the catalog by domain.""" 328 resp = self.request("GET", "/landing") 329 _raise_for_status(resp) 330 return LandingResponse.model_validate(resp.json())
What the public home page shows: the featured event (None
when nothing featured may be shown) and the catalog by domain.
332 def get_public_stats(self) -> PublicStatsResponse: 333 """The home page's live eval numbers and rounded platform scale 334 (#3413). Public and the same for every caller.""" 335 resp = self.request("GET", "/stats/public") 336 _raise_for_status(resp) 337 return PublicStatsResponse.model_validate(resp.json())
The home page's live eval numbers and rounded platform scale (#3413). Public and the same for every caller.
339 def cluster_info(self) -> ClusterInfo: 340 """Aggregate worker-node capacity / utilisation (the public 341 capacity banner; no per-node detail).""" 342 resp = self.request("GET", "/cluster-info") 343 _raise_for_status(resp) 344 return ClusterInfo.model_validate(resp.json())
Aggregate worker-node capacity / utilisation (the public capacity banner; no per-node detail).
346 def check_server_compatibility(self, *, health: HealthResponse | None = None) -> VersionCheck: 347 """Compare this client's ``ctfy`` version against the server's. 348 349 Uses the cheap unauthenticated ``/health`` probe (pass an 350 already-fetched :class:`HealthResponse` to avoid a second round 351 trip). Pure classification — never prints, never raises on a 352 mismatch, never mutates anything. The caller (CLI, MCP, harness) 353 decides what to do with :class:`~ctfy.core.version.VersionCheck` 354 (typically: print ``.message`` to stderr when not ``.quiet``). 355 356 A server too old to report its version yields 357 :attr:`Compatibility.UNKNOWN` (``health.version == ""``), which 358 is ``.quiet`` — so this stays silent against legacy servers 359 rather than crying wolf. 360 """ 361 h = health if health is not None else self.health() 362 return check_compatibility(package_version(), h.version)
Compare this client's ctfy version against the server's.
Uses the cheap unauthenticated /health probe (pass an
already-fetched HealthResponse to avoid a second round
trip). Pure classification — never prints, never raises on a
mismatch, never mutates anything. The caller (CLI, MCP, harness)
decides what to do with ~ctfy.core.version.VersionCheck
(typically: print .message to stderr when not .quiet).
A server too old to report its version yields
Compatibility.UNKNOWN (health.version == ""), which
is .quiet — so this stays silent against legacy servers
rather than crying wolf.
364 def events(self, *, auto_reconnect: bool = True) -> EventStream: 365 """Open the platform SSE event stream. 366 367 Yields ``{"event": <name>, "data": <dict>}`` for each frame. 368 Filters: team-scoped events for every team the caller's user is 369 on (across every per-comp competition), plus all global events; 370 admin tokens additionally see admin-only frames. 371 372 Usage:: 373 374 with client.events() as stream: 375 for event in stream: 376 if event["event"] == "solve": 377 ... 378 379 Auto-reconnects on transient network errors with exponential 380 backoff (1s → 30s capped). Set ``auto_reconnect=False`` to make 381 the iterator raise instead. 382 """ 383 token = self._token 384 385 def _factory() -> httpx.Client: 386 # New client per session so a reconnect after a stale 387 # connection drops fresh sockets, not warmed-over ones. 388 return httpx.Client(base_url=self._base_url, timeout=None) 389 390 return EventStream( 391 client_factory=_factory, 392 path="/events", 393 token=token, 394 auto_reconnect=auto_reconnect, 395 )
Open the platform SSE event stream.
Yields {"event": <name>, "data": <dict>} for each frame.
Filters: team-scoped events for every team the caller's user is
on (across every per-comp competition), plus all global events;
admin tokens additionally see admin-only frames.
Usage::
with client.events() as stream:
for event in stream:
if event["event"] == "solve":
...
Auto-reconnects on transient network errors with exponential
backoff (1s → 30s capped). Set auto_reconnect=False to make
the iterator raise instead.