File size: 25,406 Bytes
c1fc133
 
82cdb59
c1fc133
 
 
82cdb59
 
 
 
2e7e617
82cdb59
 
8133df9
 
82cdb59
 
 
 
 
 
 
8133df9
82cdb59
c1fc133
 
816fa8a
 
c1fc133
 
816fa8a
82cdb59
 
2e7e617
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
82cdb59
816fa8a
c1fc133
 
816fa8a
c1fc133
 
 
 
816fa8a
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
c1fc133
 
816fa8a
8133df9
 
82cdb59
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
c1fc133
82cdb59
 
 
 
 
 
2e7e617
 
c1fc133
 
816fa8a
 
82cdb59
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
2e7e617
816fa8a
82cdb59
816fa8a
c1fc133
816fa8a
82cdb59
 
 
2e7e617
 
816fa8a
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
816fa8a
82cdb59
 
 
 
 
 
2e7e617
 
816fa8a
8133df9
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
816fa8a
2e7e617
 
 
 
 
816fa8a
2e7e617
 
816fa8a
2e7e617
816fa8a
2e7e617
816fa8a
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
2e7e617
 
816fa8a
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
8133df9
 
 
 
 
 
 
 
 
82cdb59
 
 
8133df9
 
 
82cdb59
 
 
 
 
 
 
c1fc133
82cdb59
c1fc133
8133df9
 
82cdb59
 
 
 
 
 
 
8133df9
 
 
82cdb59
 
 
 
 
 
8133df9
82cdb59
 
 
 
 
8133df9
 
 
c1fc133
8133df9
 
82cdb59
 
8133df9
 
 
 
82cdb59
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
"""Per-user credentials carrying an access level and database subset for governed reads and
builds, with the maker's live grants still applying on top.

Verification reconstructs the same PUBLIC user record the normal API session carries, so every
later database read still goes through ``perm_scope`` and the existing Assistant mirror.
This module never reads product rows and never caches a
credential, user, bucket, or tenant runtime.
"""
import calendar
from dataclasses import dataclass
from datetime import datetime, timezone
import hashlib
import hmac
import logging
import os
import secrets
import time

import core.users as users
from harness import runtime


_log = logging.getLogger(__name__)
BUCKET = "external_access"
ACCESS_READ = "read"
ACCESS_READWRITE = "readwrite"
ACCESS_REFRESH = "refresh"
ACCESS_LEVELS = (ACCESS_READ, ACCESS_READWRITE, ACCESS_REFRESH)
ALL_DATABASES = "all"
MAX_SCOPE_DATABASES = 200
MAX_SCOPE_WORKBOOKS = 100
ALGORITHM = "sha256-salt-v1"
AUTH_ERROR = "invalid_external_credential"
_UNSET = object()
_DUMMY_SALT = bytes(32)
_DUMMY_HASH = hashlib.sha256(_DUMMY_SALT + b"invalid").hexdigest()
#: Seconds between two durable `last_used` stamps for ONE credential.
#:
#: ⛔⛔ THE STAMP IS THROTTLED, AND THIS IS NOT AN OPTIMISATION. `st.update(..., flush="sync")` is
#: a fresh strict read plus a BLOCKING UPLOAD, i.e. one durable commit per verified request. An
#: external AI reads in bursts and the store's budget is 256 commits an hour, so an unthrottled
#: stamp would spend a tenant's whole write budget on telemetry and put an upload inside the
#: latency of every read. It would also make a surface contract C7 calls READ ONLY write on every
#: single call, which is the claim this module exists to keep true. The pane renders `last_used` to
#: the minute, so a quarter of an hour of staleness costs the reader nothing.
#: ⚠ REVOCATION IS NOT THROTTLED AND MUST NEVER BE: `revoke` and `mint` stay `flush="sync"`, and
#: verification still reads the bucket FRESH on every request, which is what makes "revoking stops
#: the next request" true.
_STAMP_EVERY = 900.0


class ExternalAccessError(RuntimeError):
    """A stable core-layer refusal.  HTTP status and copy belong to the API layer."""

    def __init__(self, code: str):
        super().__init__(code)
        self.code = code


