Files
ecs-relay-service/deployable/relay/credential_api.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

318 lines
19 KiB
Python

"""Opt-in broker-mode OAuth and device-authenticated access-token issuance."""
import hashlib
import hmac
import json
import re
import secrets
import time
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from .common import no_cache, peer, rate_limit
from .credential_broker import (AuthorizationRequired, BrokerUnavailable, PermissionRequired, RefreshUnknown)
from .credential_store import CredentialError
from .crypto import canonical, verified, verify_device
class DeviceRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
host_id: str = Field(pattern=r"^[a-f0-9]{32}$")
binding_owner: str = Field(min_length=1, max_length=128)
binding_generation: int = Field(strict=True, ge=0)
request_id: str = Field(pattern=r"^[A-Za-z0-9_-]{8,100}$")
proof: dict = Field(repr=False)
class StatusRequest(DeviceRequest):
# Only status may bootstrap the generation, still proving the bound owner.
binding_generation: int | None = Field(default=None, strict=True, ge=0)
class PermissionRequest(DeviceRequest):
permission_profile: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")
class TransactionRequest(DeviceRequest):
transaction_id: str = Field(pattern=r"^oauth2_[a-f0-9]{32}$")
class CredentialAPI:
def __init__(self, settings, redis, store, broker, clock=time.time):
self.s, self.r, self.store, self.broker, self.clock = settings, redis, store, broker, clock
self.db = store.db
with self.db:
self.db.execute("""CREATE TABLE IF NOT EXISTS work_authorizations_v2(
transaction_id TEXT PRIMARY KEY, environment TEXT NOT NULL, app_id TEXT NOT NULL,
owner TEXT NOT NULL, host_id TEXT NOT NULL, binding_generation BIGINT NOT NULL,
permission_profile TEXT NOT NULL, scopes_json TEXT NOT NULL,
request_id TEXT NOT NULL, request_hash TEXT NOT NULL, state_hash TEXT NOT NULL UNIQUE,
state_key_id TEXT NOT NULL, state_ciphertext TEXT NOT NULL,
created_at DOUBLE PRECISION NOT NULL, expires_at DOUBLE PRECISION NOT NULL,
status TEXT NOT NULL,
UNIQUE(environment,app_id,host_id,binding_generation,request_id))""")
self.router = APIRouter()
self.router.add_api_route("/work/v2/status", self.status, methods=["POST"])
self.router.add_api_route("/work/v2/authorizations", self.start, methods=["POST"])
self.router.add_api_route("/work/v2/authorizations/status", self.transaction_status, methods=["POST"])
self.router.add_api_route("/work/v2/credentials/access-token", self.access_token, methods=["POST"])
self.router.add_api_route("/oauth/cb", self.callback, methods=["GET"])
def require_binding(self, host, owner, generation=None):
device = self.store.device(host)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "device_unbound_or_revoked")
if (device["owner"] != owner
or (generation is not None and device["binding_generation"] != generation)):
raise HTTPException(403, "stale_binding")
return device
async def authenticate(self, body, request):
await rate_limit(self.r, "credential-ip:" + peer(request), 300)
device = self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
try:
key = verify_device(device["cert"], self.s.ca_cert.read_bytes(), body.host_id)
proof = verified(body.proof, key)
if (type(proof["version"]) is not int or proof["version"] != 2
or proof["environment"] != self.s.environment or proof["app_id"] != self.s.feishu_app_id
or proof["host_id"] != body.host_id or proof["purpose"] != "work-v2"
or proof["method"] != "POST" or proof["path"] != request.url.path
or type(proof["ts"]) not in (int, float)
or not abs(self.clock() - proof["ts"]) <= 90
or not isinstance(proof["nonce"], str)
or not re.fullmatch(r"[a-f0-9]{32}", proof["nonce"])
or proof["payload_hash"] != hashlib.sha256(canonical(body.model_dump(exclude={"proof"}))).hexdigest()):
raise ValueError()
except Exception:
raise HTTPException(403, "invalid_device_proof") from None
if not await self.r.set("hn:credential-proof:" + body.host_id + ":" + proof["nonce"],
"used", nx=True, ex=180):
raise HTTPException(409, "device_request_replayed")
await rate_limit(self.r, "credential-device:" + body.host_id, 120)
# Binding may have changed during Redis awaits.
return self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
def scopes(self, profile):
scopes = self.s.credential_permission_profiles.get(profile)
if not scopes:
raise HTTPException(403, "permission_profile_not_allowed")
return tuple(sorted(set(scopes)))
def _credential_status(self, owner):
value = self.broker.store.get(self.s.environment, self.s.feishu_app_id, owner)
if value is None:
return {"credential_status": "authorization_required", "granted_scopes": []}
if self.broker.store.refresh_status(self.s.environment, self.s.feishu_app_id, owner, value.version):
status = "refresh_unknown"
elif value.access_expires_at > self.clock() or value.refresh_expires_at > self.clock():
status = "available"
else:
status = "authorization_required"
return {"credential_status": status, "granted_scopes": list(value.scopes),
"credential_version": value.version, "access_expires_at": value.access_expires_at}
async def status(self, body: StatusRequest, request: Request):
device = await self.authenticate(body, request)
try:
result = self._credential_status(device["owner"])
except CredentialError:
raise HTTPException(503, "credential_temporarily_unavailable") from None
self.require_binding(body.host_id, device["owner"], device["binding_generation"])
return no_cache(JSONResponse({"credential_mode": "broker", "protocol_version": 2,
"binding_owner": device["owner"],
"binding_generation": device["binding_generation"],
"permission_profiles": sorted(self.s.credential_permission_profiles), **result}))
def _row(self, transaction_id):
row = self.db.execute("""SELECT * FROM work_authorizations_v2
WHERE transaction_id=? AND environment=? AND app_id=?""",
(transaction_id, self.s.environment, self.s.feishu_app_id)).fetchone()
if not row:
raise HTTPException(404, "authorization_not_found")
return dict(row)
def _live_row(self, transaction_id):
row = self._row(transaction_id)
if row["expires_at"] <= self.clock():
raise HTTPException(410, "authorization_expired")
self.require_binding(row["host_id"], row["owner"], row["binding_generation"])
if list(self.scopes(row["permission_profile"])) != json.loads(row["scopes_json"]):
raise HTTPException(409, "permission_profile_changed")
return row
@staticmethod
def _state_aad(row):
names = ("transaction_id", "environment", "app_id", "owner", "host_id", "binding_generation",
"permission_profile", "scopes_json", "request_hash", "expires_at", "state_hash", "state_key_id")
return canonical(["hainuo-oauth-state-v2", *[row[name] for name in names]])
def _state(self, row):
try:
state = self.broker.store.keyring.decrypt(row["state_key_id"], row["state_ciphertext"],
self._state_aad(row)).decode("ascii")
if not hmac.compare_digest(hashlib.sha256(state.encode()).hexdigest(), row["state_hash"]):
raise ValueError()
return state
except Exception:
raise HTTPException(503, "authorization_state_unavailable") from None
def _authorization_url(self, row):
params = {"app_id": self.s.feishu_app_id, "redirect_uri": self.s.public_url.rstrip("/") + "/oauth/cb",
"state": self._state(row), "scope": " ".join(json.loads(row["scopes_json"]))}
return self.s.feishu_authorize_url + "?" + urlencode(params)
def authorization_url_for_notification(self, owner, host, transaction_id):
row = self._live_row(transaction_id)
if row["owner"] != owner or row["host_id"] != host or row["status"] != "waiting":
raise HTTPException(403, "active_device_owned_authorization_required")
return self._authorization_url(row)
async def start(self, body: PermissionRequest, request: Request):
device = await self.authenticate(body, request)
scopes = self.scopes(body.permission_profile)
await rate_limit(self.r, "credential-authorize:" + device["owner"], 5)
self.require_binding(body.host_id, device["owner"], device["binding_generation"])
request_hash = hashlib.sha256(canonical(body.model_dump(exclude={"proof"}))).hexdigest()
row = self.db.execute("""SELECT * FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND host_id=? AND binding_generation=? AND request_id=?""",
(self.s.environment, self.s.feishu_app_id, body.host_id, body.binding_generation, body.request_id)).fetchone()
if row:
row = dict(row)
if row["request_hash"] != request_hash:
raise HTTPException(409, "request_id_reused")
else:
count = self.db.execute("""SELECT COUNT(*) AS total FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND status IN ('waiting','exchanging') AND expires_at>?""",
(self.s.environment, self.s.feishu_app_id, self.clock())).fetchone()["total"]
if count >= self.s.max_pending:
raise HTTPException(503, "authorization_capacity_reached")
state = "v2_" + secrets.token_urlsafe(32)
row = {"transaction_id": "oauth2_" + secrets.token_hex(16), "environment": self.s.environment,
"app_id": self.s.feishu_app_id, "owner": device["owner"], "host_id": body.host_id,
"binding_generation": device["binding_generation"], "permission_profile": body.permission_profile,
"scopes_json": json.dumps(scopes, separators=(",", ":")), "request_id": body.request_id,
"request_hash": request_hash, "state_hash": hashlib.sha256(state.encode()).hexdigest(),
"state_key_id": self.broker.store.keyring.active_key_id,
"created_at": float(self.clock()), "expires_at": float(self.clock() + 600), "status": "waiting"}
_, row["state_ciphertext"] = self.broker.store.keyring.encrypt(state.encode(), self._state_aad(row))
with self.db:
# Take a database row lock without changing the binding. This
# serializes distinct authorization starts across PG workers;
# Redis lease ownership is not a substitute for this transaction.
bound = self.db.execute("""UPDATE devices SET binding_generation=binding_generation
WHERE host_id=? AND owner=? AND binding_generation=? AND revoked=0""",
(body.host_id, device["owner"], device["binding_generation"])).rowcount
if bound != 1:
raise HTTPException(403, "stale_binding")
inserted = self.db.execute("""INSERT INTO work_authorizations_v2
(transaction_id,environment,app_id,owner,host_id,binding_generation,permission_profile,
scopes_json,request_id,request_hash,state_hash,state_key_id,state_ciphertext,created_at,expires_at,status)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING""",
tuple(row[key] for key in ("transaction_id", "environment", "app_id", "owner", "host_id",
"binding_generation", "permission_profile", "scopes_json", "request_id", "request_hash",
"state_hash", "state_key_id", "state_ciphertext", "created_at", "expires_at", "status"))).rowcount
if inserted == 1:
# One current authorization intent per application/user. An
# older narrow consent must not overwrite newer permissions.
self.db.execute("""UPDATE work_authorizations_v2 SET status='superseded'
WHERE environment=? AND app_id=? AND owner=? AND transaction_id<>?
AND status IN ('waiting','exchanging')""",
(self.s.environment, self.s.feishu_app_id, device["owner"], row["transaction_id"]))
actual = self.db.execute("""SELECT transaction_id,request_hash FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND host_id=? AND binding_generation=? AND request_id=?""",
(self.s.environment, self.s.feishu_app_id, body.host_id, body.binding_generation, body.request_id)).fetchone()
if not actual or actual["request_hash"] != request_hash:
raise HTTPException(409, "request_id_reused")
row = self._live_row(actual["transaction_id"])
row = self._live_row(row["transaction_id"])
result = {"transaction_id": row["transaction_id"], "status": row["status"], "expires_at": row["expires_at"]}
if row["status"] == "waiting":
result["authorization_url"] = self._authorization_url(row)
return no_cache(JSONResponse(result, status_code=201))
async def transaction_status(self, body: TransactionRequest, request: Request):
await self.authenticate(body, request)
row = self._row(body.transaction_id)
if (row["owner"], row["host_id"], row["binding_generation"]) != (
body.binding_owner, body.host_id, body.binding_generation):
raise HTTPException(404, "authorization_not_found")
self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
status = ("expired" if row["expires_at"] <= self.clock() and row["status"] in {"waiting", "exchanging"}
else row["status"])
result = {"transaction_id": row["transaction_id"], "status": status}
if status == "authorized":
try:
result.update(self._credential_status(body.binding_owner))
except CredentialError:
raise HTTPException(503, "credential_temporarily_unavailable") from None
if not set(json.loads(row["scopes_json"])).issubset(result["granted_scopes"]):
result["status"] = "permission_update_required"
return no_cache(JSONResponse(result))
async def access_token(self, body: PermissionRequest, request: Request):
await self.authenticate(body, request)
required = self.scopes(body.permission_profile)
guard = lambda: self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
try:
grant = await self.broker.get_access(body.binding_owner, required_scopes=required, guard=guard)
except HTTPException:
raise
except AuthorizationRequired:
raise HTTPException(401, "authorization_required") from None
except PermissionRequired:
raise HTTPException(403, "permission_update_required") from None
except RefreshUnknown:
raise HTTPException(409, "refresh_unknown") from None
except (BrokerUnavailable, CredentialError):
raise HTTPException(503, "credential_temporarily_unavailable") from None
guard()
self.store.audit(body.binding_owner, "credential_issue", body.host_id + ":" + body.request_id,
"completed_v" + str(grant.credential_version))
# Explicit whitelist: never asdict(UserCredential) or pass a platform response.
return no_cache(JSONResponse({"access_token": grant.access_token, "token_type": "Bearer",
"expires_at": grant.expires_at, "expires_in": max(0, int(grant.expires_at - self.clock())),
"server_time": self.clock(), "credential_version": grant.credential_version,
"granted_scopes": list(grant.scopes), "app_id": self.s.feishu_app_id}))
async def callback(self, request: Request, code: str = "", state: str = "", error: str = ""):
await rate_limit(self.r, "credential-callback:" + peer(request), 60)
if not re.fullmatch(r"v2_[A-Za-z0-9_-]{43}", state) or len(code) > 4096:
raise HTTPException(400, "invalid_authorization_callback")
row = self.db.execute("""SELECT transaction_id FROM work_authorizations_v2
WHERE state_hash=? AND environment=? AND app_id=?""",
(hashlib.sha256(state.encode()).hexdigest(), self.s.environment, self.s.feishu_app_id)).fetchone()
if not row:
raise HTTPException(400, "invalid_authorization_callback")
transaction = self._live_row(row["transaction_id"])
if not hmac.compare_digest(self._state(transaction), state) or transaction["status"] != "waiting":
raise HTTPException(400, "authorization_already_consumed")
if not code and not error:
raise HTTPException(400, "invalid_authorization_callback")
with self.db:
count = self.db.execute("""UPDATE work_authorizations_v2 SET status=?
WHERE transaction_id=? AND status='waiting' AND expires_at>?""",
("cancelled" if error else "exchanging", transaction["transaction_id"], self.clock())).rowcount
if count != 1:
raise HTTPException(400, "authorization_already_consumed")
if error:
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权已取消,请返回客户端。</p>", status_code=400))
def guard():
current = self._live_row(transaction["transaction_id"])
if current["status"] != "exchanging":
raise HTTPException(409, "authorization_not_active")
try:
await self.broker.authorize(transaction["owner"], code, guard=guard)
guard()
except Exception:
with self.db:
self.db.execute("UPDATE work_authorizations_v2 SET status='failed' WHERE transaction_id=? AND status='exchanging'",
(transaction["transaction_id"],))
raise HTTPException(502, "authorization_did_not_complete") from None
with self.db:
self.db.execute("UPDATE work_authorizations_v2 SET status='authorized' WHERE transaction_id=? AND status='exchanging'",
(transaction["transaction_id"],))
self.store.audit(transaction["owner"], "credential_authorized", transaction["transaction_id"], "completed")
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权完成,请返回客户端。</p>"))