Files
ecs-relay-service/container-code/longconn/relay/work_api.py

153 lines
8.3 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, verified, verify_device
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, []))
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"]
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