class ExternalAuthError(ExternalAccessError):
    """A uniform authentication refusal that reveals no credential or tenant detail."""

    def __init__(self, code: str, *, cause: str = "unknown_key"):
        super().__init__(code)
        self.cause = cause


def normalise_access(value, *, allow_refresh=False) -> str:
    if value is None or value == "":
        return ACCESS_READWRITE
    if value in ACCESS_LEVELS and (value != ACCESS_REFRESH or allow_refresh):
        return value
    raise ExternalAccessError("external_access_scope_invalid")


def normalise_test_connection(value) -> bool:
    """Require an explicit boolean when a caller sets the test restriction."""
    if type(value) is not bool:
        raise ExternalAccessError("external_test_connection_invalid")
    return value


def normalise_databases(value):
    if value is None or (isinstance(value, str) and value.strip().lower() == ALL_DATABASES):
        return ALL_DATABASES
    if not isinstance(value, (list, tuple)) or not 1 <= len(value) <= MAX_SCOPE_DATABASES:
        raise ExternalAccessError("external_databases_invalid")
    if any(not isinstance(item, str) or not item.strip() or len(item.strip()) > 200
           for item in value):
        raise ExternalAccessError("external_databases_invalid")
    return tuple(dict.fromkeys(item.strip() for item in value))


def scope_of(record):
    """Read legacy defaults, but preserve a stored empty subset as no database access."""
    record = record if isinstance(record, dict) else {}
    access = record.get("access")
    if access not in ACCESS_LEVELS:
        access = ACCESS_READWRITE
    databases = record.get("databases")
    if isinstance(databases, (list, tuple)):
        databases = tuple(item.strip() for item in databases
                          if isinstance(item, str) and item.strip())
    else:
        databases = ALL_DATABASES
    return access, databases


def normalise_workbooks(value):
    """Accept a bounded workbook allowlist, with no implicit wildcard."""
    if value is None:
        return ()
    if (not isinstance(value, (list, tuple)) or len(value) > MAX_SCOPE_WORKBOOKS
            or any(not isinstance(item, str) or not item.strip() or len(item.strip()) > 200
                   or item.strip() == "all" for item in value)):
        raise ExternalAccessError("external_workbooks_invalid")
    return tuple(dict.fromkeys(item.strip() for item in value))


def workbooks_of(record):
    """Treat absent or malformed stored workbook grants as no refresh access."""
    try:
        return normalise_workbooks(record.get("workbooks"))
    except (AttributeError, ExternalAccessError):
        return ()


def may_write(access) -> bool:
    return access == ACCESS_READWRITE


def database_allowed(databases, database) -> bool:
    if databases == ALL_DATABASES:
        return True
    return isinstance(database, str) and bool(database.strip()) and database.strip() in databases


@dataclass(frozen=True)
class VerifiedCredential:
    """The authenticated public principal plus the request-scoped tenant runtime."""

    tenant: str
    key_id: str
    user: dict
    runtime: object
    access: str = ACCESS_READWRITE
    databases: object = ALL_DATABASES
    workbooks: tuple = ()
    warning: str | None = None
    origin_recorded: bool = False


def _now() -> str:
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def _epoch(value: str | None) -> float | None:
    if value is None:
        return None
    try:
        return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(
            tzinfo=timezone.utc).timestamp()
    except (TypeError, ValueError, OverflowError):
        return None


def normalise_expiry(value, *, now: float | None = None) -> str | None:
    """Return one canonical future UTC expiry, or ``None`` for no expiry."""
    if value is None or value == "":
        return None
    if not isinstance(value, str):
        raise ExternalAccessError("external_expiry_invalid")
    parsed = _epoch(value.strip())
    if parsed is None or parsed <= (time.time() if now is None else float(now)):
        raise ExternalAccessError("external_expiry_invalid")
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(parsed))


