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 |
status | active 或 disabled |
scope_type | system、team 或 personal |
scope_id | scope 对应 ID;system 为空 |
assigned_user_id | 分配用户 ID,仅作为管理信息 |
policy | 策略 JSON 对象 |
创建和轮换 Key 时,接口会返回一次 client_key 明文;之后只能看到 client_key_masked。
策略字段
policy 是 schema-less JSON,当前处理器识别以下字段:
| 字段 | 类型 | 对应处理器 | 说明 |
|---|---|---|---|
allowed_clients | string[] | client_guard | 限制可访问的客户端类型 |
allowed_models | string[] | model_guard | 限制可调用的模型 |
allowed_ips | string[] | ip_guard | 限制可访问的 IP 或 CIDR 网段 |
空数组或未配置表示不限制。多个策略同时存在时,必须全部通过才放行。
客户端限制
json
{
"allowed_clients": ["cc"]
}可选值:
cc/cc-lenientcodex/codex-lenientauditunknown
模型限制
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/keys | Key 分页列表 |
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_hash和client_key_key_id。 - 删除 Key 不影响历史请求日志和审计日志。
- 历史日志中保留 Key 名称和 Key ID 快照,便于删除后继续查询。