spatial-computing 0.7.0__py3-none-any.whl → 0.9.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.
- spatial/__init__.py +1 -1
- spatial/cli.py +105 -4
- spatial/compute/worker.py +12 -4
- spatial/core/auth.py +170 -0
- spatial/core/ledger.py +9 -4
- spatial/core/protocol.py +77 -26
- spatial/core/registry.py +3 -0
- spatial/fleet/__init__.py +18 -0
- spatial/fleet/agent.py +137 -0
- spatial/fleet/hub.py +279 -0
- spatial/memory/pageserver.py +9 -2
- spatial/q/compiler.py +65 -0
- spatial/runtime/runner.py +12 -4
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/METADATA +3 -2
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/RECORD +19 -15
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/WHEEL +0 -0
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/entry_points.txt +0 -0
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/licenses/LICENSE +0 -0
- {spatial_computing-0.7.0.dist-info → spatial_computing-0.9.0.dist-info}/top_level.txt +0 -0
spatial/__init__.py
CHANGED
spatial/cli.py
CHANGED
|
@@ -83,10 +83,81 @@ def cmd_bench(a):
|
|
|
83
83
|
return rc
|
|
84
84
|
|
|
85
85
|
|
|
86
|
+
def _read_token(path: str) -> bytes:
|
|
87
|
+
raw = Path(path).read_bytes()
|
|
88
|
+
return raw.strip() if raw.startswith(b"spc1.") else raw # scoped tokens are text, shared secrets are raw bytes
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _hub_client(a):
|
|
92
|
+
from .core.protocol import RpcClient
|
|
93
|
+
host, _, port = a.hub.rpartition(":")
|
|
94
|
+
return RpcClient(host or "127.0.0.1", int(port), _read_token(a.token_file), timeout=30)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_agent(a):
|
|
98
|
+
from .fleet import Agent
|
|
99
|
+
host, _, port = a.hub.rpartition(":")
|
|
100
|
+
ag = Agent(host or "127.0.0.1", int(port), _read_token(a.token_file), name=a.name, interval_s=a.interval,
|
|
101
|
+
usd_per_hour=a.usd_per_hour, labels=[x for x in a.labels.split(",") if x], run_tasks=not a.no_tasks)
|
|
102
|
+
print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"))
|
|
103
|
+
ag.run_forever()
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_fleet(a):
|
|
108
|
+
cli = _hub_client(a)
|
|
109
|
+
if a.action == "status":
|
|
110
|
+
rh, _ = cli.call({"op": "nodes", "window_s": a.window})
|
|
111
|
+
print(f"{'node':<22}{'up':<4}{'cores':>6}{'cpu%':>7}{'ram free%':>10}{'gpus':>5}{'gpu%':>6}{'$/h':>7} samples")
|
|
112
|
+
f = lambda v, n=0: "-" if v is None else f"{v:.{n}f}"
|
|
113
|
+
for r in rh["nodes"]:
|
|
114
|
+
print(f"{r['node']:<22}{'yes' if r['alive'] else 'NO':<4}{f(r['cores']):>6}{f(r['cpu_avg']):>7}{f(r['ram_avail_pct']):>10}"
|
|
115
|
+
f"{r['gpu_count']:>5}{f(r['gpu_util_avg']):>6}{f(r['usd_per_hour'], 2):>7} {r['samples']}")
|
|
116
|
+
u = rh["utilization"]
|
|
117
|
+
print(f"fleet: {u['nodes']} node(s), {u['cores']} cores, CPU utilization "
|
|
118
|
+
f"{'-' if u['cpu_utilization_pct'] is None else format(u['cpu_utilization_pct'], '.1f') + '%'} (last {a.window:g} s)")
|
|
119
|
+
elif a.action == "advise":
|
|
120
|
+
rh, _ = cli.call({"op": "advise", "window_s": a.window})
|
|
121
|
+
if not rh["recommendations"]:
|
|
122
|
+
print("no recommendation: nothing in the measurements justifies a change")
|
|
123
|
+
for r in rh["recommendations"]:
|
|
124
|
+
extra = f" [estimated saving {r['est_saving_usd_per_hour']:.2f} $/h, {r['est_saving_usd_per_month']:.0f} $/month]" if "est_saving_usd_per_hour" in r else ""
|
|
125
|
+
print(f"[{r['severity']}] {r['kind']}: {r['text']}{extra}")
|
|
126
|
+
print(f" evidence: {r['evidence']}")
|
|
127
|
+
elif a.action == "submit":
|
|
128
|
+
import json as _json
|
|
129
|
+
rh, _ = cli.call({"op": "submit", "workload": a.workload, "params": _json.loads(a.params),
|
|
130
|
+
"needs": _json.loads(a.needs)})
|
|
131
|
+
print(rh["task_id"])
|
|
132
|
+
else:
|
|
133
|
+
rh, _ = cli.call({"op": "task", "task_id": a.task_id})
|
|
134
|
+
t = rh["task"]
|
|
135
|
+
print({k: t.get(k) for k in ("id", "state", "node", "result", "error", "wall_s")})
|
|
136
|
+
cli.close()
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_token(a):
|
|
141
|
+
from .core import auth
|
|
142
|
+
if a.action == "init":
|
|
143
|
+
auth.init_master_key(a.master_key_file)
|
|
144
|
+
print(f"master key written to {a.master_key_file} (mode 600). Keep it private; it can issue any credential.")
|
|
145
|
+
return 0
|
|
146
|
+
az = auth.authorizer_from_file(a.master_key_file)
|
|
147
|
+
print(az.issue(a.name, [s for s in a.scopes.split(",") if s], ttl_s=a.ttl, max_ops=a.max_ops, max_bytes=a.max_bytes))
|
|
148
|
+
return 0
|
|
149
|
+
|
|
150
|
+
|
|
86
151
|
def cmd_worker(a):
|
|
87
152
|
mod = {"compute": "spatial.compute.worker", "memory": "spatial.memory.pageserver",
|
|
88
|
-
"runtime": "spatial.runtime.runner"}[a.kind]
|
|
89
|
-
cmd = [sys.executable, "-m", mod, "--
|
|
153
|
+
"runtime": "spatial.runtime.runner", "hub": "spatial.fleet.hub"}[a.kind]
|
|
154
|
+
cmd = [sys.executable, "-m", mod, "--host", a.host, "--port", str(a.port)]
|
|
155
|
+
if a.token_file:
|
|
156
|
+
cmd += ["--token-file", a.token_file]
|
|
157
|
+
if a.master_key_file:
|
|
158
|
+
cmd += ["--master-key-file", a.master_key_file]
|
|
159
|
+
if a.audit_log:
|
|
160
|
+
cmd += ["--audit-log", a.audit_log]
|
|
90
161
|
if a.allow_remote:
|
|
91
162
|
cmd.append("--allow-remote")
|
|
92
163
|
return subprocess.run(cmd).returncode
|
|
@@ -115,13 +186,43 @@ def main(argv=None):
|
|
|
115
186
|
p.add_argument("name", choices=[*BENCHES, "all"])
|
|
116
187
|
p.set_defaults(fn=cmd_bench)
|
|
117
188
|
p = sub.add_parser("serve", help="start a compute worker, a page server or a sandboxed binary runner (loopback by default)")
|
|
118
|
-
p.add_argument("kind", choices=["compute", "memory", "runtime"])
|
|
119
|
-
p.add_argument("--token-file",
|
|
189
|
+
p.add_argument("kind", choices=["compute", "memory", "runtime", "hub"])
|
|
190
|
+
p.add_argument("--token-file", help="shared secret: every client may do everything")
|
|
191
|
+
p.add_argument("--master-key-file", help="scoped credentials with quotas and an audit log (see `spatial token`)")
|
|
192
|
+
p.add_argument("--audit-log")
|
|
120
193
|
p.add_argument("--host", default="127.0.0.1")
|
|
121
194
|
p.add_argument("--port", type=int, default=0)
|
|
122
195
|
p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
|
|
123
196
|
p.set_defaults(fn=cmd_worker)
|
|
197
|
+
p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
|
|
198
|
+
p.add_argument("--hub", required=True, help="host:port of the hub")
|
|
199
|
+
p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
|
|
200
|
+
p.add_argument("--name")
|
|
201
|
+
p.add_argument("--interval", type=float, default=5.0)
|
|
202
|
+
p.add_argument("--usd-per-hour", type=float, help="what this machine costs per hour (for estimates only)")
|
|
203
|
+
p.add_argument("--labels", default="")
|
|
204
|
+
p.add_argument("--no-tasks", action="store_true", help="measure only; never run tasks")
|
|
205
|
+
p.set_defaults(fn=cmd_agent)
|
|
206
|
+
p = sub.add_parser("fleet", help="see and use the fleet through a hub")
|
|
207
|
+
p.add_argument("action", choices=["status", "advise", "submit", "result"])
|
|
208
|
+
p.add_argument("--hub", required=True)
|
|
209
|
+
p.add_argument("--token-file", required=True, help="scoped token with fleet:read (status/advise) or fleet:submit")
|
|
210
|
+
p.add_argument("--window", type=float, default=60.0)
|
|
211
|
+
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
212
|
+
p.add_argument("--task-id", type=int)
|
|
213
|
+
p.set_defaults(fn=cmd_fleet)
|
|
214
|
+
p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
|
|
215
|
+
p.add_argument("action", choices=["init", "issue"])
|
|
216
|
+
p.add_argument("--master-key-file", required=True)
|
|
217
|
+
p.add_argument("--name", default="tenant")
|
|
218
|
+
p.add_argument("--scopes", default="", help="comma list, e.g. run:mandel_numba,mem:read,exec:elf (trailing * = prefix)")
|
|
219
|
+
p.add_argument("--ttl", type=float, default=3600, help="seconds")
|
|
220
|
+
p.add_argument("--max-ops", type=int)
|
|
221
|
+
p.add_argument("--max-bytes", type=int)
|
|
222
|
+
p.set_defaults(fn=cmd_token)
|
|
124
223
|
a = ap.parse_args(argv)
|
|
224
|
+
if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
|
|
225
|
+
ap.error("serve needs exactly one of --token-file or --master-key-file")
|
|
125
226
|
try:
|
|
126
227
|
return a.fn(a)
|
|
127
228
|
except (Exception, SystemExit) as e: # user-facing tool: one clean line, no traceback
|
spatial/compute/worker.py
CHANGED
|
@@ -14,6 +14,7 @@ import sys
|
|
|
14
14
|
import time
|
|
15
15
|
from pathlib import Path
|
|
16
16
|
|
|
17
|
+
from ..core.auth import authorizer_from_file, require
|
|
17
18
|
from ..core.protocol import RpcClient, RpcServer
|
|
18
19
|
from . import workloads
|
|
19
20
|
|
|
@@ -23,6 +24,7 @@ def _handler(header: dict, blob: bytes):
|
|
|
23
24
|
if op == "ping":
|
|
24
25
|
return {"pong": True, "pid": os.getpid()}, b""
|
|
25
26
|
if op == "run":
|
|
27
|
+
require(f"run:{header.get('workload')}")
|
|
26
28
|
t = os.times()
|
|
27
29
|
c0, w0 = t.user + t.system, time.perf_counter()
|
|
28
30
|
result = workloads.run(header["workload"], **header.get("params", {}))
|
|
@@ -32,8 +34,9 @@ def _handler(header: dict, blob: bytes):
|
|
|
32
34
|
raise ValueError(f"unknown op {op!r}")
|
|
33
35
|
|
|
34
36
|
|
|
35
|
-
def serve(token: bytes, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False
|
|
36
|
-
|
|
37
|
+
def serve(token: bytes | None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
|
|
38
|
+
authorizer=None) -> RpcServer:
|
|
39
|
+
return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer)
|
|
37
40
|
|
|
38
41
|
|
|
39
42
|
class LocalWorkerProcess:
|
|
@@ -74,13 +77,18 @@ class LocalWorkerProcess:
|
|
|
74
77
|
|
|
75
78
|
def main():
|
|
76
79
|
ap = argparse.ArgumentParser()
|
|
77
|
-
ap.add_argument("--token-file",
|
|
80
|
+
ap.add_argument("--token-file", help="shared secret (every client may do everything)")
|
|
81
|
+
ap.add_argument("--master-key-file", help="issue scoped credentials instead (see `spatial token`)")
|
|
82
|
+
ap.add_argument("--audit-log")
|
|
78
83
|
ap.add_argument("--host", default="127.0.0.1")
|
|
79
84
|
ap.add_argument("--port", type=int, default=0)
|
|
80
85
|
ap.add_argument("--allow-remote", action="store_true",
|
|
81
86
|
help="explicit consent to accept non-loopback connections")
|
|
82
87
|
a = ap.parse_args()
|
|
83
|
-
|
|
88
|
+
if bool(a.token_file) == bool(a.master_key_file):
|
|
89
|
+
raise SystemExit("give exactly one of --token-file or --master-key-file")
|
|
90
|
+
srv = serve(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
91
|
+
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None)
|
|
84
92
|
print(f"PORT {srv.port}", flush=True)
|
|
85
93
|
srv.serve_forever()
|
|
86
94
|
|
spatial/core/auth.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Scoped credentials, quotas and an audit trail for SWP/2 services.
|
|
2
|
+
|
|
3
|
+
A server started with a master key issues credentials to tenants. A credential names the
|
|
4
|
+
tenant, the scopes it may use, an expiry and optional quotas; it is signed with the master
|
|
5
|
+
key, so the server needs no database. The tenant's per-credential secret is
|
|
6
|
+
HMAC(master, credential): only the issuer can derive it, and it is what authenticates the
|
|
7
|
+
handshake. The token handed to a tenant is "<credential>~<secret hex>".
|
|
8
|
+
|
|
9
|
+
Scopes are strings such as "run:mandel_numba", "mem:read", "mem:write", "exec:elf"; a trailing
|
|
10
|
+
"*" matches a prefix ("run:*", "*"). Services call require(scope) before acting.
|
|
11
|
+
Every request (allowed or denied) is appended to a hash-chained audit ledger.
|
|
12
|
+
|
|
13
|
+
Limits: revocation and usage counters live in the server process (restart resets counters);
|
|
14
|
+
a stolen token works until it expires or is revoked.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import hashlib
|
|
20
|
+
import hmac
|
|
21
|
+
import json
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
from .ledger import Ledger
|
|
27
|
+
|
|
28
|
+
PREFIX = "spc1"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class QuotaExceeded(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthError(Exception):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Principal:
|
|
41
|
+
name: str
|
|
42
|
+
scopes: tuple[str, ...]
|
|
43
|
+
expires: float
|
|
44
|
+
max_ops: int | None = None
|
|
45
|
+
max_bytes: int | None = None
|
|
46
|
+
cred: str = ""
|
|
47
|
+
ops: int = 0
|
|
48
|
+
nbytes: int = 0
|
|
49
|
+
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
50
|
+
|
|
51
|
+
def allows(self, scope: str) -> bool:
|
|
52
|
+
for s in self.scopes:
|
|
53
|
+
if s == "*" or s == scope or (s.endswith("*") and scope.startswith(s[:-1])):
|
|
54
|
+
return True
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_ctx = threading.local()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def current() -> Principal | None:
|
|
62
|
+
return getattr(_ctx, "principal", None)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_current(p: Principal | None) -> None:
|
|
66
|
+
_ctx.principal = p
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def require(scope: str) -> None:
|
|
70
|
+
"""Raise PermissionError unless the calling tenant holds `scope` (always true without auth)."""
|
|
71
|
+
p = current()
|
|
72
|
+
if p is not None and not p.allows(scope):
|
|
73
|
+
raise PermissionError(f"scope '{scope}' not granted to '{p.name}'")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _b64(b: bytes) -> str:
|
|
77
|
+
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _unb64(s: str) -> bytes:
|
|
81
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Authorizer:
|
|
85
|
+
def __init__(self, master_key: bytes, audit: Ledger | None = None):
|
|
86
|
+
if len(master_key) < 16:
|
|
87
|
+
raise ValueError("master key must be at least 16 bytes")
|
|
88
|
+
self._master = master_key
|
|
89
|
+
self.audit = audit
|
|
90
|
+
self._revoked: set[str] = set()
|
|
91
|
+
self._seen: dict[str, Principal] = {}
|
|
92
|
+
|
|
93
|
+
def _sig(self, payload: str) -> str:
|
|
94
|
+
return hmac.new(self._master, b"sig|" + payload.encode(), hashlib.sha256).hexdigest()[:32]
|
|
95
|
+
|
|
96
|
+
def secret_for(self, cred: str) -> bytes:
|
|
97
|
+
return hmac.new(self._master, b"secret|" + cred.encode(), hashlib.sha256).digest()
|
|
98
|
+
|
|
99
|
+
def issue(self, name: str, scopes: list[str], ttl_s: float = 3600, max_ops: int | None = None,
|
|
100
|
+
max_bytes: int | None = None) -> str:
|
|
101
|
+
body = {"n": name, "s": list(scopes), "e": time.time() + ttl_s}
|
|
102
|
+
if max_ops is not None:
|
|
103
|
+
body["o"] = max_ops
|
|
104
|
+
if max_bytes is not None:
|
|
105
|
+
body["b"] = max_bytes
|
|
106
|
+
payload = _b64(json.dumps(body, separators=(",", ":")).encode())
|
|
107
|
+
cred = f"{PREFIX}.{payload}.{self._sig(payload)}"
|
|
108
|
+
return f"{cred}~{self.secret_for(cred).hex()}"
|
|
109
|
+
|
|
110
|
+
def revoke(self, name: str) -> None:
|
|
111
|
+
self._revoked.add(name)
|
|
112
|
+
|
|
113
|
+
def principal(self, cred: str) -> Principal:
|
|
114
|
+
"""Verify signature, expiry and revocation. Raises AuthError."""
|
|
115
|
+
try:
|
|
116
|
+
prefix, payload, sig = cred.split(".")
|
|
117
|
+
except ValueError:
|
|
118
|
+
raise AuthError("malformed credential")
|
|
119
|
+
if prefix != PREFIX or not hmac.compare_digest(sig, self._sig(payload)):
|
|
120
|
+
raise AuthError("bad credential signature")
|
|
121
|
+
body = json.loads(_unb64(payload))
|
|
122
|
+
if body["e"] < time.time():
|
|
123
|
+
raise AuthError("credential expired")
|
|
124
|
+
if body["n"] in self._revoked:
|
|
125
|
+
raise AuthError("credential revoked")
|
|
126
|
+
if cred not in self._seen:
|
|
127
|
+
self._seen[cred] = Principal(body["n"], tuple(body["s"]), body["e"], body.get("o"), body.get("b"), cred)
|
|
128
|
+
return self._seen[cred]
|
|
129
|
+
|
|
130
|
+
def charge(self, p: Principal, nbytes: int) -> None:
|
|
131
|
+
with p.lock:
|
|
132
|
+
if p.max_ops is not None and p.ops + 1 > p.max_ops:
|
|
133
|
+
raise QuotaExceeded(f"'{p.name}' exceeded {p.max_ops} operations")
|
|
134
|
+
if p.max_bytes is not None and p.nbytes + nbytes > p.max_bytes:
|
|
135
|
+
raise QuotaExceeded(f"'{p.name}' exceeded {p.max_bytes} bytes")
|
|
136
|
+
p.ops += 1
|
|
137
|
+
p.nbytes += nbytes
|
|
138
|
+
|
|
139
|
+
def log(self, p: Principal | None, op: str, ok: bool, detail: str = "", nbytes: int = 0) -> None:
|
|
140
|
+
if self.audit is not None:
|
|
141
|
+
self.audit.decide("auth", f"{p.name if p else '?'}:{op}", "allowed" if ok else f"denied: {detail}",
|
|
142
|
+
ok=ok, bytes=nbytes)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse_token(token: bytes) -> tuple[bytes, bytes]:
|
|
146
|
+
"""(credential, secret) from a client token. A plain shared token has no credential."""
|
|
147
|
+
t = token.decode(errors="ignore") if token.startswith(PREFIX.encode() + b".") else ""
|
|
148
|
+
if t and "~" in t:
|
|
149
|
+
cred, secret_hex = t.split("~", 1)
|
|
150
|
+
return cred.encode(), bytes.fromhex(secret_hex.strip())
|
|
151
|
+
return b"", token
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def init_master_key(path) -> None:
|
|
155
|
+
"""Create a random 32-byte master key file (mode 600). Refuses to overwrite."""
|
|
156
|
+
import os
|
|
157
|
+
from pathlib import Path
|
|
158
|
+
p = Path(path)
|
|
159
|
+
if p.exists():
|
|
160
|
+
raise FileExistsError(f"{p} already exists; refusing to overwrite a master key")
|
|
161
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
162
|
+
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
163
|
+
with os.fdopen(fd, "wb") as f:
|
|
164
|
+
f.write(os.urandom(32))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def authorizer_from_file(master_key_file, audit_path=None) -> Authorizer:
|
|
168
|
+
from pathlib import Path
|
|
169
|
+
audit = Ledger(audit_path) if audit_path else Ledger(Path.home() / ".spatial" / "audit.jsonl")
|
|
170
|
+
return Authorizer(Path(master_key_file).read_bytes(), audit)
|
spatial/core/ledger.py
CHANGED
|
@@ -3,12 +3,15 @@
|
|
|
3
3
|
Every row carries `prev` (hash of the previous row) and `hash` = SHA-256(prev | canonical
|
|
4
4
|
JSON of the row). `verify()` detects an edited, removed or reordered row. This is tamper
|
|
5
5
|
EVIDENCE, not a signature: someone who can rewrite the whole file can rebuild the chain.
|
|
6
|
+
Thread-safe within one process. Two PROCESSES writing the same file would fork the chain: give each
|
|
7
|
+
process its own ledger file.
|
|
6
8
|
"""
|
|
7
9
|
from __future__ import annotations
|
|
8
10
|
|
|
9
11
|
import hashlib
|
|
10
12
|
import json
|
|
11
13
|
import os
|
|
14
|
+
import threading
|
|
12
15
|
import time
|
|
13
16
|
from pathlib import Path
|
|
14
17
|
|
|
@@ -29,6 +32,7 @@ class Ledger:
|
|
|
29
32
|
self.path = Path(path) if path else RESULTS / "ledger.jsonl"
|
|
30
33
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
34
|
self._last = self._tail_hash()
|
|
35
|
+
self._lock = threading.Lock() # services write from one thread per connection
|
|
32
36
|
|
|
33
37
|
def _tail_hash(self) -> str:
|
|
34
38
|
last = GENESIS
|
|
@@ -40,10 +44,11 @@ class Ledger:
|
|
|
40
44
|
|
|
41
45
|
def _append(self, row: dict) -> None:
|
|
42
46
|
row = json.loads(json.dumps(row, default=str)) # normalise before hashing
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
with self._lock: # read-last / hash / write must be one step
|
|
48
|
+
h = _digest(self._last, row)
|
|
49
|
+
with open(self.path, "a") as f:
|
|
50
|
+
f.write(json.dumps({**row, "prev": self._last, "hash": h}) + "\n")
|
|
51
|
+
self._last = h
|
|
47
52
|
|
|
48
53
|
def record(self, m: Measurement) -> Measurement:
|
|
49
54
|
self._append({"type": "measurement", **m.to_dict()})
|
spatial/core/protocol.py
CHANGED
|
@@ -1,18 +1,22 @@
|
|
|
1
|
-
"""SPATIAL wire protocol
|
|
2
|
-
|
|
3
|
-
Handshake server -> client : nonce_s (16
|
|
4
|
-
client -> server :
|
|
5
|
-
|
|
1
|
+
"""SPATIAL wire protocol v2 (SWP/2): authenticated, encrypted, forward-secret RPC over TCP.
|
|
2
|
+
|
|
3
|
+
Handshake server -> client : nonce_s (16) | server ephemeral X25519 public key (32)
|
|
4
|
+
client -> server : u16 cred_len | credential | client ephemeral public key (32) | nonce_c (16)
|
|
5
|
+
| HMAC-SHA256(secret, "SWP2c" | nonce_s | pub_s | pub_c | nonce_c | credential) (32)
|
|
6
|
+
Secret the shared token, or, with scoped credentials, HMAC(master, credential) (see auth.py)
|
|
7
|
+
Keys HKDF-SHA256(ikm = X25519 shared secret | secret, salt = nonce_s | nonce_c)
|
|
8
|
+
-> one AES-256-GCM key per direction
|
|
6
9
|
Record u32 length | AES-GCM(ciphertext | tag), nonce = 4 zero bytes | u64 record counter
|
|
7
10
|
Plaintext u32 header_len | u32 blob_len | header (JSON utf-8) | blob (raw bytes)
|
|
8
11
|
|
|
9
|
-
Properties: the
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
Properties: the secret never crosses the wire; every record is confidential and integrity-
|
|
13
|
+
protected; replayed, reordered or modified records fail authentication; the ephemeral keys
|
|
14
|
+
are discarded after the handshake, so recorded sessions stay unreadable even if the secret is
|
|
15
|
+
stolen later (FORWARD SECRECY). A party that holds the secret *during* a session can still
|
|
16
|
+
impersonate (the secret is the only identity). Use TLS/WireGuard when you need certificates.
|
|
13
17
|
|
|
14
18
|
Safety: servers bind to 127.0.0.1 unless allow_remote=True is passed explicitly.
|
|
15
|
-
No code is ever transferred: requests name allow-listed operations.
|
|
19
|
+
No code is ever transferred except by the sandboxed runner: requests name allow-listed operations.
|
|
16
20
|
"""
|
|
17
21
|
from __future__ import annotations
|
|
18
22
|
|
|
@@ -27,13 +31,17 @@ import threading
|
|
|
27
31
|
from typing import Callable
|
|
28
32
|
|
|
29
33
|
from cryptography.exceptions import InvalidTag
|
|
30
|
-
from cryptography.hazmat.primitives import hashes
|
|
34
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
35
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
|
31
36
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
32
37
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
33
38
|
|
|
39
|
+
from . import auth
|
|
40
|
+
|
|
34
41
|
_HDR = struct.Struct(">II")
|
|
35
42
|
_LEN = struct.Struct(">I")
|
|
36
43
|
MAX_FRAME = 256 * 1024 * 1024
|
|
44
|
+
_RAW = dict(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw)
|
|
37
45
|
|
|
38
46
|
|
|
39
47
|
def _recv_exact(sock: socket.socket, n: int) -> bytes:
|
|
@@ -51,8 +59,8 @@ def _recv_exact(sock: socket.socket, n: int) -> bytes:
|
|
|
51
59
|
class SecureChannel:
|
|
52
60
|
"""Encrypted, ordered record channel over a connected socket."""
|
|
53
61
|
|
|
54
|
-
def __init__(self, sock: socket.socket,
|
|
55
|
-
okm = HKDF(algorithm=hashes.SHA256(), length=64, salt=nonce_s + nonce_c, info=b"SWP/
|
|
62
|
+
def __init__(self, sock: socket.socket, ikm: bytes, nonce_s: bytes, nonce_c: bytes, is_server: bool):
|
|
63
|
+
okm = HKDF(algorithm=hashes.SHA256(), length=64, salt=nonce_s + nonce_c, info=b"SWP/2 keys").derive(ikm)
|
|
56
64
|
c2s, s2c = AESGCM(okm[:32]), AESGCM(okm[32:])
|
|
57
65
|
self._tx, self._rx = (s2c, c2s) if is_server else (c2s, s2c)
|
|
58
66
|
self._ntx = self._nrx = 0
|
|
@@ -81,43 +89,79 @@ class SecureChannel:
|
|
|
81
89
|
return header, plain[_HDR.size + hl:]
|
|
82
90
|
|
|
83
91
|
|
|
92
|
+
def _mac(secret: bytes, nonce_s: bytes, pub_s: bytes, pub_c: bytes, nonce_c: bytes, cred: bytes) -> bytes:
|
|
93
|
+
return hmac.new(secret, b"SWP2c" + nonce_s + pub_s + pub_c + nonce_c + cred, hashlib.sha256).digest()
|
|
94
|
+
|
|
95
|
+
|
|
84
96
|
Handler = Callable[[dict, bytes], tuple[dict, bytes]]
|
|
85
97
|
|
|
86
98
|
|
|
87
99
|
class RpcServer:
|
|
88
|
-
"""Threaded RPC server. Loopback-only by default.
|
|
100
|
+
"""Threaded RPC server. Loopback-only by default.
|
|
89
101
|
|
|
90
|
-
|
|
91
|
-
|
|
102
|
+
token : shared secret (every client is trusted with every scope), or None
|
|
103
|
+
authorizer : scoped credentials, quotas, audit (see auth.py); takes precedence over token
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def __init__(self, handler: Handler, token: bytes | None = None, host: str = "127.0.0.1",
|
|
107
|
+
port: int = 0, allow_remote: bool = False, authorizer: "auth.Authorizer | None" = None):
|
|
92
108
|
if host not in ("127.0.0.1", "localhost", "::1") and not allow_remote:
|
|
93
109
|
raise PermissionError(
|
|
94
110
|
"refusing to bind a non-loopback address without allow_remote=True "
|
|
95
111
|
"(explicit user consent required to expose this machine)")
|
|
112
|
+
if token is None and authorizer is None:
|
|
113
|
+
raise ValueError("RpcServer needs a token or an authorizer")
|
|
96
114
|
outer = self
|
|
97
115
|
|
|
98
116
|
class _H(socketserver.BaseRequestHandler):
|
|
99
117
|
def handle(self):
|
|
100
118
|
s = self.request
|
|
101
119
|
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
120
|
+
eph = X25519PrivateKey.generate()
|
|
121
|
+
pub_s = eph.public_key().public_bytes(**_RAW)
|
|
102
122
|
nonce_s = os.urandom(16)
|
|
103
|
-
s.sendall(nonce_s)
|
|
104
123
|
try:
|
|
105
|
-
|
|
106
|
-
|
|
124
|
+
s.sendall(nonce_s + pub_s)
|
|
125
|
+
(cl,) = struct.unpack(">H", _recv_exact(s, 2))
|
|
126
|
+
cred = _recv_exact(s, cl)
|
|
127
|
+
pub_c, nonce_c, mac = _recv_exact(s, 32), _recv_exact(s, 16), _recv_exact(s, 32)
|
|
128
|
+
except (ConnectionError, OSError):
|
|
107
129
|
return
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
130
|
+
principal = None
|
|
131
|
+
if authorizer is not None:
|
|
132
|
+
try:
|
|
133
|
+
principal = authorizer.principal(cred.decode())
|
|
134
|
+
except (auth.AuthError, ValueError, UnicodeDecodeError, KeyError):
|
|
135
|
+
return # silent drop
|
|
136
|
+
secret = authorizer.secret_for(cred.decode())
|
|
137
|
+
else:
|
|
138
|
+
if cred:
|
|
139
|
+
return
|
|
140
|
+
secret = token
|
|
141
|
+
if not hmac.compare_digest(mac, _mac(secret, nonce_s, pub_s, pub_c, nonce_c, cred)):
|
|
142
|
+
return # silent drop on bad auth
|
|
143
|
+
shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_c))
|
|
144
|
+
ch = SecureChannel(s, shared + secret, nonce_s, nonce_c, is_server=True)
|
|
111
145
|
while True:
|
|
112
146
|
try:
|
|
113
147
|
header, blob = ch.recv()
|
|
114
148
|
except (ConnectionError, OSError, ValueError):
|
|
115
149
|
return
|
|
150
|
+
op = str(header.get("op"))
|
|
116
151
|
try:
|
|
152
|
+
if principal is not None:
|
|
153
|
+
authorizer.charge(principal, len(blob))
|
|
154
|
+
auth.set_current(principal)
|
|
117
155
|
rh, rb = outer.handler(header, blob)
|
|
118
156
|
rh.setdefault("ok", True)
|
|
157
|
+
if authorizer is not None:
|
|
158
|
+
authorizer.log(principal, op, True, nbytes=len(blob))
|
|
119
159
|
except Exception as e: # report, never crash the server
|
|
120
160
|
rh, rb = {"ok": False, "error": f"{type(e).__name__}: {e}"}, b""
|
|
161
|
+
if authorizer is not None:
|
|
162
|
+
authorizer.log(principal, op, False, f"{type(e).__name__}: {e}", len(blob))
|
|
163
|
+
finally:
|
|
164
|
+
auth.set_current(None)
|
|
121
165
|
ch.send(rh, rb)
|
|
122
166
|
|
|
123
167
|
class _S(socketserver.ThreadingTCPServer):
|
|
@@ -143,13 +187,20 @@ class RpcServer:
|
|
|
143
187
|
|
|
144
188
|
|
|
145
189
|
class RpcClient:
|
|
190
|
+
"""token: the shared secret, or a scoped token string from Authorizer.issue()."""
|
|
191
|
+
|
|
146
192
|
def __init__(self, host: str, port: int, token: bytes, timeout: float = 120.0):
|
|
193
|
+
cred, secret = auth.parse_token(token)
|
|
147
194
|
self.sock = socket.create_connection((host, port), timeout=timeout)
|
|
148
195
|
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
196
|
+
hello = _recv_exact(self.sock, 48)
|
|
197
|
+
nonce_s, pub_s = hello[:16], hello[16:]
|
|
198
|
+
eph = X25519PrivateKey.generate()
|
|
199
|
+
pub_c, nonce_c = eph.public_key().public_bytes(**_RAW), os.urandom(16)
|
|
200
|
+
self.sock.sendall(struct.pack(">H", len(cred)) + cred + pub_c + nonce_c
|
|
201
|
+
+ _mac(secret, nonce_s, pub_s, pub_c, nonce_c, cred))
|
|
202
|
+
shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_s))
|
|
203
|
+
self._ch = SecureChannel(self.sock, shared + secret, nonce_s, nonce_c, is_server=False)
|
|
153
204
|
self._lock = threading.Lock()
|
|
154
205
|
|
|
155
206
|
def call(self, header: dict, blob: bytes = b"") -> tuple[dict, bytes]:
|
spatial/core/registry.py
CHANGED
|
@@ -29,6 +29,9 @@ ENGINES: list[Engine] = [
|
|
|
29
29
|
Status.OPERATIONAL_PROTOTYPE,
|
|
30
30
|
"tests/test_memory.py, benchmarks/bench_memory.py",
|
|
31
31
|
"user-space object store only; not kernel paging; single writer; no RDMA/CXL hardware"),
|
|
32
|
+
Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
|
|
33
|
+
"tests/test_fleet.py, benchmarks/bench_fleet.py",
|
|
34
|
+
"validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
|
|
32
35
|
Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
|
|
33
36
|
"tests/test_runtime.py, benchmarks/bench_runtime.py",
|
|
34
37
|
"Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Spatial Fleet: an agent on every machine, a hub that sees the whole fleet.
|
|
2
|
+
|
|
3
|
+
agent.py measures its machine continuously, reports to the hub, and runs allow-listed workloads
|
|
4
|
+
the hub hands out (pull model: the agent asks for work, nothing is pushed to it).
|
|
5
|
+
hub.py stores the fleet's measurements, places tasks, and turns the measurements into
|
|
6
|
+
recommendations whose evidence is shown. It never changes a machine by itself.
|
|
7
|
+
|
|
8
|
+
Everything travels over SWP/2 (encrypted, forward-secret, scoped credentials, audit log).
|
|
9
|
+
Savings are only ever ESTIMATES until a recommendation is applied and the fleet is measured again.
|
|
10
|
+
"""
|
|
11
|
+
def __getattr__(name): # lazy: `python -m spatial.fleet.hub` must not import itself twice
|
|
12
|
+
if name == "Agent":
|
|
13
|
+
from .agent import Agent
|
|
14
|
+
return Agent
|
|
15
|
+
if name in ("Hub", "serve_hub"):
|
|
16
|
+
from . import hub
|
|
17
|
+
return getattr(hub, name)
|
|
18
|
+
raise AttributeError(name)
|