def _stamp_is_due(last_used, now: float) -> bool:
    """Is this credential's `last_used` stale enough to be worth a durable write?

    An absent, unparseable or future stamp is DUE, so a corrupt value self-heals on the next
    request rather than freezing the field forever.
    """
    if not last_used:
        return True
    try:
        seen = calendar.timegm(time.strptime(str(last_used), "%Y-%m-%dT%H:%M:%SZ"))
    except (TypeError, ValueError):
        return True
    return not (0.0 <= now - seen < _STAMP_EVERY)


def _digest(salt: bytes, secret: str) -> str:
    """Hash one external secret with SHA-256 and its per-record random salt.

    The secret has 256 bits of machine-generated randomness, not human-password entropy.  A slow
    password KDF therefore buys nothing against an offline attacker and would deliberately delay
    every request on the read surface.
    """
    return hashlib.sha256(salt + secret.encode("utf-8")).hexdigest()


def _book(st, *, fresh: bool = True) -> dict:
    try:
        value = st.get(BUCKET, fresh=fresh)
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    if value is None:
        return {}
    if not isinstance(value, dict):
        raise ExternalAccessError("external_access_unavailable")
    return value


def _normalise_owner(username: str, tenant: str) -> tuple[str, str]:
    owner = str(username or "").strip().lower()
    tenant_key = str(tenant or "").strip().lower()
    if not owner or not tenant_key:
        raise ExternalAccessError("external_identity_invalid")
    return owner, tenant_key


def _assert_bound_runtime(st, tenant: str) -> None:
    if str(getattr(st, "key", "") or "").strip().lower() != tenant:
        raise ExternalAccessError("external_identity_invalid")


def resolve_active_user(username: str, tenant: str) -> dict:
    try:
        registry = users.registry() or {}
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    if not isinstance(registry, dict):
        raise ExternalAccessError("external_access_unavailable")
    record = registry.get(username)
    if not isinstance(record, dict) or not record.get("active", True):
        raise ExternalAccessError("external_account_unavailable")
    public = users._public(username, record)
    if public.get("tenant") != tenant:
        raise ExternalAccessError("external_account_unavailable")
    return public


def _active_public_user(username: str, tenant: str) -> dict:
    """Backward-compatible private spelling retained for the SDLC 62 seam."""
    return resolve_active_user(username, tenant)


def _normalise_label(label) -> str:
    clean = str(label or "").strip()
    if (not clean or len(clean) > 80 or any(ord(char) < 32 for char in clean)
            or "lpb1." in clean or "lpo1." in clean or "lpr1." in clean
            or "lpc1." in clean):
        raise ExternalAccessError("external_label_invalid")
    return clean


def _metadata(record: dict) -> dict:
    """Return list-safe metadata.  Salt, digest, algorithm and owner never cross this seam."""
    access, databases = scope_of(record)
    return {
        "id": record.get("id"),
        "label": record.get("label"),
        "created": record.get("created"),
        "last_used": record.get("last_used"),
        "revoked_at": record.get("revoked_at"),
        "rotated_at": record.get("rotated_at"),
        "expires_at": record.get("expires_at"),
        "access": access,
        "databases": ALL_DATABASES if databases == ALL_DATABASES else list(databases),
        "workbooks": list(workbooks_of(record)),
        "test_connection": record.get("test_connection", False) is not False,
    }


def label_for(st, key_id: str) -> str:
    """Read only a verified key's label from its tenant runtime, never credential material."""
    record = _book(st).get(key_id)
    if not isinstance(record, dict) or record.get("revoked_at"):
        raise ExternalAuthError(AUTH_ERROR)
    label = record.get("label")
    if not isinstance(label, str) or not label:
        raise ExternalAccessError("external_access_unavailable")
    return label


def is_test_connection(st, key_id: str) -> bool:
    """Read the current test restriction without returning credential material."""
    record = _book(st).get(key_id)
    if not isinstance(record, dict) or record.get("revoked_at"):
        raise ExternalAuthError(AUTH_ERROR)
    return record.get("test_connection", False) is not False


