eurycleia 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. eurycleia/__init__.py +19 -0
  2. eurycleia/__main__.py +7 -0
  3. eurycleia/_names.py +34 -0
  4. eurycleia/api.py +474 -0
  5. eurycleia/attacks.py +303 -0
  6. eurycleia/audit.py +451 -0
  7. eurycleia/boxes.py +901 -0
  8. eurycleia/boxes_migrate.py +104 -0
  9. eurycleia/cache.py +76 -0
  10. eurycleia/cli.py +644 -0
  11. eurycleia/connect.py +296 -0
  12. eurycleia/connectors/__init__.py +38 -0
  13. eurycleia/connectors/base.py +119 -0
  14. eurycleia/connectors/email.py +30 -0
  15. eurycleia/connectors/files.py +62 -0
  16. eurycleia/connectors/gdrive.py +41 -0
  17. eurycleia/connectors/rest.py +39 -0
  18. eurycleia/connectors/saas.py +225 -0
  19. eurycleia/connectors/salesforce.py +63 -0
  20. eurycleia/connectors/sharepoint.py +37 -0
  21. eurycleia/connectors/sql.py +75 -0
  22. eurycleia/crypto.py +160 -0
  23. eurycleia/derive.py +134 -0
  24. eurycleia/detect.py +475 -0
  25. eurycleia/errors.py +10 -0
  26. eurycleia/integrations/__init__.py +3 -0
  27. eurycleia/integrations/_common.py +57 -0
  28. eurycleia/integrations/crewai.py +28 -0
  29. eurycleia/integrations/langchain.py +25 -0
  30. eurycleia/learn.py +477 -0
  31. eurycleia/llm.py +481 -0
  32. eurycleia/mcp.py +235 -0
  33. eurycleia/planner.py +268 -0
  34. eurycleia/policy.py +315 -0
  35. eurycleia/py.typed +0 -0
  36. eurycleia/setup.py +501 -0
  37. eurycleia/templates/__init__.py +2 -0
  38. eurycleia/templates/finance.yaml +59 -0
  39. eurycleia/templates/fixtures-finance.yaml +10 -0
  40. eurycleia/templates/fixtures-support.yaml +13 -0
  41. eurycleia/templates/support.yaml +64 -0
  42. eurycleia/vault.py +1339 -0
  43. eurycleia/webclient.py +188 -0
  44. eurycleia-0.6.0.dist-info/METADATA +309 -0
  45. eurycleia-0.6.0.dist-info/RECORD +52 -0
  46. eurycleia-0.6.0.dist-info/WHEEL +5 -0
  47. eurycleia-0.6.0.dist-info/entry_points.txt +4 -0
  48. eurycleia-0.6.0.dist-info/licenses/LICENSE +235 -0
  49. eurycleia-0.6.0.dist-info/licenses/NOTICE +17 -0
  50. eurycleia-0.6.0.dist-info/top_level.txt +2 -0
  51. taskvault/__init__.py +31 -0
  52. taskvault/__main__.py +9 -0
