Files
lixi 062e11b1ff
CI / ai-gates (push) Successful in 39s
feat(ai): 内部 HTTP 端点 + 服务票校验 + 契约漂移守卫(166 测试)
按 openapi-internal.yaml 落地两个端点与鉴权,全部离线可测。

**鉴权(app/api/auth.py)**是这一层的安全边界,三条纪律各有测试:
- **强制校验 aud 与 iss**(交给 pyjwt 强制,不解出来自己比——自己比容易漏掉
  「claim 不存在」那一路)。这是独立密钥对方案唯一的意义所在:Java 侧现有的
  JwtVerifier 只验签名、不校验 aud,正因如此才必须独立密钥;若本服务也只验签名,
  那对独立密钥就白搭了。
- **额外强制 typ=service**,作为「有人误把用户密钥配到这里」的第二道防线。
- **缺公钥时全拒而非全过**。配置缺失必须立刻暴露,而不是变成一扇敞开的门;
  与 Java 侧 InternalAuthFilter 未配置 internal-token 时全拒 /internal/** 一致。
- 失败一律返回同一个笼统原因,**不告诉调用方是签名错/过期/aud 不符**——对方是
  我们自己的服务,真正原因在日志里;细节回给调用方只会在将来某天变成提示。

**三类失败分开**(契约核心)。第三类「任务失败」走 200 + state=failed + failure,
因为那种情况下 HTTP 调用是成功的;做成非 2xx 会让「查不到任务」与「任务失败了」
难以区分。另外两处刻意选择:
- 服务商 429 **不透传**,一律 502 + provider 信封。429 既可能是「等几秒」也可能是
  「等到明天」,状态码表达不了这个区别,retry 才是权威信号。
- 超出模型限制的请求归 service/invalid_request 而非 provider——请求**根本没发出去**,
  归到 provider 会让调用方以为是上游问题而去退避重试,而重试同样的参数永远不会变好。
- 服务商 404(含超出其 7 天保留期)归 service/task_not_found:调用方要做的是
  **停止轮询**,不是退避重试。
- 接管 FastAPI 默认的 {"detail": [...]} 校验错误,否则调用方要处理三种形状,
  而第三种还是框架实现细节。

**契约漂移守卫(tests/api/test_contract_drift.py,14 项)**:本项目开工审计已证明
「没有门禁的契约必然漂移」——四模块快照锁实际不存在,白名单 42/41 之误四份文档
一路不可见整整一个迭代。内部契约同样需要门禁。比对路径/方法/字段集/枚举/必填项,
**不比对字节**(永远不会相同,只会制造一个天天红然后被 skip 绕过的门禁)。

写这个守卫时它立刻抓到一处问题,但**问题在我的内省方式而不在应用**:本版本
FastAPI 的 include_router 会包一层内部 wrapper,路由并不平铺在 app.routes 上。
已改用 app.openapi()——它是「究竟暴露了什么」的权威视图,且不依赖框架内部结构,
否则这个门禁会在升级框架时莫名失效,而一个悄悄失效的门禁比没有门禁更糟。

**新增 pyproject.toml**:`Depends()` 放在参数默认值里正是 FastAPI 的标准写法,
ruff 的 B008 在此是误报。按 ruff 正规方式声明这些调用可安全求值,而不是在每个
端点上撒 noqa——后者迟早被用来压制真正的问题。

schemas 用 extra="forbid":拼错的字段应当立刻报错而非被静默忽略,后者表现为
「我传了 durationSec 却没生效」这类极难查的问题。测试覆盖了 camelCase 与
user_id(契约刻意不含它)两种被拒情形。

新增依赖 fastapi / uvicorn / pyjwt[crypto];测试 127 → 166。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 16:59:44 +08:00

122 lines
4.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""FastAPI 应用工厂。
装配顺序:读配置 → 建适配器注册表 → 挂路由与异常处理器。配置与注册表放在
`app.state` 上,请求处理时从 `request.app` 取——**不用模块级全局**,这样测试能起
多个配置不同的实例而互不干扰。
**异常处理器是本模块的重点**:契约定义了两类错误信封(`kind = service` /
`provider`),而 FastAPI 默认的校验错误是 `{"detail": [...]}`,与两者都不符。若不
接管,调用方就要处理三种形状——而第三种还是框架的实现细节。
"""
from __future__ import annotations
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.assembly import build_registry
from app.config import Settings
from .errors import ProviderError, ServiceError, ServiceErrorCode
from .routes import router
log = logging.getLogger(__name__)
def create_app(settings: Settings | None = None) -> FastAPI:
"""建应用。
:param settings: 省略即从环境变量读。测试传入显式配置以免依赖环境。
"""
resolved = settings or Settings.from_env()
logging.basicConfig(level=resolved.log_level)
app = FastAPI(
title="patbond-ai 内部接口",
version="0.1.0",
description=(
"patbond-creation(Java)调用本服务执行 AI 生成的内部契约。"
"权威契约见仓库根目录的 openapi-internal.yaml——"
"本服务自动生成的 /openapi.json 仅供调试,不是契约。"
),
# 内部服务不开交互文档:少一个对外表面,且契约以手写 yaml 为准。
docs_url=None,
redoc_url=None,
)
app.state.settings = resolved
app.state.registry = build_registry(resolved)
app.include_router(router)
_install_exception_handlers(app)
_install_health(app)
return app
def _install_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(ServiceError)
def handle_service_error(request: Request, exc: ServiceError) -> JSONResponse:
return JSONResponse(status_code=exc.code.http_status, content=exc.to_envelope())
@app.exception_handler(ProviderError)
def handle_provider_error(request: Request, exc: ProviderError) -> JSONResponse:
log.warning(
"服务商调用失败 code=%s retry=%s",
exc.failure.provider_code,
exc.failure.retry.value,
)
return JSONResponse(
status_code=ProviderError.HTTP_STATUS, content=exc.to_envelope()
)
@app.exception_handler(RequestValidationError)
def handle_validation_error(
request: Request, exc: RequestValidationError
) -> JSONResponse:
"""把 FastAPI 的校验错误翻成 service 信封。
默认形状是 `{"detail": [...]}`,与契约的两类信封都不符。不接管的话调用方
要处理三种形状,而第三种还是框架的实现细节——换个框架就变了。
"""
first = exc.errors()[0] if exc.errors() else {}
# 字段路径形如 ("body", "duration_sec"),去掉 "body" 前缀更可读。
location = ".".join(
str(part) for part in first.get("loc", ()) if part != "body"
)
detail = first.get("msg", "请求体不合契约")
message = f"{location}: {detail}" if location else detail
error = ServiceError(ServiceErrorCode.INVALID_REQUEST, message)
return JSONResponse(
status_code=error.code.http_status, content=error.to_envelope()
)
@app.exception_handler(Exception)
def handle_unexpected(request: Request, exc: Exception) -> JSONResponse:
"""兜底:本服务的 bug。
完整堆栈只进日志,绝不回给调用方——内部细节外泄没有任何好处。
"""
log.exception("未处理的异常")
error = ServiceError(ServiceErrorCode.INTERNAL_ERROR, "服务内部错误")
return JSONResponse(
status_code=error.code.http_status, content=error.to_envelope()
)
def _install_health(app: FastAPI) -> None:
@app.get("/health", include_in_schema=False)
def health() -> dict:
"""探活。**在 /internal 之外,故不需要服务票**——与 Java 侧各服务
`/health` 不挂鉴权的既有约定一致。
同时报出已装配的适配器:缺凭证时适配器不装配,而那个症状(任务永远排队)
离根因很远,让探活直接说出来能省很多排查时间。
"""
registry = app.state.registry
return {
"status": "ok",
"providers": sorted(registry.codes),
}