driverkit 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.
driverkit/auth.py ADDED
@@ -0,0 +1,508 @@
1
+ """
2
+ driverkit — who the caller is, and nothing more than that.
3
+
4
+ This module answers exactly one question: **which person is on the other end of
5
+ this request?** It never answers "may they do this", because the relay has no
6
+ power to grant and nothing to scope. PROTOCOL.md's core property is unchanged
7
+ by everything in this file:
8
+
9
+ THE RELAY GRANTS NO AUTHORITY. It forwards a verb to a tab that is already
10
+ logged in as a person, and that tab's own session is what the app checks.
11
+
12
+ So a credential here is not a permission. It buys the holder no ability they
13
+ did not already have in their own browser. What it buys the *relay* is the
14
+ ability to keep a hundred people's tabs apart: to list only your tabs, to route
15
+ only your calls, and to make somebody else's tab id indistinguishable from one
16
+ that was never minted. Isolation, not authorisation.
17
+
18
+ WHY SIGNED TOKENS AND NOT A CALLBACK TO THE APP
19
+ -----------------------------------------------
20
+
21
+ The alternative considered was delegated introspection: the relay takes the
22
+ browser's credentials and asks the app ``GET /dk/whoami`` who they belong to.
23
+ It was rejected, and the reason is not the round trip.
24
+
25
+ To ask the app who a browser is, the relay must hold that browser's session
26
+ cookie and replay it. A relay that collects and replays user cookies is a
27
+ credential-handling component — it holds, for a hundred users at once,
28
+ something it could use to do anything any of them could do. That is precisely
29
+ the authority this design exists not to have, and it cannot be audited away:
30
+ the capability is inherent in the data the component holds. An HMAC key, by
31
+ contrast, can only *verify*. It mints nothing the relay can act with.
32
+
33
+ Three smaller costs finish the argument. Introspection makes the app a hard
34
+ dependency of every connect, so the app being slow is tabs failing to appear.
35
+ It needs a cache to be affordable, and a cache of "who is this browser" is a
36
+ session store — the user database the relay was not supposed to need. And the
37
+ deployment PROTOCOL.md recommends is a relay *embedded in the app's own
38
+ server*, where introspection is a process calling itself over HTTP.
39
+
40
+ What tokens cost, said plainly: a shared secret to distribute and rotate, no
41
+ revocation inside a token's lifetime, and a dependence on two machines' clocks
42
+ agreeing. Short lifetimes are what make the first two tolerable, and
43
+ :data:`DEFAULT_SKEW_S` is what makes the third.
44
+
45
+ For the embedded case there is a third door that needs no secret at all:
46
+ ``Relay(resolve_principal=...)``, a function from request headers to a
47
+ principal id. An app with its own session middleware already knows the answer
48
+ and can simply say it. That hook is in :mod:`driverkit.relay`, not here,
49
+ because it involves no cryptography.
50
+
51
+ THE TOKEN
52
+ ---------
53
+
54
+ ::
55
+
56
+ dkt1.<base64url(payload JSON)>.<base64url(HMAC-SHA256(key, "dkt1." + payload))>
57
+
58
+ The algorithm is in the *prefix*, not in the payload, and that is a deliberate
59
+ departure from JWT. A JWT names its own algorithm in a header the verifier has
60
+ not authenticated yet, which is the root of both the ``alg: none`` family of
61
+ bugs and the HMAC/RSA confusion family. Here there is nothing to negotiate: a
62
+ credential either starts with ``dkt1.`` and is HMAC-SHA256, or it is not a
63
+ credential. A future ``dkt2`` would be a new prefix, which is a visible,
64
+ greppable change rather than a field an attacker can set.
65
+
66
+ Claims, all of them required unless marked:
67
+
68
+ ``sub``
69
+ The principal. An opaque string the app chooses — a user id, not an email
70
+ and not a display name, because it ends up in the relay's registry keys and
71
+ nothing should be tempted to render it.
72
+ ``aud``
73
+ The audience: which relay this token is for. Checked exactly. Without it a
74
+ secret shared by staging and production — which is what happens the first
75
+ time somebody copies an env file — makes a staging token a production
76
+ token.
77
+ ``iat``, ``exp``
78
+ Unix seconds. ``exp`` is honoured with :data:`DEFAULT_SKEW_S` of slack and
79
+ an ``iat`` far in the future is refused, because a token minted by a
80
+ machine whose clock is wrong is not evidence of anything.
81
+ ``kid``
82
+ Which key signed it. Read before verification and used to *select* the key;
83
+ an attacker may change it freely and will then fail the MAC. Unknown kid is
84
+ a refusal, never a fallback to trying every key.
85
+ ``tab`` (optional)
86
+ Binds the credential to one tab id. See :meth:`TabAuth.mint`.
87
+
88
+ ANONYMOUS
89
+ ---------
90
+
91
+ An unauthenticated visitor is not an error, and "anonymous" is not one bucket.
92
+ An anonymous credential is ``anon1.<base64url(32 random bytes)>``, minted by
93
+ the page and kept in ``sessionStorage`` beside the tab id, and the principal it
94
+ resolves to is::
95
+
96
+ anon:<sha256("driverkit-anon-v1." + secret)[:16].hex()>
97
+
98
+ Keyless on purpose. Deriving it with the relay's HMAC key would mean every
99
+ anonymous visitor's identity changed the day a key rotated, and the keying
100
+ would buy nothing: the only party who could correlate a principal id with a
101
+ secret is the party already holding the secret.
102
+
103
+ What it is: proof that this is the same browser that opened this tab, which is
104
+ all that isolation needs. Unguessable in the useful direction — the id is a
105
+ SHA-256 image of 256 random bits, so it cannot be worked back to the secret.
106
+ Independent per visitor, which is the requirement.
107
+
108
+ What it is not: an identity. It is a bearer capability, and whoever holds the
109
+ string *is* that principal. It does not survive the tab closing, deliberately.
110
+ It confers nothing at the app, which still sees an anonymous browser session.
111
+ An operator with real users should mint real tokens and set
112
+ ``anonymous=False``; anonymous exists so that a visitor who has not logged in
113
+ still gets a working widget, not so that a login can be skipped.
114
+
115
+ Stdlib only: :mod:`hmac`, :mod:`hashlib`, :mod:`secrets`, :mod:`base64`,
116
+ :mod:`json`. No ``cryptography``, no ``PyJWT``.
117
+ """
118
+
119
+ from __future__ import annotations
120
+
121
+ import base64
122
+ import hashlib
123
+ import hmac
124
+ import json
125
+ import secrets
126
+ import time
127
+ from dataclasses import dataclass
128
+ from typing import Mapping
129
+
130
+ __all__ = [
131
+ "AuthError",
132
+ "Principal",
133
+ "TabAuth",
134
+ "LOCAL_PRINCIPAL",
135
+ "TOKEN_PREFIX",
136
+ "ANON_PREFIX",
137
+ "ANON_ID_PREFIX",
138
+ "MIN_SECRET_BYTES",
139
+ "DEFAULT_TTL_S",
140
+ "DEFAULT_SKEW_S",
141
+ "mint_anon_credential",
142
+ "anon_principal_id",
143
+ ]
144
+
145
+ #: The version prefix that *is* the algorithm. See the module docstring.
146
+ TOKEN_PREFIX = "dkt1"
147
+
148
+ #: The anonymous credential's prefix.
149
+ ANON_PREFIX = "anon1"
150
+
151
+ #: What an anonymous principal id starts with, so a host app reading the relay's
152
+ #: registry can tell one from a real user id without parsing.
153
+ ANON_ID_PREFIX = "anon:"
154
+
155
+ #: The principal every request resolves to when auth is off — the unconfigured
156
+ #: loopback relay one developer runs. One principal means the scoping below is
157
+ #: a no-op and the single-developer path is byte-for-byte what it was.
158
+ LOCAL_PRINCIPAL = "local"
159
+
160
+ #: Shortest key accepted. A 16-character shared secret makes the HMAC theatre,
161
+ #: and the moment to say so is at construction rather than in a post-mortem.
162
+ MIN_SECRET_BYTES = 32
163
+
164
+ #: How long a freshly minted token lasts. Short, because short lifetime is what
165
+ #: substitutes for the revocation a stateless token cannot have. The page asks
166
+ #: for a new one on every reconnect, so this does not need to cover a session.
167
+ DEFAULT_TTL_S = 120.0
168
+
169
+ #: Clock slack on ``exp``, and the window by which an ``iat`` may lead now.
170
+ #:
171
+ #: Sixty seconds, not five minutes. Skew tolerance is a direct extension of
172
+ #: every token's lifetime, so a five-minute window on a two-minute token would
173
+ #: more than treble the time a leaked one stays useful. Sixty seconds covers
174
+ #: two hosts with working NTP, which is the case this is for; a fleet whose
175
+ #: clocks are minutes apart has a problem that a wider window hides rather than
176
+ #: solves.
177
+ DEFAULT_SKEW_S = 60.0
178
+
179
+ _ANON_DOMAIN = b"driverkit-anon-v1."
180
+
181
+
182
+ class AuthError(Exception):
183
+ """A credential did not check out.
184
+
185
+ Deliberately carries no machine-readable reason. The relay answers every
186
+ instance of this with one slug — ``bad-credential`` — because the
187
+ distinctions a caller might want are exactly the distinctions an attacker
188
+ wants: "the signature verified but the audience was wrong" tells a forger
189
+ that the forgery worked. A legitimate client's response is the same in every
190
+ case (mint a fresh token, retry once), so the split buys it nothing.
191
+
192
+ The message is for a developer reading a log on the *minting* side, and the
193
+ relay never puts it on the wire.
194
+ """
195
+
196
+
197
+ @dataclass(frozen=True)
198
+ class Principal:
199
+ """Who a request is from.
200
+
201
+ ``id`` is the registry key half that makes isolation structural: a tab is
202
+ stored under ``(principal.id, tab_id)``, so one principal cannot reach
203
+ another's tab by any code path, including one somebody adds later and
204
+ forgets to guard.
205
+
206
+ ``tab`` is the optional binding from the credential. When it is set the
207
+ caller may address that tab and no other, which is how an MCP server for
208
+ one tab gets a credential that can only drive that tab.
209
+ """
210
+
211
+ id: str
212
+ tab: str | None = None
213
+ anonymous: bool = False
214
+
215
+
216
+ def anon_principal_id(credential: str) -> str:
217
+ """The principal id an ``anon1.`` credential resolves to.
218
+
219
+ Pure, keyless and stable: the same browser secret is the same principal
220
+ across a key rotation, a relay restart and a second relay in the same
221
+ deployment.
222
+ """
223
+ secret = credential.split(".", 1)[1] if "." in credential else ""
224
+ digest = hashlib.sha256(_ANON_DOMAIN + secret.encode("utf-8")).digest()
225
+ return ANON_ID_PREFIX + digest[:16].hex()
226
+
227
+
228
+ def mint_anon_credential() -> str:
229
+ """A fresh anonymous credential. Called by the page, not by the relay.
230
+
231
+ 256 bits from :mod:`secrets`, because this string is the whole of an
232
+ anonymous visitor's isolation: anybody who can guess it is that visitor.
233
+ """
234
+ return f"{ANON_PREFIX}.{_b64u(secrets.token_bytes(32))}"
235
+
236
+
237
+ class TabAuth:
238
+ """Verification, and the minter the app's backend uses.
239
+
240
+ The app's backend is the only thing that knows who a browser is, so it is
241
+ the only thing that may mint. Give it the same ``keys`` and ``audience``
242
+ the relay has and it needs nothing else — no relay client, no callback, no
243
+ shared database.
244
+
245
+ ``keys`` maps a key id to a secret. Rotation is additive:
246
+
247
+ 1. Generate the new key and add it to the **relay's** ``keys``. Deploy. The
248
+ relay now accepts both; nothing mints with the new one yet.
249
+ 2. Point the minter at it (``active_kid``). Deploy.
250
+ 3. After ``ttl_s + skew_s`` has passed, drop the old key from the relay.
251
+
252
+ Doing it in that order is the whole of it: a key the relay does not know
253
+ yet is a key that refuses every token signed with it, and a key dropped
254
+ before the last token signed with it expires logs a hundred people out at
255
+ once.
256
+
257
+ ``anonymous`` accepts ``anon1.`` credentials. On by default so that an
258
+ unauthenticated visitor is not an error; turn it off in an app where every
259
+ user is logged in, because then an anonymous credential can only be
260
+ somebody probing.
261
+
262
+ ``require_tab_binding`` refuses any ``dkt1`` token without a ``tab`` claim.
263
+ Off by default — see :meth:`mint` for what the binding buys and what it
264
+ costs.
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ *,
270
+ audience: str,
271
+ keys: Mapping[str, bytes | str] | None = None,
272
+ secret: bytes | str | None = None,
273
+ active_kid: str | None = None,
274
+ ttl_s: float = DEFAULT_TTL_S,
275
+ skew_s: float = DEFAULT_SKEW_S,
276
+ anonymous: bool = True,
277
+ require_tab_binding: bool = False,
278
+ ) -> None:
279
+ if keys and secret is not None:
280
+ raise ValueError("driverkit: pass keys= or secret=, not both")
281
+ if secret is not None:
282
+ # Sugar for the single-key case, which is every deployment until the
283
+ # first rotation. It still gets a kid, so the token a single-key
284
+ # relay mints is shaped exactly like the token a rotating one does
285
+ # and rotation needs no format change.
286
+ keys = {"k1": secret}
287
+ if not keys:
288
+ raise ValueError("driverkit: TabAuth needs keys= or secret=")
289
+ if not audience:
290
+ # No default, because a default audience is an audience nobody
291
+ # chose, and two relays that both accept "driverkit" are one relay
292
+ # as far as a stolen token is concerned.
293
+ raise ValueError("driverkit: TabAuth needs an audience naming this relay")
294
+
295
+ self._keys: dict[str, bytes] = {}
296
+ for kid, value in keys.items():
297
+ raw = value.encode("utf-8") if isinstance(value, str) else bytes(value)
298
+ if len(raw) < MIN_SECRET_BYTES:
299
+ raise ValueError(
300
+ f"driverkit: key {kid!r} is {len(raw)} bytes; at least {MIN_SECRET_BYTES} "
301
+ "are needed. `python3 -c \"import secrets;print(secrets.token_hex(32))\"`"
302
+ )
303
+ if not kid or "." in kid:
304
+ raise ValueError(f"driverkit: {kid!r} is not a usable key id")
305
+ self._keys[kid] = raw
306
+
307
+ self.audience = audience
308
+ self.ttl_s = float(ttl_s)
309
+ self.skew_s = float(skew_s)
310
+ self.anonymous = bool(anonymous)
311
+ self.require_tab_binding = bool(require_tab_binding)
312
+ self.active_kid = active_kid or next(iter(self._keys))
313
+ if self.active_kid not in self._keys:
314
+ raise ValueError(f"driverkit: active_kid {self.active_kid!r} is not in keys")
315
+
316
+ # ---- minting, for the app's backend ------------------------------------
317
+
318
+ def mint(
319
+ self,
320
+ principal: str,
321
+ *,
322
+ tab: str | None = None,
323
+ ttl_s: float | None = None,
324
+ now: float | None = None,
325
+ ) -> str:
326
+ """A token saying ``principal`` is who the bearer is.
327
+
328
+ ``tab`` binds the token to one tab id, and whether to use it is the one
329
+ real judgement call here.
330
+
331
+ It costs a round trip. The tab mints its own id — PROTOCOL.md requires
332
+ that, so a reconnect resumes identity — which means the backend cannot
333
+ know the id at page-render time. Binding therefore turns one template
334
+ variable into "the page asks the backend for a token *after* the JS has
335
+ picked an id", and re-asks on every reconnect that changes it.
336
+
337
+ **It is not strictly safer, and the asymmetry is worth understanding
338
+ before choosing.** Both cases assume a stolen token, which is the only
339
+ case either addresses.
340
+
341
+ *Unbound.* The thief cannot read or drive the victim's tabs. They can
342
+ register a tab *they* control under the victim's principal. It runs in
343
+ their browser, where their own session is what the app checks, so they
344
+ gain no authority — but the victim's agent now sees a tab that is not
345
+ the victim's and may drive it, typing the victim's data onto the
346
+ attacker's screen. Call it injection: an extra tab, the real ones
347
+ untouched.
348
+
349
+ *Bound to tab T.* The thief cannot do that. What they can do is open a
350
+ stream for T — and a second stream for a known ``(principal, tab)`` is a
351
+ RECONNECT, which supersedes the first. So the victim's own page is hung
352
+ up on and the thief's becomes that tab, until the victim's
353
+ ``EventSource`` reconnects and supersedes back. Calls land on whichever
354
+ stream is current. That is a takeover of the exact tab the agent is
355
+ already driving, which is worse than an extra tab in the list, and it is
356
+ not a reason to skip binding so much as a reason not to believe the
357
+ binding is the whole defence.
358
+
359
+ The property that actually bounds both is **the token not leaking**:
360
+ deliver it in a ``__Host-`` cookie rather than a query parameter, keep
361
+ the lifetime short, and read the residual-weakness note in PROTOCOL.md
362
+ about what a short lifetime does and does not bound.
363
+
364
+ A credential for an **agent** should be bound whenever the agent drives
365
+ one known tab. There it is free — the agent has the tab id already — and
366
+ the supersede hazard does not apply, because an agent never opens a tab
367
+ stream.
368
+ """
369
+ if not principal:
370
+ raise ValueError("driverkit: a token needs a principal")
371
+ if principal.startswith(ANON_ID_PREFIX):
372
+ # Otherwise a backend bug could mint a signed token claiming to be
373
+ # an anonymous principal, and the two kinds would stop being
374
+ # distinguishable — which is the one thing `Principal.anonymous`
375
+ # is for.
376
+ raise ValueError(f"driverkit: {ANON_ID_PREFIX!r} is reserved for anonymous visitors")
377
+ issued = time.time() if now is None else now
378
+ life = self.ttl_s if ttl_s is None else float(ttl_s)
379
+ payload: dict[str, object] = {
380
+ "sub": principal,
381
+ "aud": self.audience,
382
+ "iat": int(issued),
383
+ "exp": int(issued + life),
384
+ "kid": self.active_kid,
385
+ }
386
+ if tab:
387
+ payload["tab"] = tab
388
+ # Compact and sorted, so the same claims are the same bytes. Nothing
389
+ # depends on it today; a test that pins a token does, and a reader
390
+ # comparing two tokens by eye does.
391
+ body = _b64u(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8"))
392
+ return f"{TOKEN_PREFIX}.{body}.{_b64u(self._mac(self.active_kid, body))}"
393
+
394
+ # ---- verification, for the relay ---------------------------------------
395
+
396
+ def principal(self, credential: str, *, now: float | None = None) -> Principal:
397
+ """The principal a credential proves, or :class:`AuthError`.
398
+
399
+ Anonymous first, because it needs no key and cannot be confused with a
400
+ token: the prefixes are disjoint and both are checked exactly.
401
+ """
402
+ credential = (credential or "").strip()
403
+ if not credential:
404
+ raise AuthError("empty credential")
405
+
406
+ if credential.startswith(ANON_PREFIX + "."):
407
+ if not self.anonymous:
408
+ raise AuthError("anonymous credentials are not accepted by this relay")
409
+ secret = credential[len(ANON_PREFIX) + 1 :]
410
+ if len(secret) < 32:
411
+ # 32 base64url characters is 24 bytes. A short anonymous secret
412
+ # is a guessable principal, and a guessable anonymous principal
413
+ # is the shared bucket this design exists to avoid.
414
+ raise AuthError("an anonymous secret must be at least 32 characters")
415
+ return Principal(id=anon_principal_id(credential), tab=None, anonymous=True)
416
+
417
+ parts = credential.split(".")
418
+ if len(parts) != 3 or parts[0] != TOKEN_PREFIX:
419
+ raise AuthError("not a dkt1 token")
420
+ _, body, signature = parts
421
+
422
+ claims = _loads(_b64u_decode(body))
423
+ if not isinstance(claims, dict):
424
+ raise AuthError("the payload is not a JSON object")
425
+
426
+ kid = claims.get("kid")
427
+ if not isinstance(kid, str) or kid not in self._keys:
428
+ # Refused, never retried against the other keys. "Try them all"
429
+ # turns a rotation window into a period where every key is live for
430
+ # every token, which is the opposite of what rotating is for.
431
+ raise AuthError("unknown key id")
432
+
433
+ want = self._mac(kid, body)
434
+ got = _b64u_decode(signature)
435
+ # Constant time, and length-safe: compare_digest on unequal lengths is
436
+ # false without leaking where they diverged.
437
+ if not hmac.compare_digest(want, got):
438
+ raise AuthError("the signature does not verify")
439
+
440
+ # Everything below this line is reading an AUTHENTICATED payload. The
441
+ # order matters: nothing from `claims` was trusted above except `kid`,
442
+ # which only selects the key the MAC is then checked with.
443
+ if claims.get("aud") != self.audience:
444
+ raise AuthError("the token is for another audience")
445
+
446
+ sub = claims.get("sub")
447
+ if not isinstance(sub, str) or not sub:
448
+ raise AuthError("the token names no principal")
449
+ if sub.startswith(ANON_ID_PREFIX):
450
+ raise AuthError(f"a signed token may not claim an {ANON_ID_PREFIX!r} principal")
451
+
452
+ moment = time.time() if now is None else now
453
+ exp = claims.get("exp")
454
+ iat = claims.get("iat")
455
+ if not _is_number(exp) or not _is_number(iat):
456
+ raise AuthError("the token has no usable iat/exp")
457
+ if float(exp) + self.skew_s < moment:
458
+ raise AuthError("the token has expired")
459
+ if float(iat) - self.skew_s > moment:
460
+ # A token from the future is not evidence. Accepting it would let a
461
+ # minter with a wrong clock issue credentials that outlive their
462
+ # stated lifetime by however far the clock is out.
463
+ raise AuthError("the token was issued in the future")
464
+
465
+ tab = claims.get("tab")
466
+ if tab is not None and (not isinstance(tab, str) or not tab):
467
+ raise AuthError("the tab claim is not a tab id")
468
+ if self.require_tab_binding and not tab:
469
+ raise AuthError("this relay requires a tab-bound token")
470
+
471
+ return Principal(id=sub, tab=tab, anonymous=False)
472
+
473
+ def _mac(self, kid: str, body: str) -> bytes:
474
+ # The prefix is inside the MAC, so a `dkt2` with a different meaning
475
+ # cannot be produced by relabelling a `dkt1` payload.
476
+ return hmac.new(
477
+ self._keys[kid], f"{TOKEN_PREFIX}.{body}".encode("utf-8"), hashlib.sha256
478
+ ).digest()
479
+
480
+
481
+ # ---- small helpers ---------------------------------------------------------
482
+
483
+
484
+ def _b64u(raw: bytes) -> str:
485
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
486
+
487
+
488
+ def _b64u_decode(text: str) -> bytes:
489
+ """Unpadded base64url, with anything undecodable raised as an AuthError.
490
+
491
+ Strict, so that ``dkt1.<json>.<sig>`` with a payload that merely *looks*
492
+ like base64 is a refusal rather than a mojibake principal id.
493
+ """
494
+ try:
495
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
496
+ except Exception as err: # binascii.Error, and ValueError on odd input
497
+ raise AuthError("not base64url") from err
498
+
499
+
500
+ def _loads(raw: bytes) -> object:
501
+ try:
502
+ return json.loads(raw)
503
+ except (ValueError, UnicodeDecodeError) as err:
504
+ raise AuthError("the payload is not JSON") from err
505
+
506
+
507
+ def _is_number(value: object) -> bool:
508
+ return isinstance(value, (int, float)) and not isinstance(value, bool)