Add an internal CredentialBroker that serializes refresh and authorization by environment/app/user using renewable Redis leases. Re-read credentials under the lease and persist rotated pairs with expected-version CAS before returning an explicit access-only grant. Verify the actual platform user, remaining lifetime and scopes; never return refresh tokens from the broker. Persist source-version refresh attempts before platform calls. Timeouts, cancellation, lease loss, malformed responses and ambiguous database errors fence reuse of the old rotating refresh token, including after restart. A new authorization can establish a new version without stale overwrite. Add a strict, separate private Work v1 OIDC adapter while preserving legacy OAuth method behavior. Enable fakeredis Lua test support for Redis lease renewal tests. Document stage boundaries, recovery limitations and testing. Validation: 147 passed, 2 skipped (real PostgreSQL not configured), with 15 existing uvicorn/websockets deprecation warnings. New broker/adapter coverage: 45 tests. AST, runtime opt-in boundary and diff checks pass. An earlier Windows temp-file replace failure in a legacy client test passed both isolated rerun and the final full suite; no client code was changed. No public credential/OAuth routes are wired, no production database/key is initialized, and no real Work authorization, refresh or ECS deployment was performed. Authenticated access-token issuance, state transactions, binding checks and unbind integration remain subsequent stages.
133 lines
6.4 KiB
Python
133 lines
6.4 KiB
Python
import asyncio
|
|
import json
|
|
import time
|
|
import httpx
|
|
|
|
|
|
class PlatformError(Exception):
|
|
pass
|
|
|
|
|
|
class Feishu:
|
|
def __init__(self, settings, transport=None):
|
|
self.settings = settings
|
|
self.http = httpx.AsyncClient(base_url=settings.feishu_api_base.rstrip("/"),
|
|
timeout=15, follow_redirects=False, transport=transport, trust_env=False)
|
|
self._token = None
|
|
self._expires = 0
|
|
self._tenant_token = None
|
|
self._tenant_expires = 0
|
|
self._lock = asyncio.Lock()
|
|
|
|
async def close(self):
|
|
await self.http.aclose()
|
|
|
|
async def _json(self, method, path, **kwargs):
|
|
try:
|
|
response = await self.http.request(method, path, **kwargs)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
if data.get("code", 0) != 0:
|
|
raise PlatformError("platform rejected request")
|
|
return data
|
|
except (httpx.HTTPError, ValueError, KeyError) as exc:
|
|
# Never propagate upstream bodies or credentials to caller/logs.
|
|
raise PlatformError("platform request failed") from None
|
|
|
|
async def app_token(self):
|
|
async with self._lock:
|
|
if self._token and self._expires > time.monotonic() + 1800:
|
|
return self._token
|
|
data = await self._json("POST", "/open-apis/auth/v3/app_access_token/internal",
|
|
json={"app_id": self.settings.feishu_app_id,
|
|
"app_secret": self.settings.feishu_app_secret})
|
|
self._token = data["app_access_token"]
|
|
self._expires = time.monotonic() + int(data.get("expire", 7200))
|
|
return self._token
|
|
|
|
async def exchange(self, code):
|
|
token = await self.app_token()
|
|
data = await self._json("POST", "/open-apis/authen/v1/oidc/access_token",
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
json={"grant_type": "authorization_code", "code": code})
|
|
return self.normalize(data["data"])
|
|
|
|
async def tenant_token(self):
|
|
async with self._lock:
|
|
if self._tenant_token and self._tenant_expires > time.monotonic() + 1800:
|
|
return self._tenant_token
|
|
data = await self._json("POST", "/open-apis/auth/v3/tenant_access_token/internal",
|
|
json={"app_id": self.settings.feishu_app_id,
|
|
"app_secret": self.settings.feishu_app_secret})
|
|
self._tenant_token = data["tenant_access_token"]
|
|
self._tenant_expires = time.monotonic() + int(data.get("expire", 7200))
|
|
return self._tenant_token
|
|
|
|
async def refresh(self, refresh_token):
|
|
token = await self.app_token()
|
|
data = await self._json("POST", "/open-apis/authen/v1/oidc/refresh_access_token",
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
json={"grant_type": "refresh_token", "refresh_token": refresh_token})
|
|
result = self.normalize(data["data"])
|
|
info = await self.user_info(result["user_access_token"])
|
|
result["open_id"] = info["open_id"]
|
|
return result
|
|
|
|
@staticmethod
|
|
def normalize(data):
|
|
return {"user_access_token": data["access_token"], "refresh_token": data.get("refresh_token", ""),
|
|
"expires_in": data.get("expires_in", data.get("expire", 0)),
|
|
"refresh_expires_in": data.get("refresh_expires_in", 0), "open_id": data.get("open_id", "")}
|
|
|
|
async def user_info(self, token):
|
|
data = await self._json("GET", "/open-apis/authen/v1/user_info",
|
|
headers={"Authorization": f"Bearer {token}"})
|
|
return data["data"]
|
|
|
|
async def _credential_request(self, grant):
|
|
"""Strict stage-2 adapter; legacy OAuth normalization remains unchanged.
|
|
|
|
Missing rotation fields are not silently defaulted; the Broker validates
|
|
them and treats an ambiguous refresh as unknown rather than replaying it.
|
|
"""
|
|
try:
|
|
token = await self.app_token()
|
|
path = ("/open-apis/authen/v1/oidc/access_token" if grant["grant_type"] == "authorization_code"
|
|
else "/open-apis/authen/v1/oidc/refresh_access_token")
|
|
response = await self.http.post(path, headers={"Authorization": f"Bearer {token}"}, json=grant)
|
|
response.raise_for_status()
|
|
body = response.json()
|
|
if not isinstance(body, dict) or type(body.get("code")) is not int or body["code"] != 0:
|
|
raise ValueError()
|
|
data = body["data"]
|
|
result = {"user_access_token": data["access_token"], "refresh_token": data["refresh_token"],
|
|
"expires_in": data.get("expires_in", data.get("expire")),
|
|
"refresh_expires_in": data.get("refresh_expires_in")}
|
|
if "scope" in data:
|
|
result["scope"] = data["scope"]
|
|
return result
|
|
except Exception:
|
|
raise PlatformError("credential platform request failed") from None
|
|
|
|
async def credential_exchange(self, code):
|
|
return await self._credential_request({"grant_type": "authorization_code", "code": code})
|
|
|
|
async def credential_refresh(self, refresh_token):
|
|
return await self._credential_request({"grant_type": "refresh_token", "refresh_token": refresh_token})
|
|
|
|
async def reply(self, message_id, text):
|
|
# Reply to the original message only: no caller-controlled recipient.
|
|
token = await self.tenant_token()
|
|
await self._json("POST", f"/open-apis/im/v1/messages/{message_id}/reply",
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
json={"msg_type": "text", "content": json.dumps({"text": text}, ensure_ascii=False)})
|
|
|
|
async def send(self, owner, msg_type, content, delivery_id, *, token=None):
|
|
token = token or await self.tenant_token()
|
|
data = await self._json('POST', '/open-apis/im/v1/messages',
|
|
params={'receive_id_type': 'open_id'},
|
|
headers={'Authorization': 'Bearer ' + token},
|
|
json={'receive_id': owner, 'msg_type': msg_type,
|
|
'content': json.dumps(content, ensure_ascii=False), 'uuid': delivery_id})
|
|
return data.get('data', {})
|