bitting 1.2.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.
bitting/manager.py ADDED
@@ -0,0 +1,783 @@
1
+ """The KeyManager: issue, verify, rotate, and revoke API keys.
2
+
3
+ This module is the orchestrator that ties together key generation
4
+ (:mod:`bitting.keys`), hashing (:mod:`bitting.hashing`), and storage
5
+ (:mod:`bitting.storage`), and emits audit events for every lifecycle
6
+ action.
7
+
8
+ Scope model
9
+ ===========
10
+ Scopes are strings like ``read:users`` or ``write:posts``. A granted
11
+ scope matches a required scope when:
12
+
13
+ * they are equal, or
14
+ * the granted scope ends with ``:*`` and shares the prefix
15
+ (``read:*`` matches ``read:users``), or
16
+ * the granted scope is the global wildcard ``*``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import json
23
+ import warnings
24
+ from collections.abc import Callable, Iterable, Mapping
25
+ from datetime import datetime, timedelta
26
+ from typing import Any
27
+
28
+ from .errors import ConfigurationError, KeyNotFoundError, StorageError
29
+ from .hashing import Hasher, ScryptHasher
30
+ from .keys import DEFAULT_ENV, ParsedKey, generate_api_key, parse_api_key, validate_env_label
31
+ from .models import (
32
+ AuditCallback,
33
+ AuditEvent,
34
+ AuditEventKind,
35
+ IssuedKey,
36
+ KeyRecord,
37
+ VerifyReason,
38
+ VerifyResult,
39
+ )
40
+ from .storage import KeyStore, new_key_id
41
+ from .timeutil import utcnow
42
+
43
+ __all__ = [
44
+ "DEFAULT_ROTATION_GRACE",
45
+ "LEGACY_STORE_WARNING",
46
+ "KeyManager",
47
+ "missing_scopes",
48
+ "scope_matches",
49
+ "validate_scopes",
50
+ ]
51
+
52
+ #: Default grace period during which a rotated key keeps working.
53
+ DEFAULT_ROTATION_GRACE = timedelta(hours=24)
54
+
55
+ #: Attempts to draw an unused prefix before giving up on issue().
56
+ _ISSUE_COLLISION_RETRIES = 8
57
+
58
+ #: Set to ``False`` to silence the legacy-store warning emitted when a
59
+ #: ``KeyStore`` lacks ``mark_verified``/``mark_rotated``/``mark_revoked``.
60
+ #: Silencing it is an explicit acceptance of the documented race risk
61
+ #: (a revoked key can verify again after a concurrent touch on such a
62
+ #: store — see README, "Limitations"); the warning exists so nobody
63
+ #: ships that configuration by accident.
64
+ LEGACY_STORE_WARNING = True
65
+
66
+
67
+ def scope_matches(granted: str, required: str) -> bool:
68
+ """Return True when a granted scope satisfies a required scope."""
69
+ if granted == required or granted == "*":
70
+ return True
71
+ if granted.endswith(":*"):
72
+ return required.startswith(granted[:-1])
73
+ return False
74
+
75
+
76
+ def validate_scopes(scopes: Iterable[str], *, label: str = "scope") -> frozenset[str]:
77
+ """Normalize and validate an iterable of scope strings.
78
+
79
+ A bare ``str``/``bytes`` is rejected rather than silently iterated into
80
+ single characters. Every element must be a non-empty string without
81
+ whitespace.
82
+
83
+ Raises:
84
+ ValueError: If ``scopes`` is a bare string or contains an invalid
85
+ scope. This is a caller/configuration error, not a bad key.
86
+ """
87
+ if isinstance(scopes, (str, bytes)):
88
+ # A bare string would silently become a set of single
89
+ # characters ("read:users" -> {'r','e','a',...}), granting
90
+ # nothing and confusing everyone. Fail loudly instead.
91
+ raise ValueError(
92
+ f"{label}s must be an iterable of scope strings, not a single "
93
+ f"string (got {scopes!r}); pass e.g. scopes={{'read:users'}}"
94
+ )
95
+ result = frozenset(scopes)
96
+ for scope in result:
97
+ if not isinstance(scope, str) or not scope or any(ch.isspace() for ch in scope):
98
+ raise ValueError(
99
+ f"{label}s must be non-empty strings without whitespace (got {scope!r})"
100
+ )
101
+ return result
102
+
103
+
104
+ def missing_scopes(granted: Iterable[str], required: Iterable[str]) -> frozenset[str]:
105
+ """Return the subset of ``required`` scopes not covered by ``granted``."""
106
+ granted_list = list(granted)
107
+ return frozenset(
108
+ req for req in required if not any(scope_matches(g, req) for g in granted_list)
109
+ )
110
+
111
+
112
+ class KeyManager:
113
+ """High-level API for the full key lifecycle.
114
+
115
+ Args:
116
+ store: Where key records live (SQLite, in-memory, or custom).
117
+ hasher: How raw keys are hashed. Defaults to
118
+ :class:`bitting.hashing.ScryptHasher` (~16 MiB per hash).
119
+ env: Environment label embedded in generated keys (``live``,
120
+ ``test`` ...). Verified keys from other labels are still
121
+ accepted if they match a stored prefix — label switching is
122
+ an operational concern, not a security boundary.
123
+ now_fn: Injectable clock (defaults to :func:`bitting.timeutil.utcnow`).
124
+ on_event: Optional synchronous audit callback invoked for every
125
+ lifecycle action, after the store has been updated.
126
+ hashers: Optional registry of extra hashers keyed by algorithm
127
+ name, used to verify keys that were issued with a different
128
+ algorithm (see "Switching hashers" in the README). New keys
129
+ are always hashed with ``hasher``.
130
+ verify_touch_interval: Minimum time between persisting
131
+ ``last_verified_at`` updates (default 60s). ``timedelta(0)``
132
+ restores the 1.0 behavior of writing on every verification.
133
+ audit_verifications: When False, skip audit events for verify
134
+ outcomes (both successes and failures); lifecycle events
135
+ (issued/rotated/revoked) are always emitted.
136
+
137
+ Example:
138
+ >>> from bitting import KeyManager, SQLiteStore
139
+ >>> manager = KeyManager(SQLiteStore("keys.db")) # doctest: +SKIP
140
+ >>> issued = manager.issue(scopes={"read:users"}, description="ci")
141
+ >>> manager.verify(issued.raw_key, required_scopes={"read:users"}).ok
142
+ True
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ store: KeyStore,
148
+ *,
149
+ hasher: Hasher | None = None,
150
+ env: str = DEFAULT_ENV,
151
+ now_fn: Callable[[], datetime] = utcnow,
152
+ on_event: AuditCallback | None = None,
153
+ hashers: Mapping[str, Hasher] | None = None,
154
+ verify_touch_interval: timedelta = timedelta(seconds=60),
155
+ audit_verifications: bool = True,
156
+ ) -> None:
157
+ self._store = store
158
+ self._hasher: Hasher = hasher if hasher is not None else ScryptHasher()
159
+ # Verification dispatches on the algorithm stored with each key,
160
+ # so keys issued under a previous hasher keep verifying after an
161
+ # algorithm change (the primary hasher covers new keys).
162
+ self._hashers: dict[str, Hasher] = {self._hasher.algorithm: self._hasher}
163
+ for name, candidate in (hashers or {}).items():
164
+ if candidate.algorithm != name:
165
+ raise ConfigurationError(
166
+ f"hasher registry key {name!r} must match the hasher's "
167
+ f"algorithm {candidate.algorithm!r}"
168
+ )
169
+ if name == self._hasher.algorithm and candidate is not self._hasher:
170
+ # Silently re-registering the primary algorithm would make
171
+ # verification use a different hasher than issuance.
172
+ raise ConfigurationError(
173
+ f"hashers registry must not re-register the primary "
174
+ f"algorithm {name!r} with a different hasher"
175
+ )
176
+ self._hashers[name] = candidate
177
+ self._env = validate_env_label(env)
178
+ self._now_fn = now_fn
179
+ self._on_event = on_event
180
+ self._verify_touch_interval = verify_touch_interval
181
+ self._audit_verifications = audit_verifications
182
+ if LEGACY_STORE_WARNING:
183
+ missing = [
184
+ name
185
+ for name in ("mark_verified", "mark_rotated", "mark_revoked")
186
+ if getattr(store, name, None) is None
187
+ ]
188
+ if missing:
189
+ warnings.warn(
190
+ "the configured store does not implement "
191
+ f"{', '.join(missing)}: bitting falls back to non-atomic "
192
+ "read-modify-write lifecycle updates, so a concurrent "
193
+ "revocation/rotation can be lost (in the worst case a "
194
+ "revoked key verifies again). Implement the mark_* "
195
+ "methods as targeted atomic updates (both built-in "
196
+ "stores do), or set bitting.manager.LEGACY_STORE_WARNING "
197
+ "= False to accept the documented risk explicitly.",
198
+ stacklevel=2,
199
+ )
200
+
201
+ @property
202
+ def store(self) -> KeyStore:
203
+ """The underlying key store."""
204
+ return self._store
205
+
206
+ @property
207
+ def hasher(self) -> Hasher:
208
+ """The hasher used for new keys (verification dispatches per record)."""
209
+ return self._hasher
210
+
211
+ # ------------------------------------------------------------------
212
+ # Issue
213
+ # ------------------------------------------------------------------
214
+
215
+ def issue(
216
+ self,
217
+ *,
218
+ scopes: Iterable[str] = (),
219
+ description: str = "",
220
+ ttl: timedelta | None = None,
221
+ expires_at: datetime | None = None,
222
+ metadata: dict[str, Any] | None = None,
223
+ ) -> IssuedKey:
224
+ """Generate and persist a new API key.
225
+
226
+ Args:
227
+ scopes: Scopes granted to this key.
228
+ description: Free-form human description.
229
+ ttl: Key lifetime from now (mutually exclusive with ``expires_at``).
230
+ expires_at: Absolute expiry moment (timezone-aware).
231
+ metadata: Arbitrary JSON-serializable metadata stored with the key.
232
+
233
+ Returns:
234
+ An :class:`IssuedKey`. The raw key is shown once and can
235
+ never be recovered — store it securely at the client.
236
+
237
+ Raises:
238
+ ValueError: If both ``ttl`` and ``expires_at`` are given.
239
+ """
240
+ return self._issue(
241
+ scopes=scopes,
242
+ description=description,
243
+ ttl=ttl,
244
+ expires_at=expires_at,
245
+ metadata=metadata,
246
+ emit=True,
247
+ )
248
+
249
+ def _issue(
250
+ self,
251
+ *,
252
+ scopes: Iterable[str] = (),
253
+ description: str = "",
254
+ ttl: timedelta | None = None,
255
+ expires_at: datetime | None = None,
256
+ metadata: dict[str, Any] | None = None,
257
+ emit: bool = True,
258
+ supersedes: str | None = None,
259
+ ) -> IssuedKey:
260
+ if ttl is not None and expires_at is not None:
261
+ raise ValueError("specify either ttl or expires_at, not both")
262
+ if ttl is not None and ttl < timedelta(0):
263
+ raise ValueError("ttl must be non-negative")
264
+ now = self._now_fn()
265
+ if ttl is not None:
266
+ expires_at = now + ttl
267
+ if expires_at is not None and expires_at.tzinfo is None:
268
+ raise ValueError("expires_at must be timezone-aware")
269
+ stored_metadata = dict(metadata or {})
270
+ try:
271
+ json.dumps(stored_metadata)
272
+ except (TypeError, ValueError) as exc:
273
+ raise ValueError("metadata must be JSON-serializable") from exc
274
+ # store.save() is an upsert by contract, so a prefix collision would
275
+ # silently overwrite somebody else's key. 16 base62 characters make
276
+ # that astronomically unlikely, but "unlikely" is not "impossible"
277
+ # and the failure mode is credential replacement: check and retry.
278
+ for _attempt in range(_ISSUE_COLLISION_RETRIES):
279
+ raw_key = generate_api_key(self._env)
280
+ parsed = parse_api_key(raw_key)
281
+ if self._store.find_by_prefix(parsed.prefix) is None:
282
+ break
283
+ else: # pragma: no cover - requires an astronomically unlikely collision
284
+ raise StorageError(
285
+ f"could not generate an unused key prefix after {_ISSUE_COLLISION_RETRIES} attempts"
286
+ )
287
+ record = KeyRecord(
288
+ key_id=new_key_id(),
289
+ prefix=parsed.prefix,
290
+ hash=self._hasher.hash(raw_key),
291
+ algorithm=self._hasher.algorithm,
292
+ scopes=self._validated_scopes(scopes),
293
+ created_at=now,
294
+ description=description,
295
+ expires_at=expires_at,
296
+ metadata=stored_metadata,
297
+ supersedes=supersedes,
298
+ )
299
+ self._store.save(record)
300
+ if emit:
301
+ self._emit(AuditEventKind.ISSUED, record.prefix, now, {"key_id": record.key_id})
302
+ return IssuedKey(raw_key=raw_key, key_id=record.key_id, prefix=parsed.prefix, record=record)
303
+
304
+ # ------------------------------------------------------------------
305
+ # Verify
306
+ # ------------------------------------------------------------------
307
+
308
+ def verify(
309
+ self,
310
+ raw_key: str,
311
+ *,
312
+ required_scopes: Iterable[str] = (),
313
+ ) -> VerifyResult:
314
+ """Verify a raw key and check required scopes.
315
+
316
+ The verdict is precise: ``result.reason`` distinguishes malformed
317
+ keys, unknown prefixes, hash mismatches, expiry, revocation,
318
+ rotation (inside and outside the grace window), and missing
319
+ scopes — so callers can answer 401 vs 403 correctly.
320
+
321
+ Verification never raises for a bad key; it returns a failed
322
+ :class:`VerifyResult` instead. Leading/trailing whitespace is
323
+ tolerated (stripped), matching the HTTP-header behavior of the
324
+ FastAPI integration.
325
+
326
+ Raises:
327
+ ValueError: If ``required_scopes`` contains a non-string,
328
+ empty, or whitespace-containing scope (caller error,
329
+ distinct from a bad key).
330
+ """
331
+ now = self._now_fn()
332
+ required = frozenset(self._validated_scopes(required_scopes, label="required scope"))
333
+
334
+ try:
335
+ candidate = raw_key.strip() if isinstance(raw_key, str) else raw_key
336
+ parsed = parse_api_key(candidate)
337
+ except Exception:
338
+ return VerifyResult(ok=False, reason=VerifyReason.INVALID_FORMAT, checked_at=now)
339
+
340
+ record = self._store.find_by_prefix(parsed.prefix)
341
+ if record is None:
342
+ return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND, checked_at=now)
343
+
344
+ if record.revoked_at is not None:
345
+ self._emit_verify(
346
+ AuditEventKind.VERIFY_FAILED,
347
+ record.prefix,
348
+ now,
349
+ {"reason": VerifyReason.REVOKED.value},
350
+ )
351
+ return VerifyResult(
352
+ ok=False, reason=VerifyReason.REVOKED, record=record, checked_at=now
353
+ )
354
+
355
+ if record.rotated_at is not None:
356
+ # Expiry is a hard cap on the grace window: a rotated key
357
+ # past its TTL is expired, never "rotated_grace".
358
+ expired = record.expires_at is not None and now >= record.expires_at
359
+ in_grace = not expired and record.grace_until is not None and now <= record.grace_until
360
+ if not in_grace:
361
+ reason = VerifyReason.EXPIRED if expired else VerifyReason.ROTATED
362
+ self._emit_verify(
363
+ AuditEventKind.VERIFY_FAILED,
364
+ record.prefix,
365
+ now,
366
+ {"reason": reason.value},
367
+ )
368
+ return VerifyResult(ok=False, reason=reason, record=record, checked_at=now)
369
+ if not self._verify_hash(candidate, record, now, rotated_grace=True):
370
+ return VerifyResult(
371
+ ok=False, reason=VerifyReason.HASH_MISMATCH, record=record, checked_at=now
372
+ )
373
+ return self._confirm_and_finish(parsed, required, VerifyReason.ROTATED_GRACE)
374
+
375
+ if record.expires_at is not None and now >= record.expires_at:
376
+ self._emit_verify(
377
+ AuditEventKind.VERIFY_FAILED,
378
+ record.prefix,
379
+ now,
380
+ {"reason": VerifyReason.EXPIRED.value},
381
+ )
382
+ return VerifyResult(
383
+ ok=False, reason=VerifyReason.EXPIRED, record=record, checked_at=now
384
+ )
385
+
386
+ if not self._verify_hash(candidate, record, now):
387
+ return VerifyResult(
388
+ ok=False, reason=VerifyReason.HASH_MISMATCH, record=record, checked_at=now
389
+ )
390
+
391
+ return self._confirm_and_finish(parsed, required, VerifyReason.OK)
392
+
393
+ @staticmethod
394
+ def _lifecycle_denial(record: KeyRecord, now: datetime) -> VerifyReason | None:
395
+ """The denial implied by a record's lifecycle state, or None.
396
+
397
+ None means the key may authenticate: either active, or rotated but
398
+ still inside its grace window (which the original expiry caps).
399
+ """
400
+ if record.revoked_at is not None:
401
+ return VerifyReason.REVOKED
402
+ expired = record.expires_at is not None and now >= record.expires_at
403
+ if record.rotated_at is not None:
404
+ in_grace = not expired and record.grace_until is not None and now <= record.grace_until
405
+ if not in_grace:
406
+ return VerifyReason.EXPIRED if expired else VerifyReason.ROTATED
407
+ return None
408
+ if expired:
409
+ return VerifyReason.EXPIRED
410
+ return None
411
+
412
+ def _confirm_and_finish(
413
+ self,
414
+ parsed: ParsedKey,
415
+ required: frozenset[str],
416
+ success_reason: VerifyReason,
417
+ ) -> VerifyResult:
418
+ """Re-read lifecycle state *after* the KDF, then authorize.
419
+
420
+ The KDF is deliberately expensive (tens of milliseconds at the
421
+ default scrypt cost, longer under CPU contention). Deciding from
422
+ the pre-hash snapshot alone lets a credential that was revoked,
423
+ expired or rotated *while the hash was running* still authenticate:
424
+ the revocation commits, but the in-flight request returns ok=True.
425
+
426
+ Re-reading the record and the clock costs one indexed lookup
427
+ (microseconds against even a million-key store) plus one clock
428
+ read, and shrinks that window from the whole KDF duration to a
429
+ single lookup. It also picks up scope narrowing committed during
430
+ the hash.
431
+
432
+ This is a mitigation, not an absolute guarantee: a lifecycle change
433
+ committed between this lookup and the caller acting on the result
434
+ is still possible. Applications needing a hard guarantee must
435
+ serialize revocation against authorization at a higher layer.
436
+ """
437
+ now = self._now_fn()
438
+ fresh = self._store.find_by_prefix(parsed.prefix)
439
+ if fresh is None:
440
+ self._emit_verify(
441
+ AuditEventKind.VERIFY_FAILED,
442
+ parsed.prefix,
443
+ now,
444
+ {"reason": VerifyReason.NOT_FOUND.value},
445
+ )
446
+ return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND, checked_at=now)
447
+ denial = self._lifecycle_denial(fresh, now)
448
+ if denial is not None:
449
+ self._emit_verify(
450
+ AuditEventKind.VERIFY_FAILED, fresh.prefix, now, {"reason": denial.value}
451
+ )
452
+ return VerifyResult(ok=False, reason=denial, record=fresh, checked_at=now)
453
+ if fresh.rotated_at is not None:
454
+ success_reason = VerifyReason.ROTATED_GRACE
455
+ return self._check_scopes(parsed, fresh, required, now, success_reason)
456
+
457
+ def _check_scopes(
458
+ self,
459
+ parsed: ParsedKey,
460
+ record: KeyRecord,
461
+ required: frozenset[str],
462
+ now: datetime,
463
+ success_reason: VerifyReason,
464
+ ) -> VerifyResult:
465
+ missing = missing_scopes(record.scopes, required) if required else frozenset()
466
+ if missing:
467
+ self._emit_verify(
468
+ AuditEventKind.VERIFY_FAILED,
469
+ record.prefix,
470
+ now,
471
+ {"reason": VerifyReason.SCOPE_MISSING.value, "missing": sorted(missing)},
472
+ )
473
+ return VerifyResult(
474
+ ok=False,
475
+ reason=VerifyReason.SCOPE_MISSING,
476
+ record=record,
477
+ missing_scopes=missing,
478
+ checked_at=now,
479
+ )
480
+ previous_touch = record.last_verified_at
481
+ record.last_verified_at = now
482
+ # Persisting the touch is throttled: the hot verification path
483
+ # stays read-only except once per interval (0 restores 1.0
484
+ # write-on-every-verify behavior). The touch is a targeted
485
+ # single-field update (mark_verified) so a concurrent revoke or
486
+ # rotate can never be clobbered by a stale full-record save.
487
+ if self._should_persist_touch(previous_touch, now):
488
+ self._touch_verified(parsed.prefix, now)
489
+ self._emit_verify(
490
+ AuditEventKind.VERIFIED,
491
+ record.prefix,
492
+ now,
493
+ {"reason": success_reason.value, "key_id": record.key_id},
494
+ )
495
+ return VerifyResult(ok=True, reason=success_reason, record=record, checked_at=now)
496
+
497
+ def _verify_hash(
498
+ self,
499
+ raw_key: str,
500
+ record: KeyRecord,
501
+ now: datetime,
502
+ *,
503
+ rotated_grace: bool = False,
504
+ ) -> bool:
505
+ """Verify the hash with the hasher recorded for this key."""
506
+ hasher = self._hashers.get(record.algorithm)
507
+ verified = False
508
+ detail_extra: dict[str, Any] = {}
509
+ if hasher is not None:
510
+ try:
511
+ verified = hasher.verify(raw_key, record.hash)
512
+ except Exception as exc:
513
+ # A corrupted stored hash (or a broken custom hasher)
514
+ # must fail closed, never crash the request path.
515
+ verified = False
516
+ detail_extra = {"hasher_error": type(exc).__name__}
517
+ if not verified:
518
+ detail: dict[str, Any] = {"reason": VerifyReason.HASH_MISMATCH.value}
519
+ if rotated_grace:
520
+ detail["rotated_grace"] = True
521
+ if hasher is None:
522
+ detail["unknown_algorithm"] = record.algorithm
523
+ detail.update(detail_extra)
524
+ self._emit_verify(AuditEventKind.VERIFY_FAILED, record.prefix, now, detail)
525
+ return False
526
+ return True
527
+
528
+ def _should_persist_touch(self, previous: datetime | None, now: datetime) -> bool:
529
+ if self._verify_touch_interval <= timedelta(0):
530
+ return True
531
+ if previous is None:
532
+ return True
533
+ return now - previous >= self._verify_touch_interval
534
+
535
+ # ------------------------------------------------------------------
536
+ # Rotate / revoke / inspect
537
+ # ------------------------------------------------------------------
538
+
539
+ def rotate(
540
+ self,
541
+ prefix: str,
542
+ *,
543
+ grace: timedelta = DEFAULT_ROTATION_GRACE,
544
+ scopes: Iterable[str] | None = None,
545
+ description: str | None = None,
546
+ ttl: timedelta | None = None,
547
+ ) -> IssuedKey:
548
+ """Replace the key identified by ``prefix`` with a fresh key.
549
+
550
+ The old key continues to verify (with reason
551
+ ``ROTATED_GRACE``) until ``grace`` elapses or the old key's
552
+ original expiry — whichever comes first — so clients can migrate
553
+ without downtime. After that the old key is rejected with
554
+ reason ``ROTATED`` (or ``EXPIRED`` if its TTL ended first).
555
+
556
+ The successor does **not** inherit the old key's TTL; pass
557
+ ``ttl`` to give the new key a lifetime.
558
+
559
+ Args:
560
+ prefix: Prefix of the key to rotate.
561
+ grace: How long the old key keeps working (non-negative,
562
+ capped by the old key's expiry).
563
+ scopes: Replacement scopes (None keeps the existing ones).
564
+ description: Replacement description (None keeps existing).
565
+ ttl: Lifetime for the *new* key (None: no expiry).
566
+
567
+ Raises:
568
+ KeyNotFoundError: If no key has this prefix.
569
+ ValueError: If the key was already rotated or revoked, is
570
+ already expired, or ``grace`` is negative.
571
+ """
572
+ if grace < timedelta(0):
573
+ raise ValueError("grace must be non-negative")
574
+ now = self._now_fn()
575
+ record = self._require(prefix)
576
+ if record.revoked_at is not None:
577
+ raise ValueError(f"key {prefix!r} is revoked; issue a new key instead")
578
+ if record.rotated_at is not None:
579
+ raise ValueError(f"key {prefix!r} was already rotated; rotate the successor instead")
580
+ if record.expires_at is not None and now >= record.expires_at:
581
+ raise ValueError(f"key {prefix!r} is expired; issue a new key instead")
582
+
583
+ # Persist the successor FIRST, complete and undisclosed: its
584
+ # supersedes link is already set, but the old key still verifies
585
+ # normally and no ROTATED event has been emitted. If anything
586
+ # fails from here on, the cleanup below removes the successor and
587
+ # the old key is untouched — a failed rotation can never strand a
588
+ # key in a rotated state without a working successor.
589
+ issued = self._issue(
590
+ scopes=record.scopes if scopes is None else scopes,
591
+ description=record.description if description is None else description,
592
+ ttl=ttl,
593
+ metadata=record.metadata,
594
+ emit=False,
595
+ supersedes=record.prefix,
596
+ )
597
+ successor = issued.record
598
+ grace_until = now + grace
599
+ try:
600
+ # Atomically claim the active→rotated transition. Concurrent
601
+ # rotations race on this single conditional update: exactly
602
+ # one caller wins; the losers clean up and raise below.
603
+ claimed = self._mark_rotated(record.prefix, rotated_at=now, grace_until=grace_until)
604
+ except BaseException:
605
+ self._discard_successor(successor.prefix)
606
+ raise
607
+ if not claimed:
608
+ self._discard_successor(successor.prefix)
609
+ current = self._require(prefix)
610
+ if current.revoked_at is not None:
611
+ raise ValueError(f"key {prefix!r} is revoked; issue a new key instead")
612
+ raise ValueError(f"key {prefix!r} was already rotated; rotate the successor instead")
613
+
614
+ self._emit(
615
+ AuditEventKind.ROTATED,
616
+ record.prefix,
617
+ now,
618
+ {"successor_prefix": successor.prefix, "grace_until": grace_until.isoformat()},
619
+ )
620
+ return issued
621
+
622
+ def _discard_successor(self, prefix: str) -> None:
623
+ """Best-effort removal of an undisclosed rotate() successor.
624
+
625
+ Cleanup must never mask the original failure, so storage errors
626
+ are suppressed: an orphaned, never-disclosed successor record is
627
+ inert (its raw key was never returned to anyone) and can be
628
+ pruned by an operator.
629
+ """
630
+ with contextlib.suppress(Exception):
631
+ self._store.delete(prefix)
632
+
633
+ def revoke(self, prefix: str, *, now: datetime | None = None) -> KeyRecord:
634
+ """Immediately revoke the key with this prefix.
635
+
636
+ Revocation goes through :meth:`bitting.storage.KeyStore.mark_revoked`
637
+ — a targeted conditional update that touches **only** ``revoked_at``
638
+ — so a rotation claimed concurrently keeps its ``rotated_at`` and
639
+ ``grace_until``, and the persisted touch of a concurrent
640
+ verification keeps its ``last_verified_at``. Revocation is
641
+ idempotent: revoking an already-revoked key keeps the first
642
+ (authoritative) timestamp and records the repeated attempt in the
643
+ audit trail with an ``already_revoked`` detail flag.
644
+
645
+ Raises:
646
+ KeyNotFoundError: If no key has this prefix.
647
+ ValueError: If ``now`` is given but timezone-naive.
648
+ """
649
+ if now is not None and now.tzinfo is None:
650
+ raise ValueError("now must be timezone-aware")
651
+ moment = now or self._now_fn()
652
+ marked = self._mark_revoked(prefix, at=moment)
653
+ # Fresh post-transition state; also the KeyNotFoundError source for a
654
+ # missing key (mark_revoked merely returns False for absent prefixes).
655
+ record = self._require(prefix)
656
+ detail: dict[str, Any] = {"key_id": record.key_id}
657
+ if not marked:
658
+ detail["already_revoked"] = True
659
+ self._emit(AuditEventKind.REVOKED, record.prefix, moment, detail)
660
+ return record
661
+
662
+ def list_keys(self) -> list[KeyRecord]:
663
+ """Return all key records (never raw keys)."""
664
+ return self._store.list_keys()
665
+
666
+ def list_events(self, *, limit: int = 100) -> list[AuditEvent]:
667
+ """Return recent audit events, newest first."""
668
+ return self._store.list_events(limit=limit)
669
+
670
+ def prune_events(self, *, before: datetime) -> int:
671
+ """Delete audit events strictly older than ``before``.
672
+
673
+ Returns the number of events removed. Use this to bound audit
674
+ growth; see ``delete_events_before`` on the stores.
675
+
676
+ Raises:
677
+ ValueError: If ``before`` is timezone-naive.
678
+ NotImplementedError: If the store does not support pruning.
679
+ """
680
+ if before.tzinfo is None:
681
+ raise ValueError("before must be timezone-aware")
682
+ delete = getattr(self._store, "delete_events_before", None)
683
+ if delete is None:
684
+ raise NotImplementedError("the configured store does not support audit pruning")
685
+ return int(delete(before))
686
+
687
+ def close(self) -> None:
688
+ """Close the underlying store, if it holds resources."""
689
+ self._store.close()
690
+
691
+ # ------------------------------------------------------------------
692
+ # Internals
693
+ # ------------------------------------------------------------------
694
+
695
+ def _require(self, prefix: str) -> KeyRecord:
696
+ record = self._store.find_by_prefix(prefix)
697
+ if record is None:
698
+ raise KeyNotFoundError(f"no key with prefix {prefix!r}")
699
+ return record
700
+
701
+ @staticmethod
702
+ def _validated_scopes(scopes: Iterable[str], *, label: str = "scope") -> frozenset[str]:
703
+ return validate_scopes(scopes, label=label)
704
+
705
+ def _touch_verified(self, prefix: str, at: datetime) -> None:
706
+ """Persist a ``last_verified_at`` touch without touching any other field.
707
+
708
+ SECURITY: if the store does not implement ``mark_verified``, the
709
+ fallback below re-reads a fresh record and saves only the timestamp
710
+ on it. That re-read shrinks — but does not eliminate — the window in
711
+ which a concurrent revocation (or rotation) can be overwritten by
712
+ the stale save: for such stores a *revoked key can verify again*
713
+ after this race. Stores used in production MUST implement
714
+ ``mark_verified`` as a targeted single-field update (both built-in
715
+ stores do; see README, "Limitations").
716
+ """
717
+ touch = getattr(self._store, "mark_verified", None)
718
+ if touch is None:
719
+ record = self._store.find_by_prefix(prefix)
720
+ if record is None:
721
+ return
722
+ record.last_verified_at = at
723
+ self._store.save(record)
724
+ return
725
+ touch(prefix, at=at)
726
+
727
+ def _mark_rotated(self, prefix: str, *, rotated_at: datetime, grace_until: datetime) -> bool:
728
+ """Claim the active→rotated transition through the store."""
729
+ mark = getattr(self._store, "mark_rotated", None)
730
+ if mark is None:
731
+ # Duck-typed store predating mark_rotated: fall back to the
732
+ # 1.0 non-atomic read-check-write behavior.
733
+ record = self._store.find_by_prefix(prefix)
734
+ if record is None or record.rotated_at is not None or record.revoked_at is not None:
735
+ return False
736
+ record.rotated_at = rotated_at
737
+ record.grace_until = grace_until
738
+ self._store.save(record)
739
+ return True
740
+ return bool(mark(prefix, rotated_at=rotated_at, grace_until=grace_until))
741
+
742
+ def _mark_revoked(self, prefix: str, *, at: datetime) -> bool:
743
+ """Claim the active→revoked transition through the store."""
744
+ mark = getattr(self._store, "mark_revoked", None)
745
+ if mark is None:
746
+ # Duck-typed store predating mark_revoked: fall back to the
747
+ # 1.0 non-atomic read-check-write behavior. Note this full-record
748
+ # save can lose a concurrent lifecycle transition (see the
749
+ # mark_rotated fallback above and README, "Limitations").
750
+ record = self._store.find_by_prefix(prefix)
751
+ if record is None or record.revoked_at is not None:
752
+ return False
753
+ record.revoked_at = at
754
+ self._store.save(record)
755
+ return True
756
+ return bool(mark(prefix, at=at))
757
+
758
+ def _emit(
759
+ self,
760
+ kind: AuditEventKind,
761
+ prefix: str,
762
+ at: datetime,
763
+ detail: dict[str, Any],
764
+ ) -> None:
765
+ event = AuditEvent(kind=kind, prefix=prefix, at=at, detail=detail)
766
+ # Audit persistence and observers are best-effort by design:
767
+ # a broken observer or store must never break verification.
768
+ with contextlib.suppress(Exception):
769
+ self._store.append_event(event)
770
+ if self._on_event is not None:
771
+ with contextlib.suppress(Exception):
772
+ self._on_event(event)
773
+
774
+ def _emit_verify(
775
+ self,
776
+ kind: AuditEventKind,
777
+ prefix: str,
778
+ at: datetime,
779
+ detail: dict[str, Any],
780
+ ) -> None:
781
+ """Emit a verify-path event, unless verify auditing is disabled."""
782
+ if self._audit_verifications:
783
+ self._emit(kind, prefix, at, detail)