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

136 lines
7.4 KiB
Python

"""Device-authenticated USER-token business gateway; no tenant-token fallback."""
import hashlib
import json
import re
import time
from urllib.parse import unquote
import httpx
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from .common import no_cache, rate_limit
from .crypto import canonical
from .device_auth import device_owner
from .store import INTEGRITY_ERRORS
class DeviceProof(BaseModel):
host_id: str = Field(pattern=r"^[a-f0-9]{32}$")
proof: dict
class BusinessCall(DeviceProof):
method: str = Field(pattern=r"^(GET|POST|PATCH|DELETE)$")
path: str = Field(max_length=1500)
params: dict = Field(default_factory=dict)
body: dict = Field(default_factory=dict)
operation_id: str = Field(default="", max_length=100)
def business_allowed(method, path):
if any(x in unquote(path) for x in ("..", "\\", "%", "?", "#", "\r", "\n")):
return False
seg = r"[A-Za-z0-9_.@-]+"
cal = r"/open-apis/calendar/v4/calendars"
rules = {
"GET": [cal, cal + "/" + seg, cal + "/" + seg + "/events(?:/" + seg + ")?(?:/attendees)?",
r"/open-apis/contact/v3/users/" + seg, r"/open-apis/search/v1/user",
r"/open-apis/(?:drive/v1/files|docx/v1/documents|wiki/v2/spaces|bitable/v1/apps)(?:/" + seg + ")*"],
"POST": [cal + "/primary", cal + "/" + seg + "/events(?:/" + seg + "/attendees)?"],
"PATCH": [cal + "/" + seg + "/events/" + seg],
"DELETE": [cal + "/" + seg + "/events/" + seg, cal + "/" + seg + "/events/" + seg + "/attendees/" + seg],
}
return any(re.fullmatch(p, path) for p in rules.get(method, []))
def router(settings, redis, store, platform):
routes = APIRouter()
store.db.execute("""CREATE TABLE IF NOT EXISTS business_operations(
owner TEXT NOT NULL, operation_id TEXT NOT NULL, request_hash TEXT NOT NULL,
status TEXT NOT NULL, result_meta TEXT NOT NULL, created DOUBLE PRECISION NOT NULL,
PRIMARY KEY(owner,operation_id))""")
if not settings.database_url:
store.db.commit()
@routes.post("/work/api")
async def call(body: BusinessCall, request: Request):
if not settings.feishu_enabled:
raise HTTPException(503, "platform disabled")
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer ") or not 10 < len(auth) <= 8192:
raise HTTPException(401, "user access token required")
if not business_allowed(body.method, body.path):
raise HTTPException(403, "business method/path not supported")
payload = {"method": body.method, "path": body.path, "params": body.params, "body": body.body,
"operation_id": body.operation_id, "token_hash": hashlib.sha256(auth[7:].encode()).hexdigest()}
owner = await device_owner(settings, redis, store, body.host_id, body.proof, "work-api-v1", payload)
await rate_limit(redis, "work-api:" + owner, 60)
try:
info = await platform.user_info(auth[7:])
except Exception:
raise HTTPException(401, "user token expired or invalid; refresh or authorize") from None
if info.get("open_id") != owner:
raise HTTPException(403, "token user does not match bound device owner")
write = body.method != "GET" and not body.path.endswith(("/primary", "/batch_get_id"))
digest = hashlib.sha256(canonical({k: v for k, v in payload.items() if k != "token_hash"})).hexdigest()
if write:
if not re.fullmatch(r"[A-Za-z0-9_-]{8,100}", body.operation_id):
raise HTTPException(422, "write requires stable operation_id")
try:
with store.db:
store.db.execute("INSERT INTO business_operations VALUES(?,?,?,?,?,?)",
(owner, body.operation_id, digest, "inflight", "{}", time.time()))
except INTEGRITY_ERRORS:
row = dict(store.db.execute("SELECT * FROM business_operations WHERE owner=? AND operation_id=?",
(owner, body.operation_id)).fetchone())
if row["request_hash"] != digest:
raise HTTPException(409, "operation_id reused with different request")
return no_cache(JSONResponse({"status": "duplicate", "operation_id": body.operation_id,
"previous_status": row["status"], **json.loads(row["result_meta"])}))
params = dict(body.params)
if write and body.method == "POST" and body.path.endswith("/events"):
params["idempotency_key"] = hashlib.sha256((owner + body.operation_id).encode()).hexdigest()
try:
async with platform.http.stream(body.method, body.path, params=params,
json=body.body if body.method != "GET" else None,
headers={"Authorization": auth}) as upstream:
raw = bytearray()
async for chunk in upstream.aiter_bytes():
raw.extend(chunk)
if len(raw) > 2 * 1024 * 1024:
raise ValueError()
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError()
code = data.get("code", 0)
if upstream.status_code != 200 or code != 0:
status = "platform_rejected"
def safe_diagnostic(value):
text = str(value)
for secret in (auth, auth[7:], settings.feishu_app_secret, settings.admin_secret, settings.internal_secret):
if secret:
text = text.replace(secret, "[redacted]")
return text[:2000]
detail = data.get("error") or {}
result = {"status": status, "http_status": upstream.status_code, "platform_code": code,
"message": "平台拒绝:请核对用户授权、应用scope、资源权限或接口版本。",
"platform_message": safe_diagnostic(data.get("msg", data.get("message", ""))),
"platform_log_id": safe_diagnostic(detail.get("log_id", "")) if isinstance(detail, dict) else "",
"permission_details": safe_diagnostic(detail.get("permission_violations", [])) if isinstance(detail, dict) else ""}
else:
status, result = "completed", {"status": "completed", "data": data.get("data", {})}
except (httpx.HTTPError, ValueError):
status = "unknown" if write else "failed"
result = {"status": status, "message": "平台请求未取得明确结果;写操作不要换新ID重试,请先核对日历。"}
if write:
event = result.get("data", {}).get("event", {})
meta = {k: event[k] for k in ("event_id", "app_link") if k in event}
with store.db:
store.db.execute("UPDATE business_operations SET status=?,result_meta=? WHERE owner=? AND operation_id=?",
(status, json.dumps(meta), owner, body.operation_id))
store.audit(owner, "work_api_" + body.method.lower(), body.path, status)
return no_cache(JSONResponse(result))
return routes