devzero-sandbox 0.1.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.
@@ -0,0 +1,363 @@
1
+ """Gateway credentials (ADR-005-W11).
2
+
3
+ Two credentials reach the gateway, one per route (ADR-005 §Gateway
4
+ verification pipeline, §In-cluster):
5
+
6
+ - External callers (``/t/<team>/s/<id>``) hold sandbox JWTs that DevZero mints
7
+ (``CreateSandbox`` / ``CreateSandboxToken``). A sandbox may have any number of
8
+ live tokens with different scopes; :class:`TokenCredentials` holds them and
9
+ sends, per request, the narrowest one that covers the route's scope.
10
+ - In-cluster callers (``/p/<policy>/s/<id>``) send their pod's projected
11
+ ServiceAccount token, bound to audience ``sandbox-gateway.devzero.io``;
12
+ :class:`ProjectedTokenCredentials` reads it from the mounted file and picks
13
+ up kubelet's rotations.
14
+
15
+ The SDK never verifies a token, the gateway does. It reads a JWT's claims only
16
+ to pick a token and to refuse sending a ServiceAccount token that is not bound
17
+ to the gateway. Tokens are held as :class:`BearerToken`, whose ``repr`` and
18
+ ``str`` never show the value, and are sent only as ``Authorization: Bearer``.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import base64
24
+ import binascii
25
+ import hmac
26
+ import json
27
+ import os
28
+ import threading
29
+ import time
30
+ from collections.abc import Callable, Iterable
31
+ from typing import Any, Literal, NoReturn, Protocol, get_args
32
+
33
+ from devzero_sandbox.errors import DevZeroSandboxError
34
+ from devzero_sandbox.incluster import IN_CLUSTER_TOKEN_PATH
35
+
36
+ Scope = Literal["exec", "files", "terminal", "watch", "ports"]
37
+ ALL_SCOPES: tuple[Scope, ...] = get_args(Scope)
38
+
39
+ #: The audience an in-cluster caller's projected token must be bound to (ADR-005 rule 9).
40
+ IN_CLUSTER_AUDIENCE = "sandbox-gateway.devzero.io"
41
+
42
+ #: 401 codes that condemn the one token presented, so another held token may still work.
43
+ _DEAD_TOKEN_CODES = frozenset({"token_expired", "token_revoked"})
44
+
45
+
46
+ class CredentialError(DevZeroSandboxError):
47
+ """A credential problem found before anything was sent."""
48
+
49
+
50
+ class NoUsableTokenError(CredentialError):
51
+ """No held token is live, bound to this sandbox and covers the route's scope."""
52
+
53
+
54
+ class InClusterTokenMissingError(CredentialError):
55
+ """The projected ServiceAccount token is not mounted, or is empty."""
56
+
57
+
58
+ class InClusterTokenAudienceError(CredentialError):
59
+ """The mounted token is not bound to the gateway audience; it is never sent."""
60
+
61
+
62
+ class BearerToken:
63
+ """A credential string that does not show itself.
64
+
65
+ ``repr``, ``str`` and formatting print ``BearerToken([REDACTED])``; only
66
+ :meth:`reveal` returns the value, and the transport calls it only to build
67
+ the ``Authorization`` header. Pickling is refused so the value cannot reach
68
+ a cache, a queue or a multiprocessing boundary by accident.
69
+ """
70
+
71
+ __slots__ = ("_value",)
72
+
73
+ def __init__(self, value: str) -> None:
74
+ if not value or value != value.strip():
75
+ raise ValueError(
76
+ "a bearer token must be a non-empty string without surrounding space"
77
+ )
78
+ self._value = value
79
+
80
+ def reveal(self) -> str:
81
+ return self._value
82
+
83
+ def __repr__(self) -> str:
84
+ return "BearerToken([REDACTED])"
85
+
86
+ __str__ = __repr__
87
+
88
+ def __format__(self, spec: str) -> str:
89
+ return repr(self)
90
+
91
+ def __eq__(self, other: object) -> bool:
92
+ if not isinstance(other, BearerToken):
93
+ return NotImplemented
94
+ return hmac.compare_digest(self._value.encode(), other._value.encode())
95
+
96
+ def __hash__(self) -> int:
97
+ return hash(self._value)
98
+
99
+ def __reduce__(self) -> NoReturn:
100
+ raise TypeError("BearerToken cannot be pickled; tokens stay in memory")
101
+
102
+
103
+ def unverified_claims(token: str) -> dict[str, Any]:
104
+ """Decode a JWT's payload without verifying it; ``{}`` if it is not a JWT."""
105
+ parts = token.split(".")
106
+ if len(parts) != 3:
107
+ return {}
108
+ try:
109
+ payload = base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4))
110
+ claims = json.loads(payload)
111
+ except (binascii.Error, ValueError):
112
+ return {}
113
+ return claims if isinstance(claims, dict) else {}
114
+
115
+
116
+ def _scopes(values: Iterable[str]) -> frozenset[Scope]:
117
+ out: set[Scope] = set()
118
+ for v in values:
119
+ if v not in ALL_SCOPES:
120
+ raise ValueError(f"unknown scope {v!r}; scopes are {', '.join(ALL_SCOPES)}")
121
+ out.add(v) # narrowed to Scope by the membership test
122
+ # An empty scope means all five (CreateSandboxTokenRequest.scope).
123
+ return frozenset(out) or frozenset(ALL_SCOPES)
124
+
125
+
126
+ class SandboxToken:
127
+ """One sandbox JWT and what the SDK needs to choose it.
128
+
129
+ ``jti``, ``scopes`` (``dz.scope``), ``expires_at`` (``exp``) and
130
+ ``sandbox_id`` (``sub``) are read from the token's claims unless given; a
131
+ caller that minted the token (``CreateSandboxTokenResponse``) may pass them.
132
+ A token whose claims cannot be read covers every scope and never expires
133
+ locally, and the gateway decides.
134
+ """
135
+
136
+ __slots__ = ("bearer", "expires_at", "jti", "sandbox_id", "scopes")
137
+
138
+ def __init__(
139
+ self,
140
+ token: str,
141
+ *,
142
+ jti: str | None = None,
143
+ scopes: Iterable[str] | None = None,
144
+ expires_at: float | None = None,
145
+ ) -> None:
146
+ self.bearer = BearerToken(token)
147
+ claims = unverified_claims(token)
148
+ dz = claims.get("dz") if isinstance(claims.get("dz"), dict) else {}
149
+ claim_scope = dz.get("scope") if isinstance(dz, dict) else None
150
+ self.jti: str | None = (
151
+ jti if jti is not None else _str_or_none(claims.get("jti"))
152
+ )
153
+ self.sandbox_id: str | None = _str_or_none(claims.get("sub"))
154
+ self.scopes: frozenset[Scope] = _scopes(
155
+ scopes
156
+ if scopes is not None
157
+ else claim_scope
158
+ if isinstance(claim_scope, list)
159
+ else ()
160
+ )
161
+ exp = claims.get("exp")
162
+ self.expires_at: float | None = (
163
+ expires_at
164
+ if expires_at is not None
165
+ else float(exp)
166
+ if isinstance(exp, int | float)
167
+ else None
168
+ )
169
+
170
+ def covers(self, scope: Scope) -> bool:
171
+ return scope in self.scopes
172
+
173
+ def expired(self, now: float) -> bool:
174
+ return self.expires_at is not None and now >= self.expires_at
175
+
176
+ def __repr__(self) -> str:
177
+ return (
178
+ f"SandboxToken(jti={self.jti!r}, sandbox_id={self.sandbox_id!r}, "
179
+ f"scopes={sorted(self.scopes)!r}, expires_at={self.expires_at!r}, token=[REDACTED])"
180
+ )
181
+
182
+
183
+ def _str_or_none(v: object) -> str | None:
184
+ return v if isinstance(v, str) and v else None
185
+
186
+
187
+ class Credentials(Protocol):
188
+ """What :class:`devzero_sandbox.transport.GatewayTransport` needs from a credential.
189
+
190
+ ``route`` is the URL prefix the credential is valid on: ``"t"`` for sandbox
191
+ JWTs, ``"p"`` for projected ServiceAccount tokens (anything else is
192
+ ``401 wrong_auth_for_route``).
193
+ """
194
+
195
+ @property
196
+ def route(self) -> Literal["t", "p"]: ...
197
+
198
+ def bearer_for(self, scope: Scope, sandbox_id: str) -> BearerToken:
199
+ """The token to send for a request of ``scope`` to ``sandbox_id``."""
200
+ ...
201
+
202
+ def on_rejected(
203
+ self, bearer: BearerToken, code: str, scope: Scope, sandbox_id: str
204
+ ) -> bool:
205
+ """React to a ``401 <code>`` for ``bearer``; ``True`` means retry once."""
206
+ ...
207
+
208
+
209
+ class TokenCredentials:
210
+ """The sandbox JWTs an external caller holds (multi-token).
211
+
212
+ Tokens are added when minted, replaced wholesale when the caller supplies a
213
+ new one, and removed on revocation. :meth:`select` picks, among live tokens
214
+ bound to the sandbox (``sub``) that cover the scope, the one with the fewest
215
+ scopes (least privilege), then the latest expiry. A ``401 token_expired`` or
216
+ ``token_revoked`` drops the token that drew it.
217
+ """
218
+
219
+ route: Literal["t"] = "t"
220
+
221
+ def __init__(
222
+ self, *tokens: SandboxToken | str, now: Callable[[], float] = time.time
223
+ ) -> None:
224
+ self._now = now
225
+ self._lock = threading.Lock()
226
+ self._tokens: list[SandboxToken] = []
227
+ for t in tokens:
228
+ self.add(t)
229
+
230
+ def add(self, token: SandboxToken | str) -> SandboxToken:
231
+ """Hold one more token; a token with the same ``jti`` is replaced."""
232
+ tok = token if isinstance(token, SandboxToken) else SandboxToken(token)
233
+ with self._lock:
234
+ self._tokens = [
235
+ t for t in self._tokens if tok.jti is None or t.jti != tok.jti
236
+ ] + [tok]
237
+ return tok
238
+
239
+ def replace(self, *tokens: SandboxToken | str) -> None:
240
+ """Drop every held token and hold only ``tokens`` (a refreshed credential)."""
241
+ new = [t if isinstance(t, SandboxToken) else SandboxToken(t) for t in tokens]
242
+ with self._lock:
243
+ self._tokens = new
244
+
245
+ def remove(self, jti: str) -> None:
246
+ """Forget the token with this ``jti`` (after ``RevokeSandboxToken``)."""
247
+ with self._lock:
248
+ self._tokens = [t for t in self._tokens if t.jti != jti]
249
+
250
+ def tokens(self) -> list[SandboxToken]:
251
+ with self._lock:
252
+ return list(self._tokens)
253
+
254
+ def select(self, scope: Scope, sandbox_id: str) -> SandboxToken:
255
+ now = self._now()
256
+ usable = [
257
+ t
258
+ for t in self.tokens()
259
+ if t.covers(scope)
260
+ and not t.expired(now)
261
+ and (t.sandbox_id is None or t.sandbox_id == sandbox_id)
262
+ ]
263
+ if not usable:
264
+ raise NoUsableTokenError(
265
+ f"no live token for sandbox {sandbox_id} covers scope {scope!r}; "
266
+ "mint one with CreateSandboxToken"
267
+ )
268
+ return min(
269
+ usable, key=lambda t: (len(t.scopes), -(t.expires_at or float("inf")))
270
+ )
271
+
272
+ def bearer_for(self, scope: Scope, sandbox_id: str) -> BearerToken:
273
+ return self.select(scope, sandbox_id).bearer
274
+
275
+ def on_rejected(
276
+ self, bearer: BearerToken, code: str, scope: Scope, sandbox_id: str
277
+ ) -> bool:
278
+ if code not in _DEAD_TOKEN_CODES:
279
+ return False
280
+ with self._lock:
281
+ self._tokens = [t for t in self._tokens if t.bearer != bearer]
282
+ try:
283
+ self.select(scope, sandbox_id)
284
+ except NoUsableTokenError:
285
+ return False
286
+ return True
287
+
288
+ def __repr__(self) -> str:
289
+ inner = ", ".join(f"jti={t.jti!r}" for t in self.tokens())
290
+ return f"TokenCredentials({inner})"
291
+
292
+
293
+ class ProjectedTokenCredentials:
294
+ """The in-cluster caller's projected ServiceAccount token (ADR-005 §In-cluster).
295
+
296
+ The pod mounts ``serviceAccountToken: {audience: sandbox-gateway.devzero.io}``
297
+ at ``/var/run/dz-sandbox/token``. kubelet rewrites the file well before the
298
+ token expires (at 80 % of ``expirationSeconds``) by swapping a symlink, so
299
+ the file is re-read whenever its identity (inode, size, mtime) changes, and
300
+ once more on any ``401`` in case a rewrite kept all three.
301
+
302
+ A token whose ``aud`` does not contain the gateway audience is refused
303
+ before it is sent: the likely mistake is pointing the SDK at the kubelet's
304
+ default API-server token, and that credential must never leave the pod.
305
+ """
306
+
307
+ route: Literal["p"] = "p"
308
+
309
+ def __init__(
310
+ self,
311
+ token_path: str = IN_CLUSTER_TOKEN_PATH,
312
+ *,
313
+ audience: str = IN_CLUSTER_AUDIENCE,
314
+ ) -> None:
315
+ self.token_path = token_path
316
+ self.audience = audience
317
+ self._lock = threading.Lock()
318
+ self._stat: tuple[int, int, int] | None = None
319
+ self._bearer: BearerToken | None = None
320
+
321
+ def _read(self, force: bool) -> BearerToken:
322
+ try:
323
+ st = os.stat(self.token_path)
324
+ key = (st.st_ino, st.st_size, st.st_mtime_ns)
325
+ if not force and key == self._stat and self._bearer is not None:
326
+ return self._bearer
327
+ with open(self.token_path, encoding="ascii") as f:
328
+ raw = f.read().strip()
329
+ except FileNotFoundError:
330
+ raw, key = "", (0, 0, 0)
331
+ if not raw:
332
+ raise InClusterTokenMissingError(
333
+ f"no ServiceAccount token at {self.token_path}; mount a projected "
334
+ f"serviceAccountToken with audience {self.audience} there (ADR-005 §In-cluster)"
335
+ )
336
+ aud = unverified_claims(raw).get("aud")
337
+ auds = [aud] if isinstance(aud, str) else aud if isinstance(aud, list) else None
338
+ if auds is not None and self.audience not in auds:
339
+ raise InClusterTokenAudienceError(
340
+ f"the token at {self.token_path} is not bound to audience {self.audience}; "
341
+ "it was not sent. Mount a projected serviceAccountToken with that audience "
342
+ "instead of the default API-server token"
343
+ )
344
+ self._stat, self._bearer = key, BearerToken(raw)
345
+ return self._bearer
346
+
347
+ def bearer_for(self, scope: Scope, sandbox_id: str) -> BearerToken:
348
+ # Scopes do not apply on the in-cluster route (ADR-007 §URL scheme).
349
+ with self._lock:
350
+ return self._read(force=False)
351
+
352
+ def on_rejected(
353
+ self, bearer: BearerToken, code: str, scope: Scope, sandbox_id: str
354
+ ) -> bool:
355
+ with self._lock:
356
+ try:
357
+ fresh = self._read(force=True)
358
+ except CredentialError:
359
+ return False
360
+ return fresh != bearer
361
+
362
+ def __repr__(self) -> str:
363
+ return f"ProjectedTokenCredentials(token_path={self.token_path!r}, audience={self.audience!r})"