def mint(st, username: str, tenant: str, label: str, access=None, databases=None,
         expires_at=None, test_connection=False, workbooks=None) -> tuple[dict, str]:
    """Create one credential and return ``(metadata, token)``; the token is never persisted."""
    access = normalise_access(access, allow_refresh=True)
    databases = normalise_databases(databases)
    workbooks = normalise_workbooks(workbooks)
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    _active_public_user(owner, tenant_key)
    clean_label = _normalise_label(label)
    expiry = normalise_expiry(expires_at)
    test_connection = normalise_test_connection(test_connection)

    secret = secrets.token_urlsafe(32)
    salt = secrets.token_bytes(32)
    created = _now()
    minted: dict = {}

    def _set(value):
        if value is None:
            book = {}
        elif isinstance(value, dict):
            book = dict(value)
        else:
            raise ExternalAccessError("external_access_unavailable")
        key_id = secrets.token_urlsafe(18)
        while key_id in book:
            key_id = secrets.token_urlsafe(18)
        record = {
            "id": key_id,
            "username": owner,
            "tenant": tenant_key,
            "label": clean_label,
            "access": access,
            "databases": ALL_DATABASES if databases == ALL_DATABASES else list(databases),
            "workbooks": list(workbooks),
            "salt": salt.hex(),
            "hash": _digest(salt, secret),
            "algo": ALGORITHM,
            "created": created,
            "last_used": None,
            "revoked_at": None,
            "rotated_at": None,
            "expires_at": expiry,
            "test_connection": test_connection,
            "minted_space": os.environ.get("SPACE_ID") or None,
        }
        book[key_id] = record
        minted["record"] = record
        return book

    try:
        st.update(BUCKET, _set, flush="sync")
    except ExternalAccessError:
        raise
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    record = minted.get("record")
    if not isinstance(record, dict):
        raise ExternalAccessError("external_access_unavailable")
    token = f"lpb1.{tenant_key}.{record['id']}.{secret}"
    return _metadata(record), token


def edit(st, username: str, tenant: str, key_id: str, *, label=_UNSET, access=_UNSET,
         databases=_UNSET, expires_at=_UNSET, test_connection=_UNSET, workbooks=_UNSET) -> dict:
    """Edit metadata/scope in one store update; credential material is left untouched."""
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    resolve_active_user(owner, tenant_key)
    target = str(key_id or "").strip()
    if label is access is databases is expires_at is test_connection is workbooks is _UNSET:
        raise ExternalAccessError("external_edit_empty")
    clean_label = _normalise_label(label) if label is not _UNSET else _UNSET
    clean_access = normalise_access(access, allow_refresh=True) if access is not _UNSET else _UNSET
    clean_databases = normalise_databases(databases) if databases is not _UNSET else _UNSET
    clean_workbooks = normalise_workbooks(workbooks) if workbooks is not _UNSET else _UNSET
    clean_expiry = normalise_expiry(expires_at) if expires_at is not _UNSET else _UNSET
    clean_test = normalise_test_connection(test_connection) if test_connection is not _UNSET else _UNSET
    edited: dict = {}

    def _set(value):
        if not isinstance(value, dict):
            raise ExternalAccessError("external_key_not_found")
        book = dict(value)
        current = book.get(target)
        if (not isinstance(current, dict) or current.get("username") != owner
                or current.get("tenant") != tenant_key or current.get("revoked_at")):
            raise ExternalAccessError("external_key_not_found")
        record = dict(current)
        if clean_label is not _UNSET:
            record["label"] = clean_label
        if clean_access is not _UNSET:
            record["access"] = clean_access
        if clean_databases is not _UNSET:
            record["databases"] = (ALL_DATABASES if clean_databases == ALL_DATABASES
                                   else list(clean_databases))
        if clean_workbooks is not _UNSET:
            record["workbooks"] = list(clean_workbooks)
        if clean_expiry is not _UNSET:
            record["expires_at"] = clean_expiry
        if clean_test is not _UNSET:
            record["test_connection"] = clean_test
        book[target] = record
        edited["record"] = record
        return book

    try:
        st.update(BUCKET, _set, flush="sync")
    except ExternalAccessError:
        raise
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    record = edited.get("record")
    if not isinstance(record, dict):
        raise ExternalAccessError("external_access_unavailable")
    return _metadata(record)


