"""Lean ZKCoding gateway, preserving the original gateway's identity contract.""" from __future__ import annotations import uuid from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.middleware.trustedhost import TrustedHostMiddleware from src.modules.knowledge.api.router import build_router as knowledge_router from src.modules.skill.api.router import build_router as skill_router from src.modules.skill.domain.models import Actor, SkillError def attach(app, skill_service, knowledge_catalog, *, verifier=None, organization_check=None, resource_client=None, runtime=None): """Reuse an injected verifier, including app.state.identity.verify from WorkOS.""" if getattr(app.state, "zkcoding_skill", None) is not None: raise ValueError("SKILL_ALREADY_ATTACHED") app.state.zkcoding_skill = skill_service app.state.zkcoding_knowledge = knowledge_catalog def principal(request: Request): if any(h in request.headers for h in ("x-user-id", "x-tenant-id", "x-internal-authorization")): raise SkillError("UNTRUSTED_IDENTITY_HEADER", "不能使用客户端身份头。", 400) authorization = request.headers.get("authorization", "") if not authorization.startswith("Bearer ") or len(authorization) > 8192: raise SkillError("TOKEN_INVALID", "请先登录。", 401) verify = verifier or getattr(getattr(request.app.state, "identity", None), "verify", None) if verify is None: raise SkillError("IDENTITY_NOT_CONFIGURED", "身份服务尚未接入。", 503) try: user = verify(authorization[7:]) if organization_check: organization_check(user) return Actor(tenant_id=user["tenant_id"], user_id=user["user_id"], roles=list(user.get("roles", []))) except SkillError: raise except Exception: raise SkillError("TOKEN_INVALID", "登录状态无效或已撤销。", 401) from None @app.exception_handler(SkillError) async def error(request, exc): return JSONResponse(status_code=exc.status, content={"code": exc.code, "message": exc.message, "details": exc.details, "trace_id": getattr(request.state, "trace_id", "")}) @app.exception_handler(RequestValidationError) async def invalid(request, exc): return JSONResponse(status_code=422, content={"code": "VALIDATION_ERROR", "message": "输入不符合接口契约。", "details": {"fields": [".".join(map(str, x["loc"])) for x in exc.errors()]}, "trace_id": getattr(request.state, "trace_id", "")}) app.include_router(skill_router(skill_service, principal, runtime=runtime)) app.include_router(knowledge_router(knowledge_catalog, principal)) if runtime is not None: from src.modules.orchestrator.api import build_router app.include_router(build_router(runtime, principal)) if resource_client: from fastapi import Depends @app.get("/api/v1/admin/resources/usage", tags=["ZKCoding Resources"]) def usage(actor=Depends(principal)): skill_service.require(actor, {"admin", "skill_manager"}) return {"items": resource_client.summary()} app.openapi_schema = None return app def create_app(skill_service, knowledge_catalog, *, verifier=None, resource_client=None, runtime=None): app = FastAPI(title="智科Coding API Gateway", version="0.1.0", description="Skill、知识库与编程资源接口;无办公业务") app.add_middleware(TrustedHostMiddleware, allowed_hosts=["127.0.0.1", "localhost", "testserver"]) @app.middleware("http") async def boundary(request: Request, call_next): request.state.trace_id = "trace-" + uuid.uuid4().hex[:16] # Buffer at most 2 MiB even without Content-Length. Does not read knowledge archives over HTTP. raw = bytearray() async for chunk in request.stream(): raw.extend(chunk) if len(raw) > 2 * 1024 * 1024: return JSONResponse(status_code=413, content={"code": "PAYLOAD_TOO_LARGE", "trace_id": request.state.trace_id}) request._body = bytes(raw) response = await call_next(request) response.headers["X-Trace-Id"] = request.state.trace_id response.headers["Cache-Control"] = "no-store" return response @app.get("/health/live") def live(): return {"status": "alive", "mode": "local-module-development", "office_modules": False} return attach(app, skill_service, knowledge_catalog, verifier=verifier, resource_client=resource_client, runtime=runtime)