feat(credentials): add stage 3 authenticated OAuth and access-token issuance

Add explicit legacy/broker configuration. Broker mode requires a protected
keyring, product-approved permission profiles and enabled platform OAuth;
production requires PostgreSQL. Default legacy behavior stays unchanged.

Wire the broker to v2 signed device status, authorization start/status and
access-token issuance routes. Bind proofs to protocol, environment, app,
method/path and complete payload; verify nonce, certificate, owner and
binding generation. Add an additive generation migration and return the
current generation in binding receipts or authenticated bootstrap status.

Persist encrypted OAuth state and atomically claim callbacks. Verify the
actual consenting user, supersede older pending authorization intents and
recheck bindings/transactions before credential writes and issuance.
Preserve rotated credentials if unbind occurs mid-refresh, but deny issuance.
Return an explicit access-only response and record metadata-only audit.

Extract shared legacy device authentication so notifications do not depend
on the business proxy module. Broker mode omits legacy refresh/claim/start
and /work/api routes; authorization cards reference server-owned v2
transactions. Document signatures, configuration and migration boundaries.

Validation: 185 passed, 3 skipped (real PostgreSQL not configured), with
15 existing dependency deprecation warnings. New API coverage: 38 passed,
1 real PostgreSQL case skipped. AST, docs and staged diff checks pass.

No production deployment, key generation, client upgrade or real Work API
calls were performed. Compose/mount configuration, full unbind/connection
compensation and durable message-task lifecycle remain later stages.
This commit is contained in:
ex_tianzy
2026-11-04 10:52:16 +08:00
parent 02d433250f
commit 93bfbca83a
13 changed files with 1066 additions and 47 deletions
+14 -2
View File
@@ -148,12 +148,14 @@ class CredentialBroker:
return AccessGrant(credential.access_token, credential.access_expires_at,
remaining, credential.version, credential.scopes)
async def authorize(self, owner, code):
async def authorize(self, owner, code, *, guard=None):
"""Only callable after the future OAuth transaction authenticates owner/state."""
identity = self._identity(owner)
if not isinstance(code, str) or not code or len(code) > 4096:
raise CredentialError("invalid authorization input")
async with self._lease(owner) as lease:
if guard:
guard()
current = self.store.get(*identity)
expected_version = current.version if current else 0
started = self.clock()
@@ -164,6 +166,8 @@ class CredentialBroker:
if not isinstance(info, dict) or info.get("open_id") != owner:
raise CredentialError("authorization identity mismatch")
await lease.check()
if guard:
guard()
version = self.store.save(*identity, expected_version=expected_version, **payload)
except CredentialConflict:
raise BrokerUnavailable("credential version changed") from None
@@ -176,11 +180,13 @@ class CredentialBroker:
credential = UserCredential(version=version, **{**payload, "scopes": tuple(payload["scopes"])})
return self._grant(credential, ())
async def get_access(self, owner, *, required_scopes=()):
async def get_access(self, owner, *, required_scopes=(), guard=None):
identity = self._identity(owner)
required = self._scopes(required_scopes)
# Lock even cache hits: authorization replacement and refresh share one owner.
async with self._lease(owner) as lease:
if guard:
guard()
current = self.store.get(*identity)
if current is None:
raise AuthorizationRequired("authorization required")
@@ -190,6 +196,8 @@ class CredentialBroker:
raise PermissionRequired("permission update required")
if current.access_expires_at - self.clock() > self.minimum_validity:
await lease.check()
if guard:
guard()
return self._grant(current, required)
if current.refresh_expires_at <= self.clock():
raise AuthorizationRequired("authorization required")
@@ -200,6 +208,8 @@ class CredentialBroker:
started = self.clock()
try:
await lease.check()
if guard:
guard()
result = await asyncio.wait_for(self.platform.credential_refresh(current.refresh_token),
self.platform_timeout)
payload = self._payload(result, started, previous=current)
@@ -223,4 +233,6 @@ class CredentialBroker:
self.store.finish_refresh(*identity, current.version, attempt, "completed")
from .credential_store import UserCredential
credential = UserCredential(version=version, **{**payload, "scopes": tuple(payload["scopes"])})
if guard:
guard()
return self._grant(credential, required)