def rotate(st, username: str, tenant: str, key_id: str) -> tuple[dict, str]:
    """Replace one owned key's secret atomically and reveal the replacement exactly once."""
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    resolve_active_user(owner, tenant_key)
    target = str(key_id or "").strip()
    secret = secrets.token_urlsafe(32)
    salt = secrets.token_bytes(32)
    rotated: dict = {}

    def _set(value):
        if not isinstance(value, dict):
            raise ExternalAccessError("external_key_not_found")
        book = dict(value)
        current = book.get(target)
        if (not isinstance(current, dict) or current.get("username") != owner
                or current.get("tenant") != tenant_key or current.get("revoked_at")):
            raise ExternalAccessError("external_key_not_found")
        record = dict(current)
        record.update({
            "salt": salt.hex(), "hash": _digest(salt, secret), "algo": ALGORITHM,
            "rotated_at": _now(), "last_used": None,
            "minted_space": os.environ.get("SPACE_ID") or None,
        })
        book[target] = record
        rotated["record"] = record
        return book

    try:
        st.update(BUCKET, _set, flush="sync")
    except ExternalAccessError:
        raise
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    record = rotated.get("record")
    if not isinstance(record, dict):
        raise ExternalAccessError("external_access_unavailable")
    return _metadata(record), f"lpb1.{tenant_key}.{target}.{secret}"


def list_for_user(st, username: str, tenant: str) -> list[dict]:
    """List only this user's active credential metadata, newest first."""
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    records = [
        _metadata(record)
        for record in _book(st).values()
        if isinstance(record, dict)
        and record.get("username") == owner
        and record.get("tenant") == tenant_key
        and not record.get("revoked_at")
    ]
    return sorted(records, key=lambda row: str(row.get("created") or ""), reverse=True)


def revoke(st, username: str, tenant: str, key_id: str) -> dict:
    """Tombstone one credential owned by this user; foreign and absent IDs are identical."""
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    target = str(key_id or "").strip()
    revoked: dict = {}

    def _set(value):
        if not isinstance(value, dict):
            raise ExternalAccessError("external_key_not_found")
        book = dict(value)
        current = book.get(target)
        if (not isinstance(current, dict)
                or current.get("username") != owner
                or current.get("tenant") != tenant_key):
            raise ExternalAccessError("external_key_not_found")
        record = dict(current)
        if not record.get("revoked_at"):
            record["revoked_at"] = _now()
            book[target] = record
        revoked["record"] = record
        return book

    try:
        st.update(BUCKET, _set, flush="sync")
    except ExternalAccessError:
        raise
    except Exception as exc:
        raise ExternalAccessError("external_access_unavailable") from exc
    record = revoked.get("record")
    if not isinstance(record, dict):
        raise ExternalAccessError("external_access_unavailable")
    return _metadata(record)


def _parse_token(token: str) -> tuple[str, str, str]:
    parts = str(token or "").strip().split(".")
    if (len(parts) != 4 or parts[0] != "lpb1" or not all(parts[1:])
            or len(parts[1]) > 128 or len(parts[2]) > 128 or len(parts[3]) > 256):
        raise ExternalAuthError(AUTH_ERROR)
    return parts[1].lower(), parts[2], parts[3]


def _comparison_material(record) -> tuple[bool, bytes, str]:
    usable = isinstance(record, dict) and record.get("algo") == ALGORITHM
    if usable:
        try:
            salt = bytes.fromhex(str(record.get("salt") or ""))
            expected = str(record.get("hash") or "")
            if len(salt) != 32 or len(expected) != 64:
                raise ValueError("bad credential digest")
            int(expected, 16)
            return True, salt, expected
        except (TypeError, ValueError):
            pass
    return False, _DUMMY_SALT, _DUMMY_HASH


def _recorded_space(record: dict) -> str | None:
    """Treat missing or malformed origin metadata as unproved."""
    value = record.get("minted_space")
    return value if isinstance(value, str) and value.strip() else None