eurycleia/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ # Copyright 2026 AgentP-Codes
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ """eurycleia - a task-scoped data vault for AI agents (working name).
4
+
5
+ Core: Vault, Task, Policy, Blocked, AuditLog
6
+ Planner: eurycleia.planner.Planner (provenance-tracked, CaMeL-style)
7
+ Storage: eurycleia.crypto (customer-held keys), eurycleia.cache (read-through)
8
+ Adapters: eurycleia.connectors, eurycleia.mcp (proxy), eurycleia.llm (models)
9
+ Tooling: eurycleia.attacks (attack suite), `eurycleia` CLI
10
+ """
11
+
12
+ __version__ = "0.6.0"
13
+
14
+ from .audit import AuditLog # noqa: E402
15
+ from .policy import Policy, PolicyError # noqa: E402
16
+ from .vault import ApprovalRequest, Blocked, SinkError, Task, Vault # noqa: E402
17
+
18
+ __all__ = ["ApprovalRequest", "AuditLog", "Blocked", "Policy", "PolicyError", "SinkError", "Task", "Vault",
19
+ "__version__"]
eurycleia/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ # Copyright 2026 AgentP-Codes
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
eurycleia/_names.py ADDED
@@ -0,0 +1,34 @@
1
+ # Copyright 2026 AgentP-Codes
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ """Eurycleia was called taskvault before 0.6. Settings, folders and files under the old name keep working:
4
+ the new name is used when it's there, the old one otherwise."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from pathlib import Path
10
+
11
+ OLD = "taskvault"
12
+ MARKS = ("--eurycleia-connected", "--taskvault-connected") # set by `connect` in a wrapped server's arguments
13
+
14
+
15
+ def setting(name: str, default: str | None = None) -> str | None:
16
+ """EURYCLEIA_<name>, else the old TASKVAULT_<name>, else `default`."""
17
+ return os.environ.get(f"EURYCLEIA_{name}") or os.environ.get(f"TASKVAULT_{name}") or default
18
+
19
+
20
+ def _pick(new: Path, old: Path) -> Path:
21
+ return old if old.exists() and not new.exists() else new
22
+
23
+
24
+ def home_dir() -> Path:
25
+ """Where `connect`, `api` and the audit log keep their files: ~/.eurycleia (or ~/.taskvault if only that exists)."""
26
+ explicit = setting("HOME")
27
+ if explicit:
28
+ return Path(explicit)
29
+ return _pick(Path.home() / ".eurycleia", Path.home() / ".taskvault")
30
+
31
+
32
+ def local(new: str, old: str) -> str:
33
+ """A file or folder in the current directory: `new`, unless only the old name exists."""
34
+ return str(_pick(Path(new), Path(old)))
eurycleia/api.py ADDED
@@ -0,0 +1,474 @@
1
+ # Copyright 2026 AgentP-Codes
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ """A local API so agents written in other languages (TypeScript, JavaScript, ...) can use eurycleia.
4
+
5
+ eurycleia api --app eurycleia_app:build_vault # connectors from `eurycleia setup`
6
+ eurycleia api --policy eurycleia.yaml -- <MCP server> # or tools from an MCP server
7
+
8
+ The language adapters (in `adapters/`) are thin clients: every check, placeholder, pseudonym, audit entry
9
+ and block happens here, in the same code the Python SDK uses. Nothing is re-implemented per language.
10
+
11
+ Actions ("sinks") such as sending an email can run on either side:
12
+
13
+ * in Python, if the app factory or MCP server provides them, or
14
+ * in the other language's app: the adapter registers a handler, and when the vault approves the action
15
+ it asks the adapter to run it with the real values (like a Python sink function receives them), then
16
+ masks whatever the handler returns before the model sees it.
17
+
18
+ Locked down by default: listens on 127.0.0.1 only; every request needs a random bearer token; requests
19
+ from web pages (an Origin header) and unexpected Host headers are refused, so a website you visit can't
20
+ reach it; bodies are size-limited; tasks expire when idle.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import hmac
27
+ import json
28
+ import logging
29
+ import os
30
+ import queue
31
+ import secrets
32
+ import threading
33
+ import time
34
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
35
+ from pathlib import Path
36
+ from typing import Any
37
+
38
+ from . import __version__
39
+ from .audit import owner_only
40
+ from .errors import EurycleiaError
41
+ from .vault import Blocked, SinkError, Task, Vault
42
+
43
+ log = logging.getLogger("eurycleia.api")
44
+ MAX_BODY = 1024 * 1024
45
+ _current = threading.local()
46
+
47
+
48
+ class ApiError(EurycleiaError):
49
+ """`eurycleia api` can't start as asked."""
50
+
51
+
52
+ def _alive(pid: int) -> bool:
53
+ if os.name == "nt": # checking another process needs extra Windows calls; assume it has gone
54
+ return False
55
+ try:
56
+ os.kill(pid, 0)
57
+ except ProcessLookupError:
58
+ return False
59
+ except PermissionError:
60
+ return True # exists, owned by someone else
61
+ return True
62
+
63
+
64
+ class RemoteSink:
65
+ """A sink whose code lives in the adapter's app (another language). See module docs."""
66
+
67
+ def __init__(self, name: str):
68
+ self.name = name
69
+
70
+ def __call__(self, **args: Any) -> Any:
71
+ ex = getattr(_current, "exchange", None)
72
+ if ex is None:
73
+ raise RuntimeError(f"{self.name} is run by the app connected through `eurycleia api`, "
74
+ "and can only be used from there")
75
+ return ex.run_remote(self.name, args)
76
+
77
+
78
+ def remote_sinks(vault_or_policy: Any) -> dict[str, RemoteSink]:
79
+ """A RemoteSink for every action the policy names (in any task, or behind any tool)."""
80
+ policy = getattr(vault_or_policy, "policy", vault_or_policy)
81
+ names = {s for t in policy.tasks.values() for s in t.sinks}
82
+ names |= {tm.act for tm in policy.tools.values() if tm.act}
83
+ return {name: RemoteSink(name) for name in sorted(names)}
84
+
85
+
86
+ class _Exchange:
87
+ """One API call running on a worker thread, able to pause while the adapter runs a sink."""
88
+
89
+ def __init__(self, exec_timeout: float):
90
+ self.id = secrets.token_urlsafe(16)
91
+ self.outbox: queue.Queue = queue.Queue()
92
+ self.inbox: queue.Queue = queue.Queue()
93
+ self.exec_timeout = exec_timeout
94
+
95
+ def run_remote(self, sink: str, args: dict[str, Any]) -> Any:
96
+ self.outbox.put({"status": "execute", "exec": self.id, "sink": sink, "args": args})
97
+ try:
98
+ reply = self.inbox.get(timeout=self.exec_timeout)
99
+ except queue.Empty:
100
+ raise TimeoutError(f"the app didn't finish {sink} within {self.exec_timeout:.0f} seconds") from None
101
+ if "error" in reply:
102
+ raise RuntimeError(str(reply["error"])) # masked by the vault; never cut first (cut values escape)
103
+ return reply.get("result")
104
+
105
+
106
+ class _Session:
107
+ def __init__(self, task: Task):
108
+ self.task, self.lock, self.last = task, threading.Lock(), time.monotonic()
109
+
110
+
111
+ class ApiServer:
112
+ def __init__(self, vault: Vault, port: int = 0, token: str | None = None, idle_minutes: float = 30,
113
+ exec_timeout: float = 120, max_tasks: int = 1000):
114
+ self.vault = vault
115
+ self.token = token or secrets.token_urlsafe(32)
116
+ self.idle, self.exec_timeout, self.max_tasks = idle_minutes * 60, exec_timeout, max_tasks
117
+ self.sessions: dict[str, _Session] = {}
118
+ self.pending: dict[str, tuple[_Exchange, float]] = {}
119
+ self._nonces: dict[str, float] = {}
120
+ self._lock = threading.Lock()
121
+ server = self
122
+
123
+ class Handler(_Handler):
124
+ api = server
125
+
126
+ self.httpd = _Server(("127.0.0.1", port), Handler)
127
+ self.httpd.daemon_threads = True
128
+ self.port = self.httpd.server_address[1]
129
+ self.url = f"http://127.0.0.1:{self.port}"
130
+
131
+ # ------------------------------------------------------------ lifecycle
132
+ def serve_forever(self) -> None:
133
+ self.httpd.serve_forever(poll_interval=0.1) # also how quickly shutdown() returns
134
+
135
+ def start(self) -> ApiServer:
136
+ threading.Thread(target=self.serve_forever, daemon=True, name="eurycleia-api").start()
137
+ return self
138
+
139
+ def shutdown(self) -> None:
140
+ self.httpd.shutdown()
141
+ self.httpd.server_close()
142
+
143
+ def write_connection_file(self, path: Path) -> Path:
144
+ """Where adapters find the URL and token. Written owner-only, all at once, never through a symbolic
145
+ link, and never over the file of another `eurycleia api` that is still running."""
146
+ path = Path(path)
147
+ if not path.parent.exists():
148
+ path.parent.mkdir(parents=True, mode=0o700)
149
+ owner_only(path.parent)
150
+ if path.is_symlink():
151
+ raise ApiError(f"{path} is a symbolic link; refusing to write the token through it")
152
+ if path.exists():
153
+ try:
154
+ other = int(json.loads(path.read_text()).get("pid") or 0)
155
+ except (ValueError, TypeError, AttributeError, OSError):
156
+ other = 0
157
+ if other and other != os.getpid() and _alive(other):
158
+ raise ApiError(f"another eurycleia api (process {other}) is using {path}; stop it, "
159
+ "or give this one its own --connection-file")
160
+ tmp = path.with_name(f".{path.name}.{secrets.token_hex(6)}.tmp")
161
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
162
+ fd = os.open(tmp, flags, 0o600)
163
+ try:
164
+ owner_only(tmp) # Windows ignores 0600: restrict it before the token goes in
165
+ with os.fdopen(fd, "wb") as f:
166
+ f.write(json.dumps({"url": self.url, "token": self.token, "pid": os.getpid()}).encode())
167
+ f.flush()
168
+ os.fsync(f.fileno())
169
+ os.replace(tmp, path) # replaces a link or loose file; never writes through it
170
+ except BaseException:
171
+ tmp.unlink(missing_ok=True)
172
+ raise
173
+ self._conn_file = path
174
+ return path
175
+
176
+ def remove_connection_file(self) -> None:
177
+ """Remove the connection file, but only if it's still ours (not a newer server's)."""
178
+ path = getattr(self, "_conn_file", None)
179
+ try:
180
+ if path and json.loads(path.read_text()).get("token") == self.token:
181
+ path.unlink()
182
+ except (OSError, ValueError, AttributeError):
183
+ pass
184
+
185
+ def _fresh_nonce(self, nonce: str) -> bool:
186
+ """Each signed request's random value is accepted once (replays are refused)."""
187
+ now = time.monotonic()
188
+ with self._lock:
189
+ if len(self._nonces) > 10000:
190
+ for k in [k for k, t in self._nonces.items() if now - t > 2 * AUTH_WINDOW + 5]:
191
+ del self._nonces[k]
192
+ if len(self._nonces) > 400_000:
193
+ return False # flooded: refuse rather than grow without end
194
+ if nonce in self._nonces:
195
+ return False
196
+ self._nonces[nonce] = now
197
+ return True
198
+
199
+ # -------------------------------------------------------------- actions
200
+ def _expire(self) -> None:
201
+ now = time.monotonic()
202
+ with self._lock:
203
+ for sid in [s for s, v in self.sessions.items() if now - v.last > self.idle]:
204
+ del self.sessions[sid]
205
+ for eid in [e for e, (_, t) in self.pending.items() if now - t > self.exec_timeout]:
206
+ del self.pending[eid]
207
+
208
+ def start_task(self, body: dict[str, Any]) -> tuple[int, dict[str, Any]]:
209
+ self._expire()
210
+ template, trusted = body.get("template"), body.get("trusted") or {}
211
+ if not isinstance(template, str) or not isinstance(trusted, dict):
212
+ return 400, {"error": "give 'template' (a task name) and 'trusted' (an object)"}
213
+ with self._lock:
214
+ if len(self.sessions) >= self.max_tasks:
215
+ return 429, {"error": "too many open tasks; end some first"}
216
+ if not all(isinstance(k, str) and k.isidentifier() for k in trusted):
217
+ return 400, {"error": "trusted input names must be plain names"}
218
+ try:
219
+ task = self.vault.start_task(template, **trusted)
220
+ except (KeyError, ValueError) as e:
221
+ return 400, {"error": str(e).strip("'\"")}
222
+ except TypeError:
223
+ return 400, {"error": "a trusted input has a reserved name"}
224
+ sid = secrets.token_urlsafe(16)
225
+ with self._lock:
226
+ self.sessions[sid] = _Session(task)
227
+ return 200, {"task": sid, "tools": task.tool_specs()}
228
+
229
+ def _session(self, sid: str) -> _Session | None:
230
+ self._expire()
231
+ with self._lock:
232
+ s = self.sessions.get(sid)
233
+ if s:
234
+ s.last = time.monotonic()
235
+ return s
236
+
237
+ def run(self, sid: str, op: str, body: dict[str, Any]) -> tuple[int, dict[str, Any]]:
238
+ s = self._session(sid)
239
+ if s is None:
240
+ return 404, {"error": "no such task (it ended or expired)"}
241
+ if op == "call":
242
+ name, args = body.get("name"), body.get("arguments") or {}
243
+ if not isinstance(name, str) or not isinstance(args, dict):
244
+ return 400, {"error": "give 'name' (a tool) and 'arguments' (an object)"}
245
+ fn = lambda: s.task.call_tool(name, args) # noqa: E731
246
+ elif op == "read":
247
+ source, key, fields = body.get("source"), body.get("key"), body.get("fields")
248
+ if not isinstance(source, str) or (fields is not None and not isinstance(fields, list)):
249
+ return 400, {"error": "give 'source', and optionally 'key' and 'fields' (a list)"}
250
+ fn = lambda: s.task.read(source, key, fields=fields) # noqa: E731
251
+ elif op == "act":
252
+ sink, args = body.get("sink"), body.get("args") or {}
253
+ if not isinstance(sink, str) or not isinstance(args, dict):
254
+ return 400, {"error": "give 'sink' and 'args' (an object)"}
255
+ fn = lambda: s.task.act(sink, **args) # noqa: E731
256
+ elif op == "end":
257
+ with self._lock:
258
+ self.sessions.pop(sid, None)
259
+ return 200, {"status": "ended"}
260
+ else:
261
+ return 404, {"error": "unknown operation"}
262
+ ex = _Exchange(self.exec_timeout)
263
+
264
+ def worker() -> None:
265
+ _current.exchange = ex
266
+ # one call at a time per task (tasks keep state). If an earlier call is stuck, give up rather
267
+ # than queue: a queued action could otherwise run after the app was told it timed out.
268
+ # wait longer than an earlier call can take to time out, so a slow app never makes this one fail
269
+ if not s.lock.acquire(timeout=self.exec_timeout + 30):
270
+ ex.outbox.put({"status": "error", "message": "the task is still busy with an earlier call"})
271
+ return
272
+ try:
273
+ out = {"status": "ok", "result": fn()}
274
+ except Blocked as e:
275
+ out = {"status": "blocked", "reason": e.reason}
276
+ except SinkError as e: # already masked by the vault
277
+ out = {"status": "error", "message": str(e)}
278
+ except KeyError as e:
279
+ out = {"status": "error", "message": f"not available: {e}"}
280
+ except TypeError as e: # e.g. a sink called with arguments it doesn't take
281
+ out = {"status": "error", "message": f"bad arguments: {type(e).__name__}"}
282
+ except Exception as e: # noqa: BLE001 - never echo internals, which may hold values
283
+ log.warning("api %s failed: %s", op, type(e).__name__)
284
+ out = {"status": "error", "message": "internal error (see the server log)"}
285
+ finally:
286
+ _current.exchange = None
287
+ s.lock.release()
288
+ ex.outbox.put(out)
289
+
290
+ threading.Thread(target=worker, daemon=True, name="eurycleia-api-call").start()
291
+ return self._next(ex)
292
+
293
+ def _next(self, ex: _Exchange) -> tuple[int, dict[str, Any]]:
294
+ try:
295
+ item = ex.outbox.get(timeout=self.exec_timeout * 2 + 60)
296
+ except queue.Empty:
297
+ return 504, {"error": "timed out"}
298
+ if item.get("status") == "execute":
299
+ with self._lock:
300
+ self.pending[ex.id] = (ex, time.monotonic())
301
+ return 200, item
302
+
303
+ def finish(self, eid: str, body: dict[str, Any]) -> tuple[int, dict[str, Any]]:
304
+ with self._lock:
305
+ entry = self.pending.pop(eid, None)
306
+ if entry is None:
307
+ return 404, {"error": "no such pending action (it finished or timed out)"}
308
+ ex, _ = entry
309
+ ex.inbox.put({"error": body["error"]} if "error" in body else {"result": body.get("result")})
310
+ return self._next(ex)
311
+
312
+
313
+ class _Server(ThreadingHTTPServer):
314
+ request_queue_size = 256 # many agents connecting at once (the default of 5 drops connections)
315
+ daemon_threads = True
316
+ max_connections = 256 # beyond this, new connections are closed straight away
317
+
318
+ def __init__(self, *a: Any, **kw: Any):
319
+ super().__init__(*a, **kw)
320
+ self._slots = threading.BoundedSemaphore(self.max_connections)
321
+
322
+ def process_request(self, request: Any, client_address: Any) -> None:
323
+ if not self._slots.acquire(blocking=False):
324
+ self.shutdown_request(request) # too many open connections (e.g. a slow-connection attack)
325
+ return
326
+ try:
327
+ super().process_request(request, client_address)
328
+ except Exception:
329
+ self._slots.release()
330
+ raise
331
+
332
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
333
+ try:
334
+ super().process_request_thread(request, client_address)
335
+ finally:
336
+ self._slots.release()
337
+
338
+
339
+ # ------------------------------------------------------------------ request signing
340
+ # The token is a shared secret and never travels over the connection. Each request carries the time, a
341
+ # one-off random value and an HMAC over them, the method, the path and the body; each reply carries an
342
+ # HMAC over the same random value, the status and the reply body. So the server knows the request came
343
+ # from someone holding the token (and wasn't replayed), and the adapter knows the reply came from the
344
+ # real eurycleia, not another program listening on the same port.
345
+ AUTH_WINDOW = 120
346
+
347
+
348
+ def request_mac(token: str, method: str, path: str, ts: str, nonce: str, body: bytes) -> str:
349
+ msg = "\n".join(["TV1", method, path, ts, nonce, hashlib.sha256(body).hexdigest()])
350
+ return hmac.new(token.encode(), msg.encode(), hashlib.sha256).hexdigest()
351
+
352
+
353
+ def response_mac(token: str, nonce: str, status: int, body: bytes) -> str:
354
+ msg = "\n".join(["TV1-RESPONSE", nonce, str(status), hashlib.sha256(body).hexdigest()])
355
+ return hmac.new(token.encode(), msg.encode(), hashlib.sha256).hexdigest()
356
+
357
+
358
+ def signed_headers(token: str, method: str, path: str, body: bytes) -> dict[str, str]:
359
+ """Headers for a request to `eurycleia api` (what the adapters do, in Python)."""
360
+ ts, nonce = str(int(time.time())), secrets.token_hex(16)
361
+ return {"x-eurycleia-time": ts, "x-eurycleia-nonce": nonce,
362
+ "x-eurycleia-auth": request_mac(token, method, path, ts, nonce, body)}
363
+
364
+
365
+ class _Handler(BaseHTTPRequestHandler):
366
+ api: ApiServer
367
+ server_version = "eurycleia-api"
368
+ sys_version = ""
369
+ timeout = 30 # a client that stops sending is dropped (no thread held forever)
370
+ protocol_version = "HTTP/1.0"
371
+
372
+ def log_message(self, fmt: str, *args: Any) -> None: # no request details in logs
373
+ pass
374
+
375
+ def _send(self, status: int, payload: dict[str, Any]) -> None:
376
+ try:
377
+ data = json.dumps(payload, default=str).encode()
378
+ except (TypeError, ValueError, RecursionError):
379
+ status, data = 500, b'{"error": "reply could not be encoded"}'
380
+ self.send_response(status)
381
+ self.send_header("content-type", "application/json")
382
+ self.send_header("content-length", str(len(data)))
383
+ self.send_header("cache-control", "no-store")
384
+ self.send_header("connection", "close") # one request per connection: say so, so clients never reuse it
385
+ nonce = self.headers.get("x-eurycleia-nonce") or ""
386
+ if getattr(self, "_signed", False) and nonce:
387
+ self.send_header("x-eurycleia-auth", response_mac(self.api.token, nonce, status, data))
388
+ self.end_headers()
389
+ self.wfile.write(data)
390
+
391
+ def _check(self) -> bytes | None:
392
+ """All the guards. Returns the request body, or None after sending a refusal."""
393
+ self._signed = False
394
+ host = (self.headers.get("host") or "").lower()
395
+ if host not in (f"127.0.0.1:{self.api.port}", f"localhost:{self.api.port}"):
396
+ self._send(421, {"error": "wrong Host header"}) # blocks DNS-rebinding tricks
397
+ return None
398
+ if self.headers.get("origin") is not None:
399
+ self._send(403, {"error": "requests from web pages are refused"})
400
+ return None
401
+ try:
402
+ n = int(self.headers.get("content-length") or 0)
403
+ except ValueError:
404
+ n = -1
405
+ if n < 0 or n > MAX_BODY:
406
+ if 0 < n <= 4 * MAX_BODY: # read and drop it, so the refusal arrives (Windows otherwise resets
407
+ left = n # the connection when unread data is left, and the reply is lost)
408
+ while left > 0:
409
+ chunk = self.rfile.read(min(65536, left))
410
+ if not chunk:
411
+ break
412
+ left -= len(chunk)
413
+ self._send(413, {"error": "request too large"})
414
+ return None
415
+ body = self.rfile.read(n) if n else b""
416
+ ts, nonce = self.headers.get("x-eurycleia-time") or "", self.headers.get("x-eurycleia-nonce") or ""
417
+ mac = self.headers.get("x-eurycleia-auth") or ""
418
+ good = request_mac(self.api.token, self.command, self.path, ts, nonce, body)
419
+ if not (ts.isdigit() and 16 <= len(nonce) <= 64 and hmac.compare_digest(mac.encode(), good.encode())):
420
+ self._send(401, {"error": "request not signed with this server's token"})
421
+ return None
422
+ if abs(time.time() - int(ts)) > AUTH_WINDOW or not self.api._fresh_nonce(nonce):
423
+ self._send(401, {"error": "request expired or replayed"})
424
+ return None
425
+ self._signed = True # from here on, replies are signed
426
+ return body
427
+
428
+ def handle_one_request(self) -> None:
429
+ try:
430
+ super().handle_one_request()
431
+ except (RecursionError, ValueError, TypeError) as e: # never a dropped connection with no answer
432
+ log.warning("api request failed: %s", type(e).__name__)
433
+ try:
434
+ self._send(400, {"error": "bad request"})
435
+ except OSError:
436
+ pass
437
+
438
+ def do_GET(self) -> None: # noqa: N802
439
+ if self._check() is None:
440
+ return
441
+ if self.path == "/v1/health":
442
+ self._send(200, {"ok": True, "version": __version__})
443
+ else:
444
+ self._send(404, {"error": "not found"})
445
+
446
+ def do_POST(self) -> None: # noqa: N802
447
+ raw = self._check()
448
+ if raw is None:
449
+ return
450
+ if (self.headers.get("content-type") or "").split(";")[0].strip().lower() != "application/json":
451
+ self._send(415, {"error": "send JSON (content-type: application/json)"})
452
+ return
453
+ try:
454
+ body = json.loads(raw or b"{}")
455
+ except (ValueError, RecursionError): # also bad UTF-8 and numbers too long to convert
456
+ self._send(400, {"error": "body isn't valid JSON"})
457
+ return
458
+ if not isinstance(body, dict):
459
+ self._send(400, {"error": "body must be a JSON object"})
460
+ return
461
+ try:
462
+ json.dumps(body, ensure_ascii=False).encode("utf-8") # e.g. a lone "\ud800" can't be real text
463
+ except UnicodeEncodeError:
464
+ self._send(400, {"error": "body contains text that isn't valid Unicode"})
465
+ return
466
+ parts = self.path.strip("/").split("/")
467
+ if parts == ["v1", "tasks"]:
468
+ self._send(*self.api.start_task(body))
469
+ elif len(parts) == 4 and parts[:2] == ["v1", "tasks"]:
470
+ self._send(*self.api.run(parts[2], parts[3], body))
471
+ elif len(parts) == 3 and parts[:2] == ["v1", "exec"]:
472
+ self._send(*self.api.finish(parts[2], body))
473
+ else:
474
+ self._send(404, {"error": "not found"})