Files
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

147 lines
7.0 KiB
Python

import asyncio
import hashlib
import hmac
import secrets
import time
from dataclasses import dataclass
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
from .common import no_cache, peer, rate_limit
from .platform import PlatformError
@dataclass
class Transaction:
secret_hash: str
expires: float
status: str = "waiting"
result: dict | None = None
owner: str = ""
host_id: str = ""
class Empty(BaseModel):
host_id: str = ""
proof: dict = Field(default_factory=dict)
class Refresh(BaseModel):
refresh_token: str = Field(min_length=1, max_length=4096)
class OAuth:
"""A single connector process owns transactions and tokens in memory only."""
def __init__(self, settings, redis, platform):
self.settings, self.redis, self.platform = settings, redis, platform
self.pending: dict[str, Transaction] = {}
self.lock = asyncio.Lock()
self.router = APIRouter()
self.router.add_api_route("/oauth/start", self.start, methods=["POST"], status_code=201)
self.router.add_api_route("/oauth/cb", self.callback, methods=["GET"])
self.router.add_api_route("/oauth/claim", self.claim, methods=["GET"])
self.router.add_api_route("/oauth/pending", self.status, methods=["GET"])
self.router.add_api_route("/oauth/refresh", self.refresh, methods=["POST"])
def prune(self):
now = time.monotonic()
for state in list(self.pending):
if self.pending[state].expires <= now:
del self.pending[state]
def authenticated(self, state, secret):
self.prune()
item = self.pending.get(state)
digest = hashlib.sha256((secret or "").encode()).hexdigest()
if not item or not hmac.compare_digest(item.secret_hash, digest):
raise HTTPException(404, "transaction not found")
return item
async def start(self, body: Empty, request: Request):
if not self.settings.feishu_enabled or not self.settings.oauth_enabled:
raise HTTPException(503, "platform disabled")
await rate_limit(self.redis, "oauth:start:" + peer(request), 20)
owner = ""
if body.host_id:
from .device_auth import device_owner
owner = await device_owner(self.settings, self.redis, self.store, body.host_id,
body.proof, "work-oauth-v1", {})
async with self.lock:
self.prune()
if len(self.pending) >= self.settings.max_pending:
raise HTTPException(503, "too many pending transactions")
state, secret = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
self.pending[state] = Transaction(hashlib.sha256(secret.encode()).hexdigest(), time.monotonic() + 600,
owner=owner, host_id=body.host_id)
redirect = self.settings.public_url.rstrip("/") + "/oauth/cb"
parameters = {"app_id": self.settings.feishu_app_id, "redirect_uri": redirect, "state": state}
if self.settings.feishu_oauth_scopes:
parameters["scope"] = self.settings.feishu_oauth_scopes
url = self.settings.feishu_authorize_url + "?" + urlencode(parameters)
return no_cache(JSONResponse({"state": state, "claim_secret": secret, "authorization_url": url,
"redirect_uri": redirect, "expires_in": 600,
"code_ttl": 60, "poll_interval": 2}, status_code=201))
async def callback(self, request: Request, state: str = "", code: str = "", error: str = ""):
await rate_limit(self.redis, "oauth:cb:" + peer(request))
async with self.lock:
self.prune()
item = self.pending.get(state)
if error and item and item.status == "waiting":
item.status = "failed"
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权未完成,请返回客户端重新授权。</p>", status_code=400))
if not code or len(code) > 4096 or not item or item.status != "waiting":
raise HTTPException(400, "invalid callback")
item.status = "exchanging"
try:
result = await self.platform.exchange(code)
info = await self.platform.user_info(result["user_access_token"])
if not info.get("open_id") or (item.owner and info["open_id"] != item.owner):
raise PlatformError("authorization user mismatch")
result["open_id"] = info["open_id"]
except PlatformError:
async with self.lock:
item.status = "failed"
raise HTTPException(502, "authorization exchange failed") from None
async with self.lock:
if state not in self.pending or item.expires <= time.monotonic():
self.pending.pop(state, None)
raise HTTPException(400, "authorization expired")
item.result, item.status = result, "ready"
item.expires = min(item.expires, time.monotonic() + 60)
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权完成,请返回客户端。</p>"))
async def claim(self, request: Request, state: str):
await rate_limit(self.redis, "oauth:claim:" + peer(request))
async with self.lock:
item = self.authenticated(state, request.headers.get("X-OAuth-Claim-Secret"))
if item.status == "failed":
del self.pending[state]
raise HTTPException(502, "authorization failed")
if item.status != "ready":
return no_cache(JSONResponse({"status": "waiting", "retry_after": 2}, status_code=202))
del self.pending[state]
return no_cache(JSONResponse({"status": "claimed", **item.result}))
async def status(self, request: Request, state: str):
await rate_limit(self.redis, "oauth:pending:" + peer(request))
async with self.lock:
item = self.authenticated(state, request.headers.get("X-OAuth-Claim-Secret"))
return no_cache(JSONResponse({"status": item.status}))
async def refresh(self, body: Refresh, request: Request):
if not self.settings.feishu_enabled:
raise HTTPException(503, "platform disabled")
await rate_limit(self.redis, "oauth:refresh:" + peer(request), 20)
# Lock and consume before the upstream call; ambiguous failures never retry an old refresh token.
digest = hashlib.sha256(body.refresh_token.encode()).hexdigest()
if not await self.redis.set("hn:refresh:" + digest, "used", nx=True, ex=2592000):
raise HTTPException(409, "refresh already attempted; use returned token or reauthorize")
try:
result = await self.platform.refresh(body.refresh_token)
except PlatformError:
raise HTTPException(502, "refresh failed; reauthorize") from None
return no_cache(JSONResponse(result))