This repository was archived by the owner on Sep 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
489 lines (391 loc) · 16 KB
/
api.py
File metadata and controls
489 lines (391 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import atexit
import json
import time
import typing as t
from datetime import datetime, timezone
from urllib.parse import urlparse
from uuid import UUID
import httpx
from pydantic import BaseModel
from rich import print
from dreadnode_cli import __version__, utils
from dreadnode_cli.config import UserConfig
from dreadnode_cli.defaults import (
DEBUG,
DEFAULT_MAX_POLL_TIME,
DEFAULT_POLL_INTERVAL,
DEFAULT_TOKEN_MAX_TTL,
PLATFORM_BASE_URL,
)
class Token:
"""A JWT token with an expiration time."""
data: str
expires_at: datetime
def __init__(self, token: str):
self.data = token
self.expires_at = utils.parse_jwt_token_expiration(token)
def ttl(self) -> int:
"""Get number of seconds left until the token expires."""
return int((self.expires_at - datetime.now()).total_seconds())
def is_expired(self) -> bool:
"""Return True if the token is expired."""
return self.ttl() <= 0
def is_close_to_expiry(self) -> bool:
"""Return True if the token is close to expiry."""
return self.ttl() <= DEFAULT_TOKEN_MAX_TTL
class Client:
"""Client for the Dreadnode API."""
def __init__(
self,
base_url: str = PLATFORM_BASE_URL,
*,
cookies: dict[str, str] | None = None,
debug: bool = DEBUG,
):
_cookies = httpx.Cookies()
cookie_domain = urlparse(base_url).hostname
if cookie_domain is None:
raise Exception(f"Invalid URL: {base_url}")
if "localhost" == cookie_domain:
cookie_domain = "localhost.local"
for key, value in (cookies or {}).items():
_cookies.set(key, value, domain=cookie_domain)
self._base_url = base_url.rstrip("/")
self._client = httpx.Client(
cookies=_cookies,
headers={
"User-Agent": f"dreadnode-cli/{__version__}",
"Accept": "application/json",
},
base_url=self._base_url,
timeout=30,
)
if debug:
self._client.event_hooks["request"].append(self._log_request)
self._client.event_hooks["response"].append(self._log_response)
def _log_request(self, request: httpx.Request) -> None:
"""Log every request to the console if debug is enabled."""
print("-------------------------------------------")
print(f"[bold]{request.method}[/] {request.url}")
print("Headers:", request.headers)
print("Content:", request.content)
print("-------------------------------------------")
def _log_response(self, response: httpx.Response) -> None:
"""Log every response to the console if debug is enabled."""
print("-------------------------------------------")
print(f"Response: {response.status_code}")
print("Headers:", response.headers)
print("Content:", response.read())
print("--------------------------------------------")
def _get_error_message(self, response: httpx.Response) -> str:
"""Get the error message from the response."""
try:
obj = response.json()
return f'{response.status_code}: {obj.get("detail", json.dumps(obj))}'
except Exception:
return str(response.content)
def _request(
self,
method: str,
path: str,
query_params: dict[str, str] | None = None,
json_data: dict[str, t.Any] | None = None,
) -> httpx.Response:
"""Make a raw request to the API."""
return self._client.request(method, path, json=json_data, params=query_params)
def request(
self,
method: str,
path: str,
query_params: dict[str, str] | None = None,
json_data: dict[str, t.Any] | None = None,
) -> httpx.Response:
"""Make a request to the API. Raise an exception for non-200 status codes."""
response = self._request(method, path, query_params, json_data)
if response.status_code == 401:
raise Exception("Authentication expired, use [bold]dreadnode login[/]")
try:
response.raise_for_status()
return response
except httpx.HTTPStatusError as e:
raise Exception(self._get_error_message(response)) from e
# Auth
def url_for_user_code(self, user_code: str) -> str:
"""Get the URL to verify the user code."""
return f"{self._base_url}/account/device?code={user_code}"
class DeviceCodeResponse(BaseModel):
id: UUID
completed: bool
device_code: str
expires_at: datetime
expires_in: int
user_code: str
verification_url: str
def get_device_codes(self) -> DeviceCodeResponse:
"""Start the authentication flow by requesting user and device codes."""
response = self.request("POST", "/api/auth/device/code")
return self.DeviceCodeResponse(**response.json())
class AccessRefreshTokenResponse(BaseModel):
access_token: str
refresh_token: str
def poll_for_token(
self, device_code: str, interval: int = DEFAULT_POLL_INTERVAL, max_poll_time: int = DEFAULT_MAX_POLL_TIME
) -> AccessRefreshTokenResponse:
"""Poll for the access token with the given device code."""
start_time = datetime.now(timezone.utc)
while (datetime.now(timezone.utc) - start_time).total_seconds() < max_poll_time:
response = self._request("POST", "/api/auth/device/token", json_data={"device_code": device_code})
if response.status_code == 200:
return self.AccessRefreshTokenResponse(**response.json())
elif response.status_code != 401:
raise Exception(self._get_error_message(response))
time.sleep(interval)
raise Exception("Polling for token timed out")
# User
class UserAPIKeyResponse(BaseModel):
key: str
class UserResponse(BaseModel):
id: UUID
email_address: str
username: str
api_key: "Client.UserAPIKeyResponse"
def get_user(self) -> UserResponse:
"""Get the user email and username."""
response = self.request("GET", "/api/user")
return self.UserResponse(**response.json())
# Challenges
class ChallengeResponse(BaseModel):
authors: list[str]
difficulty: str
key: str
lead: str
name: str
status: str
title: str
tags: list[str]
def list_challenges(self) -> list[ChallengeResponse]:
"""List all challenges."""
response = self.request("GET", "/api/challenges")
return [self.ChallengeResponse(**challenge) for challenge in response.json()]
def get_challenge_artifact(self, challenge: str, artifact_name: str) -> bytes:
"""Get a challenge artifact."""
response = self.request("GET", f"/api/artifacts/{challenge}/{artifact_name}")
return response.content
def submit_challenge_flag(self, challenge: str, flag: str) -> bool:
"""Submit a flag to a challenge."""
response = self.request("POST", f"/api/challenges/{challenge}/submit-flag", json_data={"flag": flag})
return bool(response.json().get("correct", False))
# Github
class GithubTokenResponse(BaseModel):
token: str
expires_at: datetime
repos: list[str]
def get_github_access_token(self, repos: list[str]) -> GithubTokenResponse:
"""Try to get a GitHub access token for the given repositories."""
response = self.request("POST", "/api/github/token", json_data={"repos": repos})
return self.GithubTokenResponse(**response.json())
# Strikes
StrikeRunStatus = t.Literal[
"pending", # Waiting to be processed in the DB
"deploying", # Dropship pod is being created and configured
"running", # Dropship pod is actively executing
"completed", # All zones finished successfully
"mixed", # Some zones succeeded, others terminated
"terminated", # All zones ended with non-zero exit codes
"timeout", # Maximum allowed run time was exceeded
"failed", # System/infrastructure error occurred
]
StrikeRunZoneStatus = t.Literal[
"pending", # Waiting to be processed in the DB
"deploying", # Dropship is creating the zone resources
"running", # Zone pods are actively executing
"completed", # Agent completed successfully (exit code 0)
"terminated", # Agent ended with non-zero exit code
"timeout", # Maximum allowed run time was exceeded
"failed", # System/infrastructure error occurred
]
class StrikeModel(BaseModel):
key: str
name: str
provider: str
class StrikeZone(BaseModel):
key: str
name: str
guidance: str | None
description: str | None
class StrikeSummaryResponse(BaseModel):
id: UUID
key: str
competitive: bool
models: list["Client.StrikeModel"]
type: str
name: str
description: str | None
class StrikeResponse(StrikeSummaryResponse):
zones: list["Client.StrikeZone"]
guidance: str | None
description: str | None
class Container(BaseModel):
image: str
env: dict[str, str]
name: str | None
class StrikeAgentVersion(BaseModel):
id: UUID
created_at: datetime
notes: str | None
container: "Client.Container"
class StrikeAgentResponse(BaseModel):
id: UUID
user_id: UUID
strike_id: UUID | None
key: str
name: str | None
created_at: datetime
latest_run_status: "Client.StrikeRunStatus | None"
latest_run_id: UUID | None
versions: list["Client.StrikeAgentVersion"]
latest_version: "Client.StrikeAgentVersion"
revision: int
class StrikeAgentSummaryResponse(BaseModel):
id: UUID
user_id: UUID
strike_id: UUID | None
key: str
name: str | None
created_at: datetime
latest_run_status: "Client.StrikeRunStatus | None"
latest_run_id: UUID | None
latest_version: "Client.StrikeAgentVersion"
revision: int
class StrikeRunOutputScore(BaseModel):
value: int | float | bool
explanation: str | None = None
metadata: dict[str, t.Any] = {}
class StrikeRunOutputSummary(BaseModel):
score: t.Optional["Client.StrikeRunOutputScore"] = None
metadata: dict[str, t.Any] = {}
class StrikeRunOutput(StrikeRunOutputSummary):
data: dict[str, t.Any]
class _StrikeRunZone(BaseModel):
key: str
status: "Client.StrikeRunZoneStatus"
start: datetime | None
end: datetime | None
class StrikeRunZoneSummary(_StrikeRunZone):
outputs: list["Client.StrikeRunOutputSummary"]
class StrikeRunZone(_StrikeRunZone):
agent_logs: str | None
container_logs: dict[str, str]
outputs: list["Client.StrikeRunOutput"]
inferences: list[dict[str, t.Any]]
class _StrikeRun(BaseModel):
id: UUID
strike_id: UUID
strike_key: str
strike_name: str
strike_type: str
strike_description: str | None
model: str | None
agent_id: UUID
agent_key: str
agent_name: str | None = None
agent_revision: int
agent_version: "Client.StrikeAgentVersion"
status: "Client.StrikeRunStatus"
start: datetime | None
end: datetime | None
def is_running(self) -> bool:
return self.status in ["pending", "deploying", "running"]
class StrikeRunSummaryResponse(_StrikeRun):
zones: list["Client.StrikeRunZoneSummary"]
class StrikeRunResponse(_StrikeRun):
zones: list["Client.StrikeRunZone"]
def get_strike(self, strike: str) -> StrikeResponse:
response = self.request("GET", f"/api/strikes/{strike}")
return self.StrikeResponse(**response.json())
def list_strikes(self) -> list[StrikeSummaryResponse]:
response = self.request("GET", "/api/strikes")
return [self.StrikeResponse(**strike) for strike in response.json()]
def list_strike_agents(self, strike_id: UUID | None = None) -> list[StrikeAgentSummaryResponse]:
response = self.request(
"GET",
"/api/strikes/agents",
query_params={"strike_id": str(strike_id)} if strike_id else None,
)
return [self.StrikeAgentSummaryResponse(**agent) for agent in response.json()]
def get_strike_agent(self, agent: UUID | str) -> StrikeAgentResponse:
response = self.request("GET", f"/api/strikes/agents/{agent}")
return self.StrikeAgentResponse(**response.json())
def create_strike_agent(
self, container: Container, name: str, strike: str | None = None, notes: str | None = None
) -> StrikeAgentResponse:
response = self.request(
"POST",
"/api/strikes/agents",
json_data={
"container": container.model_dump(mode="json"),
"strike": strike,
"name": name,
"notes": notes,
},
)
return self.StrikeAgentResponse(**response.json())
def update_strike_agent(self, agent: str, name: str) -> StrikeAgentResponse:
response = self.request("PATCH", f"/api/strikes/agents/{agent}", json_data={"name": name})
return self.StrikeAgentResponse(**response.json())
def create_strike_agent_version(
self, agent: str, container: Container, notes: str | None = None
) -> StrikeAgentResponse:
response = self.request(
"POST",
f"/api/strikes/agents/{agent}/versions",
json_data={
"container": container.model_dump(mode="json"),
"notes": notes,
},
)
return self.StrikeAgentResponse(**response.json())
def start_strike_run(
self, agent_version_id: UUID, *, model: str | None = None, strike: UUID | str | None = None
) -> StrikeRunResponse:
response = self.request(
"POST",
"/api/strikes/runs",
json_data={
"agent_version_id": str(agent_version_id),
"model": model,
"strike": str(strike) if strike else None,
},
)
return self.StrikeRunResponse(**response.json())
def get_strike_run(self, run: UUID | str) -> StrikeRunResponse:
response = self.request("GET", f"/api/strikes/runs/{run}")
return self.StrikeRunResponse(**response.json())
def list_strike_runs(self, *, strike_id: UUID | str | None = None) -> list[StrikeRunSummaryResponse]:
response = self.request(
"GET", "/api/strikes/runs", query_params={"strike_id": str(strike_id)} if strike_id else None
)
return [self.StrikeRunSummaryResponse(**run) for run in response.json()]
def create_client(*, profile: str | None = None) -> Client:
"""Create an authenticated API client using stored configuration data."""
user_config = UserConfig.read()
config = user_config.get_server_config(profile)
client = Client(config.url, cookies={"access_token": config.access_token, "refresh_token": config.refresh_token})
# Pre-emptively check if the token is expired
if Token(config.refresh_token).is_expired():
raise Exception("Authentication expired, use [bold]dreadnode login[/]")
def _flush_auth_changes() -> None:
"""Flush the authentication data to disk if it has been updated."""
access_token = client._client.cookies.get("access_token")
refresh_token = client._client.cookies.get("refresh_token")
changed: bool = False
if access_token and access_token != config.access_token:
changed = True
config.access_token = access_token
if refresh_token and refresh_token != config.refresh_token:
changed = True
config.refresh_token = refresh_token
if changed:
user_config.set_server_config(config, profile).write()
atexit.register(_flush_auth_changes)
return client