Files
kefu/wechat_rpa/group_access.py
T
2026-11-04 10:14:23 +08:00

256 lines
11 KiB
Python

"""Authenticated, read-only group metadata snapshots; never enroll or grant."""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import re
import threading
import time
from pathlib import Path
from typing import Any, Callable
SIGNED_PATH = "/group/access-snapshot"
MAX_REQUEST_BYTES = 16 * 1024
MAX_RESPONSE_BYTES = 4 * 1024 * 1024
MAX_GIDS = 100
MAX_PERMISSIONS = 2000
WINDOW_SECONDS = 90
MAX_NONCES = 8192
_HEX_32 = re.compile(r"[0-9a-f]{32}\Z")
_HEX_64 = re.compile(r"[0-9a-f]{64}\Z")
_GID = re.compile(r"gid_[0-9a-f]{32}\Z")
_TIMESTAMP = re.compile(r"(?:0|[1-9][0-9]{0,11})\Z")
class AccessError(ValueError):
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
def _unavailable() -> AccessError:
return AccessError(503, "集团授权元数据暂不可用")
def load_key() -> bytes:
"""Load only the explicitly configured, bounded, non-public key file."""
configured = os.environ.get("ZYT_GROUP_METADATA_KEY_FILE", "")
try:
path = Path(configured)
if not configured or not path.is_absolute() or path.is_symlink():
raise ValueError("Invalid key location")
resolved = path.resolve(strict=True)
project = Path(__file__).resolve().parent.parent
public_roots = (
project / "admin-web/apps/web-antd/dist",
project / "admin-web/apps/mobile-h5/dist",
)
if any(resolved.is_relative_to(root.resolve()) for root in public_roots):
raise ValueError("Public key location")
with resolved.open("rb") as source:
raw = source.read(65)
if not re.fullmatch(rb"[0-9a-fA-F]{64}", raw):
raise ValueError("Invalid key contents")
return bytes.fromhex(raw.decode("ascii"))
except (OSError, ValueError, RuntimeError):
raise _unavailable() from None
def request_signature(key: bytes, body: bytes, timestamp: str, nonce: str) -> str:
signed = f"POST\n{SIGNED_PATH}\n{timestamp}\n{nonce}\n{hashlib.sha256(body).hexdigest()}"
return hmac.new(key, signed.encode("ascii"), hashlib.sha256).hexdigest()
def response_signature(key: bytes, body: bytes, nonce: str) -> str:
signed = f"response\n{nonce}\n{hashlib.sha256(body).hexdigest()}"
return hmac.new(key, signed.encode("ascii"), hashlib.sha256).hexdigest()
def _object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate JSON key")
result[key] = value
return result
def parse_request(body: bytes) -> dict[str, Any]:
try:
def invalid_constant(_value):
raise ValueError("Invalid JSON constant")
value = json.loads(body.decode("utf-8"), object_pairs_hook=_object,
parse_constant=invalid_constant)
if not isinstance(value, dict) or set(value) != {"client_id", "gids", "include_catalog"}:
raise ValueError("Invalid fields")
gids = value["gids"]
if value["client_id"] != "kefu" or type(value["include_catalog"]) is not bool:
raise ValueError("Invalid client")
if not isinstance(gids, list) or len(gids) > MAX_GIDS:
raise ValueError("Invalid subjects")
if any(not isinstance(gid, str) or not _GID.fullmatch(gid) for gid in gids):
raise ValueError("Invalid identity")
if len(set(gids)) != len(gids):
raise ValueError("Duplicate identities")
return value
except (ValueError, UnicodeError, RecursionError):
raise AccessError(422, "集团授权元数据请求无效") from None
def _positive(value: Any) -> int:
if type(value) is not int or value < 1:
raise _unavailable()
return value
def _text(value: Any) -> str:
if not isinstance(value, str):
raise _unavailable()
return value
def snapshot(database, request: dict[str, Any], generated_at: int) -> dict[str, Any]:
"""Project existing bindings only. Authorization stays in its existing reader."""
gids = request["gids"]
rows = {}
if gids:
with database.connect() as db:
placeholders = ",".join("?" for _ in gids)
found = db.execute(f"""SELECT b.gid,b.source_admin_id,b.company_id,
b.source_account,b.source_name,u.id,u.username,u.active,
u.role AS role_code,COALESCE(r.name,u.role) AS role_name
FROM group_sso_bindings b JOIN users u ON u.id=b.user_id
LEFT JOIN roles r ON r.code=u.role
WHERE b.provider=? AND b.gid IN ({placeholders})""",
["zyt_group", *gids]).fetchall()
rows = {row["gid"]: dict(row) for row in found}
subjects = []
for gid in gids:
row = rows.get(gid)
if row is None:
subjects.append({"gid": gid, "found": False})
continue
user_id = _positive(row["id"])
# Deliberately use the same effective-permission reader as ordinary API
# authentication. Inactive users are empty there; do not reinterpret
# catalog enabled flags as API authorization rules.
permissions = sorted(database.permissions_for_user(user_id))
if len(permissions) > MAX_PERMISSIONS or any(not isinstance(code, str) for code in permissions):
raise _unavailable()
# A concurrent deactivation must not pair an inactive metadata row with
# nonempty permissions. This does not claim a cross-request transaction.
if not row["active"]:
permissions = []
subjects.append({
"gid": gid, "found": True,
"source_admin_id": _positive(row["source_admin_id"]),
"company_id": _positive(row["company_id"]),
"user": {
"id": user_id, "username": _text(row["username"]),
"source_account": _text(row["source_account"]),
"source_name": _text(row["source_name"]), "active": bool(row["active"]),
"role": {"code": _text(row["role_code"]), "name": _text(row["role_name"])},
"permissions": permissions,
},
})
catalog = None
if request["include_catalog"]:
definitions = database.permission_catalog()
if len(definitions) > MAX_PERMISSIONS:
raise _unavailable()
permissions = []
seen = set()
for item in definitions:
code = _text(item["code"])
if not code or code in seen or item["kind"] not in {"page", "action", "link"}:
raise _unavailable()
seen.add(code)
# A custom link is a page in this protocol; never expose its URL.
permissions.append({
"code": code, "name": _text(item["name"]),
"group": _text(item["group_name"]), "page": _text(item["page_name"]),
"kind": "page" if item["kind"] == "link" else item["kind"],
"source": _text(item["source"]), "enabled": bool(item["enabled"]),
"sort": int(item["sort_order"]),
})
catalog = {"permissions": permissions}
return {"version": 1, "client_id": "kefu", "generated_at": generated_at,
"subjects": subjects, "catalog": catalog}
class AccessSnapshot:
"""One application instance's bounded, fail-closed read-protocol replay cache.
Memory replay protection is permitted by metadata v1. Multi-worker installs
should share a nonce store when replay rejection across workers is required.
"""
def __init__(self, database, clock: Callable[[], float] | None = None,
max_nonces: int = MAX_NONCES):
self.database = database
self.clock = clock or time.time
self.max_nonces = max_nonces
self._nonces: dict[str, int] = {}
self._lock = threading.Lock()
def respond(self, body: bytes, headers) -> tuple[bytes, dict[str, str]]:
key = load_key()
if len(body) > MAX_REQUEST_BYTES:
raise AccessError(413, "集团授权元数据请求过大")
timestamp = headers.get("x-group-timestamp", "")
nonce = headers.get("x-group-nonce", "")
signature = headers.get("x-group-signature", "")
now = int(self.clock())
if (not _TIMESTAMP.fullmatch(timestamp) or not _HEX_32.fullmatch(nonce)
or not _HEX_64.fullmatch(signature) or abs(int(timestamp) - now) > WINDOW_SECONDS):
raise AccessError(401, "集团服务认证无效")
if not hmac.compare_digest(request_signature(key, body, timestamp, nonce), signature):
raise AccessError(401, "集团服务认证无效")
with self._lock:
self._nonces = {value: expires for value, expires in self._nonces.items() if expires >= now}
if nonce in self._nonces:
raise AccessError(401, "集团服务认证无效")
if len(self._nonces) >= self.max_nonces:
raise _unavailable()
self._nonces[nonce] = int(timestamp) + WINDOW_SECONDS
request = parse_request(body)
try:
result = snapshot(self.database, request, now)
raw = json.dumps(result, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
if len(raw) > MAX_RESPONSE_BYTES:
raise _unavailable()
except AccessError:
raise
except Exception:
# No upstream/database values or deployment paths may reach callers.
raise _unavailable() from None
return raw, {"Cache-Control": "no-store",
"X-Group-Response-Signature": response_signature(key, raw, nonce)}
async def handle_request(request, service: AccessSnapshot):
"""Read bounded raw bytes; authenticate before any JSON interpretation."""
from fastapi.responses import JSONResponse, Response
try:
if request.url.query:
raise AccessError(422, "集团授权元数据请求无效")
for name in ("x-group-timestamp", "x-group-nonce", "x-group-signature"):
if len(request.headers.getlist(name)) != 1:
raise AccessError(401, "集团服务认证无效")
raw = bytearray()
async for chunk in request.stream():
if len(raw) + len(chunk) > MAX_REQUEST_BYTES:
raise AccessError(413, "集团授权元数据请求过大")
raw.extend(chunk)
# The DB work and key-file access run outside the application's loop.
import asyncio
body, headers = await asyncio.to_thread(service.respond, bytes(raw), request.headers)
return Response(content=body, media_type="application/json", headers=headers)
except AccessError as exc:
return JSONResponse(status_code=exc.status, content={"detail": str(exc)},
headers={"Cache-Control": "no-store"})