Python 套件
aidy 包让 Python 宿主加入 aidy 目录:用 x-aidy 标注操作,校验 aidy 以用户身份调用时携带的 Aidy-Assertion,并实现身份与搜索契约。需要 Python 3.12 或更高版本。
pip install "aidy[fastapi]"使用教程见 FastAPI 指南。下文内容都可以从 aidy 导入,FastAPI 集成除外,它位于 aidy.fastapi。
def op( name: str, *, title: str | None = None, description: str | None = None, effect: Effect | None = None, approval: Approval | None = None, role: Role | None = None, surfaces: list[Surface] | None = None, confirmation: Confirmation | None = None, form: str | None = None, resolve: dict[str, Reference] | None = None, next: Next | None = None, open: str | None = None, redact: list[str] | None = None, repeatable: bool | None = None, timeout_seconds: float | None = None, cli: Cli | None = None,) -> dict[str, Any]返回给 FastAPI openapi_extra 使用的 {"x-aidy": {...}}。关键字参数就是 x-aidy 的键,采用 snake case:timeout_seconds 对应 timeoutSeconds。嵌套对象保持线上格式的 camelCase。值为 None 的参数会被省略,因此目录默认值生效。结果会按内置的 x-aidy schema 校验;有任何问题都会抛出 ValueError,并列出全部问题。
@app.post( "/api/vm/{vm_id}/stop", openapi_extra=op( "stop_vm", title="Stop server", open="/console/instance/{vm_id}", confirmation={ "title": "Stop server {resource_name}?", "lookup": {"path": "/api/vm/{vm_id}", "labelPath": "name"}, }, ),)| Literal 类型 | 取值 |
|---|---|
Effect |
"read"、"create"、"update"、"delete"、"external" |
Approval |
"never"、"always" |
Role |
"identity"、"search"、"form" |
Surface |
"agent"、"mcp"、"cli" |
Risk |
"low"、"medium"、"high" |
这些 Literal 类型位于 aidy.openapi。
op() 嵌套对象对应的 TypedDict:
| 类型 | 键 |
|---|---|
Confirmation |
title(必填)、target、fields: list[ConfirmationField]、lookup: Lookup、risk: Risk、costHint |
ConfirmationField |
key、label、values: dict[str, str](可选) |
Lookup |
path、labelPath |
Next |
op(必填)、arguments: dict[str, str]、argumentsFrom: str、when: dict[str, Any] |
Reference |
op、key(可选) |
Cli |
command(必填)、args: list[str] |
AidyHost
Section titled “AidyHost”from aidy.fastapi import AidyHost
AidyHost( app: FastAPI, *, keys: Mapping[str, Ed25519PublicKey], audience: str, identity: IdentityResolver, public_url: str | None = None, replay_cache: ReplayCache | None = None,)以 ASGI 中间件的形式在 app 上安装断言校验。没有 Aidy-Assertion 的请求原样放行。
| 参数 | 含义 |
|---|---|
keys |
按 kid 索引的固定 aidy 公钥,由 load_public_keys 得到。 |
audience |
宿主的 origin(https://console.example.com),即断言的 aud。 |
identity |
(request) -> (subject, tenant | None) | None,同步或异步均可,按 UI 完全相同的方式从请求自身的凭据解析用户。返回 None 表示请求不对应任何用户。它抛出的 HTTPException 会原样返回。 |
public_url |
客户端访问时的基础地址,与原始路径和查询串拼接,重建断言绑定的 URL。默认等于 audience。代理去掉了路径前缀时需要设置(https://console.example.com/gw)。 |
replay_cache |
保存已见 jti 的位置。默认 MemoryReplayCache(),仅限单进程。 |
遇到断言时,中间件会缓冲请求体并依次检查:
- 用固定公钥(
kid)验证 EdDSA 签名,以及声明的结构; - 有效期 ≤ 60 s,
exp/iat偏差不超过 60 s,aud == audience; htm、htu(发送时的完整 URL,含查询串)和bsh(请求体原始字节的 SHA-256);jti未出现过;sub/ten与identity(request)一致,op与路由器实际分派到的路由的x-aidy.name(取自app.openapi())一致,操作需要审批时(取其approval,否则读操作为never、其余为always)带有apr。
失败时返回:
{ "detail": "aidy_assertion_invalid", "code": "approval_missing" }状态码为 401,code 见 失败码。成功时声明保存在 request.state.aidy。
AidyCall
Section titled “AidyCall”from aidy.fastapi import AidyCall
async def stop_vm(vm_id: str, aidy: AidyCall) -> dict[str, str]: if aidy is not None: audit(actor="aidy", run=aidy.rid, approval=aidy.apr)AidyCall 即 Annotated[AssertionClaims | None, Depends(...)]:委托调用时为校验过的声明,用户直接调用时为 None。
AssertionClaims
Section titled “AssertionClaims”断言声明的不可变 pydantic 模型(见 委托):
| 字段 | 类型 |
|---|---|
iss、aud、htu |
str(URL) |
sub、sid、rid、cid |
str |
ten、apr |
str | None |
op |
str |
htm |
"GET"、"HEAD"、"POST"、"PUT"、"PATCH" 或 "DELETE" |
bsh、jti |
str |
iat、exp |
int |
claims.audit() 返回去掉缺省字段的普通 dict,便于写入审计记录。宿主应记录 actor = aidy、rid 和 apr。
ReplayCache 与 MemoryReplayCache
Section titled “ReplayCache 与 MemoryReplayCache”ReplayCache 是一个协议,签名与 redis-py 的 set 相同:
def set(self, key: str, value: str, *, nx: bool, ex: int) -> object: ...nx=True 时,只有键是新的才会保存 ex 秒,并返回真值。同步或异步均可,因此 redis.Redis 和 redis.asyncio.Redis 都适用。键为 aidy:jti:<jti>,保留到该断言不可能再被接受为止。
MemoryReplayCache() 是单进程实现。有多个 worker 时,请传入共享存储:
from redis.asyncio import Redis
AidyHost(app, ..., replay_cache=Redis.from_url("redis://cache:6379/0"))不使用 FastAPI
Section titled “不使用 FastAPI”verify_assertion
Section titled “verify_assertion”def verify_assertion( token: str, *, keys: Mapping[str, Ed25519PublicKey], audience: str, method: str, url: str, body: bytes | str, remember: Callable[[str, int], bool], now: int | None = None,) -> AssertionClaims校验签名、有效期、audience、请求绑定和重放(宿主校验的第 1 至 3 条)。url 是客户端发送时的完整 URL,含查询串;body 是请求体原始字节(没有请求体时为空)。remember(jti, until) 记录 jti 直到 epoch 秒 until,已出现过时返回 False。失败时抛出 AidyAssertionError。
verify_signed(...) 参数相同但没有 remember,跳过重放检查,适合重放存储为异步的调用方。
check_call
Section titled “check_call”def check_call( claims: AssertionClaims, *, subject: str, tenant: str | None, op: str, approval: Literal["never", "always"],) -> None第 4 至 6 条检查:断言指向宿主解析出的用户和所服务的操作,并在 approval 为 "always" 时带有 apr。失败时抛出 AidyAssertionError。
from aidy import check_call, verify_assertion
claims = verify_assertion( token, keys=keys, audience="https://console.example.com", method="POST", url=full_url_as_sent, body=raw_body, remember=lambda jti, until: cache.add(jti, until), # False when seen before)check_call(claims, subject=user.id, tenant=user.tenant_id, op="stop_vm", approval="always")load_public_keys
Section titled “load_public_keys”def load_public_keys(jwks: Iterable[Mapping[str, str]]) -> dict[str, Ed25519PublicKey]从 Ed25519 JWK({"kty": "OKP", "crv": "Ed25519", "x": …, "kid": …},即 aidy keys generate 打印的格式)得到按 kid 索引的公钥。JWK 缺少 kid、类型不对或长度不对时抛出 ValueError。
args_hash 与 canonical_json
Section titled “args_hash 与 canonical_json”def canonical_json(value: object) -> strdef args_hash(args: Mapping[str, object]) -> strcanonical_json 实现 JSON 规范化方案(JCS,RFC 8785):键排序,数字和字符串采用 ECMAScript 的形式。args_hash 是冻结参数规范化 JSON 的 base64url SHA-256,即审批所绑定的哈希。两者的输出与 @aidy-dev/spec 完全一致。
AidyAssertionError
Section titled “AidyAssertionError”一个 Exception,带有 code: AssertionErrorCode,即失败的检查项名称。
| 代码 | 检查项 |
|---|---|
malformed |
不是 compact JWS、header 不对或声明无效。 |
unknown_key |
没有与 kid 对应的固定公钥。 |
bad_signature |
签名验证失败。 |
expired |
exp 已过,超出 60 s 偏差。 |
not_yet_valid |
iat 比当前时间晚 60 s 以上。 |
too_long |
exp - iat 超过 60 s。 |
audience |
aud 不是宿主的 origin。 |
method |
htm 不匹配。 |
url |
htu 不匹配。 |
body |
bsh 不匹配。 |
replay |
jti 已出现过。 |
subject |
sub 不是解析出的用户,或请求不对应任何用户。 |
tenant |
ten 不是解析出的租户。 |
operation |
op 不是处理该请求的操作,或没有目录操作处理该请求。 |
approval_missing |
操作需要审批,但缺少 apr。 |
Identity
Section titled “Identity”class Identity(BaseModel): subject: str tenant: str | None = None name: str | None = None locale: str | None = None scopes: list[str] | None = Nonerole: identity 操作的返回值。序列化时省略缺省字段。ADMIN_SCOPE 为 "aidy:admin"。见 身份。
@app.get("/api/me", openapi_extra=op("whoami", role="identity"))async def whoami(request: Request) -> Identity: user = current_user(request) return Identity(subject=user.id, tenant=user.tenant_id, locale="zh-CN")SearchHit 与 SearchResponse
Section titled “SearchHit 与 SearchResponse”class SearchHit(BaseModel): type: str # ^[a-z][a-z0-9_.-]{0,31}$ id: str title: str excerpt: str | None = None # at most 300 characters url: str # a path starting with one "/", or http(s):// updated_at: AwareDatetime | None = None content: str | None = None # at most 4000 characters, for the model only
class SearchResponse(BaseModel): hits: list[SearchHit] # at most 50SearchHit 序列化为线上格式的 camelCase(updatedAt),两种写法都能接受。未知字段会被拒绝。content 是给模型读的正文段落:aidy 的 search 工具把它交给模型,并从 /aidy/v0/search 的响应和引用中去掉它,所以人看到的是 title、excerpt 和 url。
Form、SearchHit、SearchResponse 和 Identity 序列化为 camelCase,并省略缺失的字段(aidy 运行时拒绝 null),在 model_dump、model_dump_json 和 FastAPI 响应中都是如此,不需要 response_model_exclude_none。FastAPI 的 OpenAPI 文档会显示它们真实的 camelCase schema。DEFAULT_SEARCH_LIMIT 为 10,MAX_SEARCH_LIMIT 为 50。见 搜索。
@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))async def search_vms(q: str, limit: int = 10) -> SearchResponse: return SearchResponse( hits=[ SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}") for vm in find_vms(q, limit) ] )| 名称 | 值 |
|---|---|
ASSERTION_HEADER |
"aidy-assertion" |
ADMIN_SCOPE |
"aidy:admin" |
DEFAULT_SEARCH_LIMIT |
10 |
MAX_SEARCH_LIMIT |
50 |
aidy.fastapi.INVALID |
"aidy_assertion_invalid" |