def _credential_cause(record, tenant: str, key_id: str, secret: str, *, owner=None):
    """Inspect status only after the secret and optional session owner match the stored record."""
    material_ok, salt, expected = _comparison_material(record)
    matched = hmac.compare_digest(_digest(salt, secret), expected)
    if (not material_ok or not matched or record.get("id") != key_id
            or record.get("tenant") != tenant or not record.get("username")
            or (owner is not None and record.get("username") != owner)):
        return "unknown_key"
    origin, current = _recorded_space(record), os.environ.get("SPACE_ID")
    if origin and current and origin != current:
        return "minted_elsewhere"
    if record.get("revoked_at"):
        return "revoked"
    if record.get("expires_at"):
        expiry = _epoch(record["expires_at"])
        if expiry is None or expiry <= time.time():
            return "expired"
    return None


def verify_for_owner(st, username: str, tenant: str, token: str) -> dict:
    """Diagnose only a session owner's secret inside that session's tenant runtime."""
    owner, tenant_key = _normalise_owner(username, tenant)
    _assert_bound_runtime(st, tenant_key)
    try:
        verified = verify(token, owner_runtime=st, owner=owner)
    except ExternalAuthError as exc:
        return {"valid": False, "cause": exc.cause, "warning": None, "origin_recorded": None}
    return {"valid": True, "cause": None, "warning": verified.warning,
            "origin_recorded": verified.origin_recorded, "key_id": verified.key_id}


def verify(token: str, *, owner_runtime=None, owner=None) -> VerifiedCredential:
    """Verify a bearer token from fresh state and resolve its ordinary public-user principal."""
    try:
        tenant_key, key_id, secret = _parse_token(token)
        if owner_runtime is not None:
            if not owner or getattr(owner_runtime, "key", None) != tenant_key:
                raise ExternalAuthError(AUTH_ERROR)
            st = owner_runtime
        else:
            try:
                st = runtime.get_runtime(tenant_key)
            except KeyError as exc:
                raise ExternalAuthError(AUTH_ERROR) from exc

        book = _book(st)
        record = book.get(key_id)
        cause = _credential_cause(record, tenant_key, key_id, secret, owner=owner)
        if cause:
            raise ExternalAuthError(AUTH_ERROR, cause=cause)

        owner = str(record["username"]).strip().lower()
        try:
            public = _active_public_user(owner, tenant_key)
        except ExternalAccessError as exc:
            raise ExternalAuthError(AUTH_ERROR) from exc

        access, databases = scope_of(record)
        if not _stamp_is_due(record.get("last_used"), time.time()):
            return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st,
                                      access=access, databases=databases, workbooks=workbooks_of(record),
                                      origin_recorded=bool(_recorded_space(record)))

        used_at = _now()

        def _stamp(value):
            if not isinstance(value, dict):
                raise ExternalAuthError(AUTH_ERROR)
            current = value.get(key_id)
            cause = _credential_cause(current, tenant_key, key_id, secret, owner=owner)
            if cause:
                raise ExternalAuthError(AUTH_ERROR, cause=cause)
            book_now = dict(value)
            stamped = dict(current)
            stamped["last_used"] = used_at
            book_now[key_id] = stamped
            return book_now

        warning = None
        try:
            st.update(BUCKET, _stamp, flush="sync")
        except ExternalAuthError:
            raise
        except Exception as exc:
            # Store diagnostics must not include credential material or exception text.
            _log.warning("external_access last_used stamp failed: %s", type(exc).__name__)
            warning = "store_write_refused"
        return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st,
                                  access=access, databases=databases, workbooks=workbooks_of(record),
                                  warning=warning, origin_recorded=bool(_recorded_space(record)))
    except ExternalAuthError:
        raise
    except ExternalAccessError as exc:
        if owner_runtime is not None:
            raise
        raise ExternalAuthError(AUTH_ERROR) from exc
    except Exception as exc:
        raise ExternalAuthError(AUTH_ERROR) from exc