Files
ecs-relay-service/deployable/relay/device_auth.py
T
ex_tianzy 93bfbca83a 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.
2026-11-04 10:52:16 +08:00

26 lines
1.1 KiB
Python

"""Shared legacy device proof verification; v2 adds binding/version checks."""
import hashlib
import re
import time
from fastapi import HTTPException
from .crypto import canonical, verified, verify_device
async def device_owner(settings, redis, store, host, proof, purpose, payload):
device = store.device(host)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "active bound device required")
try:
key = verify_device(device["cert"], settings.ca_cert.read_bytes(), host)
data = verified(proof, key)
if (data["host_id"] != host or data["purpose"] != purpose or abs(time.time() - data["ts"]) > 90
or not re.fullmatch(r"[a-f0-9]{32}", data["nonce"])
or data["payload_hash"] != hashlib.sha256(canonical(payload)).hexdigest()):
raise ValueError()
except Exception:
raise HTTPException(403, "invalid device request proof") from None
if not await redis.set("hn:work-proof:" + host + ":" + data["nonce"], "1", nx=True, ex=180):
raise HTTPException(409, "device request replayed")
return device["owner"]