Skip to content

Key 与策略

LLM Fence 通过 MongoDB api_keys 集合管理业务 Key。当前版本应通过内置管理端或 /api/admin/keys API 创建和轮换 Key;服务端只保存 HMAC 哈希和脱敏展示值,不保存明文 client_key

Key 存储模型

业务 Key 文档包含:

字段说明
name业务 Key 名称
client_key_hash使用 LLM_FENCE_SECRET_KEY 计算的 HMAC-SHA256 哈希
client_key_masked脱敏展示值,例如 sk-****abcd
client_key_key_id生成哈希时使用的 LLM_FENCE_SECRET_KEY_ID
statusactivedisabled
scope_typesystemteampersonal
scope_idscope 对应 ID;system 为空
assigned_user_id分配用户 ID,仅作为管理信息
policy策略 JSON 对象

创建和轮换 Key 时,接口会返回一次 client_key 明文;之后只能看到 client_key_masked

策略字段

policy 是 schema-less JSON,当前处理器识别以下字段:

字段类型对应处理器说明
allowed_clientsstring[]client_guard限制可访问的客户端类型
allowed_modelsstring[]model_guard限制可调用的模型
allowed_ipsstring[]ip_guard限制可访问的 IP 或 CIDR 网段

空数组或未配置表示不限制。多个策略同时存在时,必须全部通过才放行。

客户端限制

json
{
  "allowed_clients": ["cc"]
}

可选值:

  • cc / cc-lenient
  • codex / codex-lenient
  • audit
  • unknown

模型限制

json
{
  "allowed_models": ["gpt-4o", "deepseek-chat"]
}

/v1/models 也生效:携带业务 Key 时只返回该 Key 允许的模型。

IP 限制

json
{
  "allowed_ips": ["1.2.3.4", "10.0.0.0/8", "2001:db8::/32"]
}

支持单 IP 和 CIDR,IPv4/IPv6 均可。

管理 API

方法路径说明
GET/api/admin/keysKey 分页列表
POST/api/admin/keys创建 Key,明文只返回一次
PATCH/api/admin/keys/{key_id}更新名称、状态、scope 和 policy
DELETE/api/admin/keys/{key_id}软删除 Key,同时置为 disabled
POST/api/admin/keys/{key_id}/rotate轮换 Key,明文只返回一次

创建 Key 示例:

json
{
  "name": "dev-team-key",
  "scope_type": "system",
  "scope_id": null,
  "assigned_user_id": null,
  "policy": {
    "allowed_models": ["gpt-4o"],
    "allowed_ips": ["10.0.0.0/8"]
  }
}

数据说明

  • 不要再手动写入明文 client_key 字段;当前认证逻辑查询的是 client_key_hashclient_key_key_id
  • 删除 Key 不影响历史请求日志和审计日志。
  • 历史日志中保留 Key 名称和 Key ID 快照,便于删除后继续查询。