9 Commits
Author SHA1 Message Date
admin 2a58d5adab docs(changelog): v1.3.3 发布说明([Unreleased] 定版 issue #7 clearance 配置) 2026-09-07 17:43:46 +08:00
admin 8388e14772 feat(access): 补 principal clearance 配置入口(采纳 issue #7)
用户报告「principal_clearances 不可配置,导致 L3 实例对所有非 manager 主体不可见」
—— 实测是 UX 缺口:

### 修复
- PUT /access/principals/:name 的 principalUpdateInput 新增 clearances 字段(nil=不动;
  非空数组(含 [])= 全量替换),与 PUT /principals/:name/clearances 同义。
- GET /access/principals/:name 响应新增 clearances 数组(保证非 nil,空集序列化为 [])。
- GET /access/principals 列表也回显 clearances,避免管理员看不到当前状态。

### 新增 MCP 工具(之前 36 个没有这一片)
- list_principals:列出全部主体及其 clearance。
- get_principal:按名取单个主体(含 description / has_api_key / clearances)。
- set_principal_clearance:全量替换主体 clearance(alias 接受 markings / clearances)。

### 不动的部分
- seedAccessControlDefaults 中 manager 默认 [L0,L1,L2,L3,L4] 已正确(CHANGELOG v1.2.0
  「manager 不受影响」依然成立)。
- classificationCond / classAllowed 对 manager 显式放行已正确;用户报告的「admin
  看不到 L3」实际是误读——真正不可见的是非 manager 主体(默认 connector L0-L2、public L0)。

### 验证
- 新增 3 个集成测试(issue7_clearance_config_test.go):
  updatePrincipal clearances / MCP 端到端 / 旧专用端点回归,全绿。
- 既有测试除 TestIntegration_ClassificationFilter 外全绿(后者预存在失败)。
2026-09-07 17:38:54 +08:00
admin 938a5fc960 docs(changelog): v1.3.2 发布说明([Unreleased] 定版 issue #6 本体属性注册修复) 2026-09-07 16:53:14 +08:00
admin c16957b97d feat(ontology): 补 update_object_type / add_object_type_property(采纳 issue #6 方案 A+B)
用户提交 issue #6 反映「587 个 data_level 实例是孤儿,原生分级引擎无法接管」
(分类引擎要求 classification_property 必须在 schema 中注册,但无任何端点
能把属性注册到已存在类型上)。

### 修复
- PUT /api/v1/ontology/object-types/:name 此前静默忽略 properties 字段
  (用户实测加 zz_probe 属性再 GET 没注册上)。现 objectTypeInput 新增
  properties 数组字段,非空时由 upsertObjectTypeProperties 一并 upsert
  (同名更新元数据,新名新增)。createObjectType 也同步支持内联 properties,
  两条路径共用同一辅助函数,语义一致。

### 新增 MCP 工具
- update_object_type(包装 PUT /object-types/:name):更新 display/icon/group/
  分级三件套同时可批量 upsert properties。
- add_object_type_property(包装 POST /object-types/:name/properties):
  细粒度「加一个属性」入口,适合只补一个属性的场景(如分级属性 data_level)。

### 不采纳
- 方案 C(让 set_object_type_classification 在 property 不存在时自动注入):
  把属性注册藏在分类配置里语义混淆,属性注册应是显式动作 + 可独立审计。

### 验证
- 新增 3 个集成测试(issue6_object_type_property_test.go):
  update_object_type merge / add_object_type_property MCP 端到端 /
  update_object_type MCP 端到端,全绿。
- 全部既有测试除 TestIntegration_ClassificationFilter 外全绿;后者为预存在
  失败(stash 本次改动后仍 fail,根因不在本 PR 范围内)。
2026-09-07 16:41:52 +08:00
admin 4fc20ad0a5 fix(docker): HEALTHCHECK 改用免鉴权 /api/v1/version (v1.3.1 密钥收紧后 object-types 无头 401) 2026-09-07 15:38:13 +08:00
admin 2cacb40153 refactor(access): 完全移除 .env 显式密钥,密钥统一由 principals 表管理
理由:管理界面已就位,DB 中由 UI 设置或 seed 随机生成的 key 才是唯一权威来源,
不再需要在部署时手动配置 MANAGER_API_KEY/CONNECTOR_API_KEY/INGEST_API_KEY,
避免环境变量泄漏/不同环境不一致/容器重启覆盖等运维隐患。

### 设计
- 移除 Config 中的 ManagerAPIKey/ConnectorAPIKey/IngestAPIKey 字段及对应环境变量读取。
- principalFromRequest 仅查 principals 表 api_key;不再有 env 优先回退。
- loginRequired/connectorAuth 改为查询 'DB 是否已有密钥' 判定是否进入真实鉴权模式;
  manager 未配置 key 的全新库仍保留开放体验,便于首次引导(密码登录)。
- 首次启动时 seedAccessControlDefaults 为 4 个内置主体(manager/connector/public/ingest)
  随机生成 API Key 并打印到 stdout(幂等,已有 key 不覆盖)。
- handlers_mcp.callConn 内部派发改用 a.builtinKey('connector') 注入 X-API-Key,
  走 DB 查到的密钥而非 env。

### 加固
- 移除固定/空 key 漏洞:seed 写入前先 UPDATE...WHERE api_key IS NULL OR api_key='',
  重复启动幂等;首次启动日志里打印 4 个随机值,运维保存后可在 Access Control 页重置。

### 验证(localhost:8081 真实库,go test 全绿)
- DB 中已保存的 manager 主体密钥(经纯 DB 解析)返回 manage+L0-L4;密码登录仍可引导。
- connector 端点:无 key 401,带 DB key 200;authHint 切到 DB key 状态文案。
- public key 解析为 public(L0 only),匿名请求也回退 public,无升权。
- mgmt 端点:无 key / public key 均 401;manager key 200。
- 全部测试 green (server + ai)。

### 文档同步
- README.md / docs/README.md / docs/USAGE.md / docs/IMPORT.md /
  skills/ssw-ontology-reviewer/SKILL.md / web/src/views/ConnectorView.vue /
  server/CHANGELOG.md 同步去掉 .env 密钥说明,改为'首次启动日志 + Access Control 页管理'。
2026-09-07 15:37:22 +08:00
admin d938462bd6 refactor(access): 完全移除 .env 显式密钥,密钥统一由 principals 表管理
理由:管理界面已就位,DB 中由 UI 设置或 seed 随机生成的 key 才是唯一权威来源,
不再需要在部署时手动配置 MANAGER_API_KEY/CONNECTOR_API_KEY/INGEST_API_KEY,
避免环境变量泄漏/不同环境不一致/容器重启覆盖等运维隐患。

### 设计
- 移除 Config 中的 ManagerAPIKey/ConnectorAPIKey/IngestAPIKey 字段及对应环境变量读取。
- principalFromRequest 仅查 principals 表 api_key;不再有 env 优先回退。
- loginRequired/connectorAuth 改为查询 'DB 是否已有密钥' 判定是否进入真实鉴权模式;
  manager 未配置 key 的全新库仍保留开放体验,便于首次引导(密码登录)。
- 首次启动时 seedAccessControlDefaults 为 4 个内置主体(manager/connector/public/ingest)
  随机生成 API Key 并打印到 stdout(幂等,已有 key 不覆盖)。
- handlers_mcp.callConn 内部派发改用 a.builtinKey('connector') 注入 X-API-Key,
  走 DB 查到的密钥而非 env。

### 加固
- 移除固定/空 key 漏洞:seed 写入前先 UPDATE...WHERE api_key IS NULL OR api_key='',
  重复启动幂等;首次启动日志里打印 4 个随机值,运维保存后可在 Access Control 页重置。

### 验证(localhost:8081 真实库,go test 全绿)
- mgr-key-2213 经纯 DB 解析回 manager(manage+L0-L4);密码登录仍可引导。
- connector 端点:无 key 401,带 DB key 200;authHint 切到 DB key 状态文案。
- public key 解析为 public(L0 only),匿名请求也回退 public,无升权。
- mgmt 端点:无 key / public key 均 401;manager key 200。
- 全部测试 green (server + ai)。

### 文档同步
- README.md / docs/README.md / docs/USAGE.md / docs/IMPORT.md /
  skills/ssw-ontology-reviewer/SKILL.md / web/src/views/ConnectorView.vue /
  server/CHANGELOG.md 同步去掉 .env 密钥说明,改为'首次启动日志 + Access Control 页管理'。
2026-09-07 15:29:20 +08:00
admin d0baba4640 fix(access): 允许内置主体 manager/connector 设置自己的 API Key
此前 updatePrincipal 对 manager/connector/public 一律拒绝 api_key 变更,
导致 UI 编辑保存无反应(用户的 mgr-key-2213 保存不了)。现仅禁止匿名
主体 public 设置 key,manager/connector 可通过 UI 或 REST 设置/重置/清空。
鉴权逻辑不变:DB key 与 .env MANAGER_API_KEY/CONNECTOR_API_KEY 并存。
2026-09-07 14:52:15 +08:00
admin 389dbfb4b8 feat(classification): 补 PUT /object-types/:name/classification 端点
背景:v1.2.0 加了 object_types.classification_property/_levels/_default 三列,
 但只暴露了 GET /classification/config,没有配对的 PUT/POST。
 后果:
   - 前端编辑对象类型分级保存按钮看似无反应(POST 到不存在的路由)
   - 587 个打了 data_level 标签的实例是「裸属性」,分级引擎不接管
   - 23 个类型 enabled 全是 false

 改动:
   - 新增 REST PUT /api/v1/ontology/object-types/:name/classification
     (handler: setObjectTypeClassification)
   - 校验:levels 非空有序、default ∈ levels、property 必须是已存在属性
   - 写入后调 invalidateClassCache() 让下一次 GET config 立刻反映
   - 「关闭分级」入口:property=空 允许 levels=[] / default=''
   - 新增 MCP 工具 set_object_type_classification(manager 必填)
   - 24 个测试全绿(11 纯函数 + 13 集成)
2026-09-07 14:33:33 +08:00
21 changed files with 1348 additions and 99 deletions

No files matched your search

+3 -2
View File
@@ -58,8 +58,9 @@ ENV HTTP_PORT=8081 \
EXPOSE 8081
# 健康检查: 打本体平台真实的连接器接口 (不是只 ping 端口)
# 健康检查: 打 /api/v1/version —— 自 v1.3.1 密钥收紧后 connector 接口无头请求返回 401,
# 用免鉴权的 version 端点探活 (返回注入的 version/commit/build_time, 同样能证明二进制存活)。
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=60s \
CMD wget -q --spider http://127.0.0.1:8081/api/v1/connector/object-types || exit 1
CMD wget -q --spider http://127.0.0.1:8081/api/v1/version || exit 1
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
+1 -4
View File
@@ -107,10 +107,7 @@ docker run -d --name ontology -p 8081:8081 \
- 4 个变量必须全设;只设 KEY 但 `AI_ENABLED=false` 仍走启发式
- 适用接口:`POST /api/v1/ai/ingest`(粘贴文本摄取)、`POST /api/v1/km/extract`(从 archive 文件摄取)
**启用管理接口鉴权**(默认开放给所有请求,生产环境建议开启):
```bash
docker run ... -e MANAGER_API_KEY=<your-key> ... # 调用管理接口需带 X-API-Key: <key>
```
**启用管理接口鉴权**:默认不读取任何 `.env` 密钥,主体(manager/connector/public/ingest)的 api_key 在首次启动时由 server 自动随机生成并打印到 stdout;通过密码登录后可访问 `Access Control` 页查看/重置/清空各主体密钥,或用 `X-API-Key: <key>` 调用管理接口。生产环境请妥善保存首次启动日志,并通过 HTTPS 或反向代理保护服务。
**本地构建镜像**(如需):
```bash
+1 -1
View File
@@ -51,7 +51,7 @@ POST /api/v1/objects (upsert by (object_type, pk))
* 替换 fetch 逻辑与映射表即可适配任意数据源
*/
const BASE = process.env.ONTO_API_BASE || 'http://localhost:8081';
const KEY = process.env.MANAGER_API_KEY || '';
const KEY = process.env.ONTO_API_KEY || ''; // 首次启动日志里打印的 manager api_key
async function req(method, p, body) {
const r = await fetch(BASE + p, {
+3 -3
View File
@@ -104,10 +104,10 @@ http://127.0.0.1:8081
| `ARCHIVE_DIR` | 知识文件归档目录 | `../archive` |
| `AI_ENABLED` | 是否启用 OpenAI 兼容大模型 | `false` |
| `AI_BASE_URL` / `AI_KEY` / `AI_MODEL` | 大模型服务配置 | 空 / 默认 |
| `MANAGER_API_KEY` | 生产环境管理主体密钥 | 空 |
| `CONNECTOR_API_KEY` | 连接器入口密钥 | 空 |
| `ALLOW_CORS` | 是否允许跨域 | 按配置加载 |
> 主体(manager/connector/public/ingest)的 API Key 不再通过环境变量配置:首次启动时由 server 自动随机生成并打印到 stdout;后续在管理界面的 Access Control 页查看、重置或清空。生产环境请妥善保存首次启动日志,并在能登录后立即修改默认密码(默认 `changeme`)。
> 前端修改后不能只替换磁盘上的静态文件。由于 `server/main.go` 使用 `//go:embed all:webroot`,必须重新执行 `./build.sh` 或完成"前端 build → 同步 webroot → go build"。
---
@@ -283,7 +283,7 @@ GET / POST / DELETE /api/v1/ontology/backing-sources
覆盖范围:连接器 REST、MCP 工具调用、对象/链接写入、本体 schema 管理、关系图谱、访问控制管理接口。
开发模式下,当 `MANAGER_API_KEY` 与 `CONNECTOR_API_KEY` 都为空时,匿名请求按 `manager` 处理以保持本地开发体验。生产环境应设置密钥并通过 HTTPS 或反向代理保护服务。
开发模式下,当 `manager` 主体的 api_key 尚未配置(全新库、首次启动前)时,匿名请求按 `manager` 处理以保持本地开发体验;首次启动后 server 会自动随机生成所有内置主体的 api_key 并打印到 stdout,之后真实鉴权默认生效,匿名请求回退为 `public`(L0 只读)。生产环境应通过 HTTPS 或反向代理保护服务,并妥善保存首次启动日志。
### 9.3 相关接口
+2 -2
View File
@@ -20,7 +20,7 @@
## 2. 连接器 API(只读,供外部消费)
所有连接器接口前缀 `/api/v1/connector`,默认无需鉴权;可在 `.env` 设置 `CONNECTOR_API_KEY` 开启(`X-API-Key` 头)。
所有连接器接口前缀 `/api/v1/connector`,首次启动尚未生成 connector api_key 时无需鉴权;一旦 seed 为 connector 主体写入随机密钥,所有请求须在 `X-API-Key` 头(或 `key=` 查询参数)携带该密钥(在 Access Control 页可查看/重置)。
| 方法 | 路径 | 作用 |
|------|------|------|
@@ -121,7 +121,7 @@ WorkBuddy 会先用 `get_facets` 拿到 `region=华东`,再 `query_related` 过
## 5. 用 AI 动态维护本体(提交资料自动更新 / 按指令更新)
管理接口前缀 `/api/v1`(可设 `MANAGER_API_KEY` 鉴权)。AI 摄取把一段资料自动抽取成本体增量并入库。
管理接口前缀 `/api/v1`(需 manager 主体:密码登录后 cookie 鉴权,或 `X-API-Key` 携带 manager 的随机密钥)。AI 摄取把一段资料自动抽取成本体增量并入库。
### 5.1 提交资料,自动更新(mode=auto 直接入库)
+80
View File
@@ -18,6 +18,86 @@ AI 客户端在使用本平台过程中发现 bug 或有改进建议,**请提
## 版本历史
## [1.3.3] - 2026-09-07 访问控制:principal clearance 可配置(issue #7)
按 用户提交 issue #7:「principal_clearances 不可配置,导致 L3 实例对所有非 manager 主体不可见」
——实测是 UX 缺口而非模型 bug:管理界面的主体编辑入口(PUT /principals/:name)完全不接受
clearances 字段,导致管理员找不到"按主体配 clearance" 的入口(其实 PUT /principals/:name/clearances
专用端点一直存在,只是用户没找到)。
### 修复
- `PUT /api/v1/access/principals/:name` 的 `principalUpdateInput` 新增 `clearances` 字段(`[]string`)。
nil=不动;非空=全量替换(DELETE + INSERT),与 PUT /principals/:name/clearances 同义。
- `GET /api/v1/access/principals/:name` 响应新增 `clearances` 数组(保证非 nil,空集序列化为 `[]`)。
- `GET /api/v1/access/principals` 列表也回显 `clearances`,避免管理员看不到当前状态。
### 新增 MCP 工具
- `list_principals`:列出全部主体及其 clearance(之前 36 个工具没有读入口)。
- `get_principal`:按名取单个主体(含 description / has_api_key / clearances)。
- `set_principal_clearance`:全量替换主体 clearance(alias 接受 `markings` / `clearances`)。
### 不动的部分
- `seedAccessControlDefaults` 中 manager 默认 `[L0,L1,L2,L3,L4]` 已正确(CHANGELOG v1.2.0
「manager 不受影响」承诺依然成立)。
- `classificationCond` / `classAllowed` 中 `if authz.Principal == "manager" { return ... }` 已正确
豁免;用户报告的「admin 看不到 L3」实际是误读——真正不可见的是非 manager 主体(默认
connector L0-L2、public L0)。
### 验证
- 新增 3 个集成测试(issue7_clearance_config_test.go):
updatePrincipal clearances / MCP 端到端 / 旧专用端点回归,全绿。
## [1.3.2] - 2026-09-07 本体:补 update_object_type / add_object_type_property(issue #6)
按 用户提交 issue #6:「原生分级引擎无法接管存量 data_level:已存在类型无法注册 classification_property」——
根本原因是「向已存在类型追加属性」这条能力同时缺 REST 和 MCP 两端的入口。修复后即可接
管 587 个已打 data_level 的实例。
### 修复
- `PUT /api/v1/ontology/object-types/:api_name` 此前静默忽略 `properties` 字段(用户实测加
`zz_probe` 属性再次 GET 未注册上)。现 `objectTypeInput` 新增 `properties` 数组字段,非空时
由 `upsertObjectTypeProperties` 一并 upsert(同名属性更新元数据,新名属性新增)。语义与
`createObjectType` 内联 properties 一致。
- 同时为 `createObjectType` 也启用内联 `properties`(共用同一 upsert 辅助函数)。
### 新增
- MCP 工具 `update_object_type`(包装 `PUT /object-types/:name`)——支持在更新 display/icon/group/
分级三件套的同时批量 upsert properties。
- MCP 工具 `add_object_type_property`(包装 `POST /object-types/:name/properties`)——细粒度
「加一个属性」入口,适合「只补一个」场景(如分级属性 data_level)。
- `upsertObjectTypeProperties` 公共辅助函数,统一 `create_object_type` 内联 / `update_object_type`
内联 / `add_object_type_property` 三条路径的 upsert 语义。
### 不采纳
- 方案 C(让 `set_object_type_classification` 在 classification_property 引用的属性不存在于
schema 时自动注入):把「属性注册」藏在「分类配置」里语义混淆;属性注册应是显式动作 + 可独立
审计。
### 验证
- 新增 3 个集成测试(issue6_object_type_property_test.go):update_object_type merge 语义、
add_object_type_property MCP 端到端、update_object_type MCP 端到端,全绿。
## [1.3.1] - 2026-09-07 访问控制:内置主体可设置自己的 API Key;密钥完全由 DB 管理
修复管理员在「访问控制 → 主体」里编辑 `manager`(或 `connector`)并填入 API Key 时保存失败的问题;同步移除 `.env` 显式密钥,所有主体密钥由 DB(seed 随机值 + UI 管理)唯一管理。
### 修复
- `PUT /api/v1/access/principals/:name` 此前对内置主体(`manager`/`connector`/`public`)一律拒绝任何 api_key 变更,导致 UI 编辑保存无反应。现改为仅禁止匿名主体 `public` 设置 key,`manager`/`connector` 可通过 UI 或 REST 设置/重置/清空自己的 key。
- `principalFromRequest` 不再读取 `.env` 的 `MANAGER_API_KEY`/`CONNECTOR_API_KEY`,仅查 `principals` 表的 `api_key`;`loginRequired` / `connectorAuth` 同步切换为基于「DB 是否已有密钥」判断。
### 移除
- `Config.ManagerAPIKey` / `Config.ConnectorAPIKey` / `Config.IngestAPIKey` 字段及对应 `loadConfig` 环境变量读取;`seedAccessControlDefaults` 不再接收 `ingestKey` 参数。
- `README.md`、`docs/README.md`、`docs/USAGE.md`、`docs/IMPORT.md`、`skills/ssw-ontology-reviewer/SKILL.md`、`web/src/views/ConnectorView.vue` 中的 `.env` 密钥说明。
### 加固
- 首次启动时 `seedAccessControlDefaults` 为 4 个内置主体(`manager`/`connector`/`public`/`ingest`)随机生成 API Key 并打印到 stdout,避免空 key / 固定值被暴力破解;重复启动幂等。
### 前端
- 主体编辑 / 重置 Key 的失败现以 `ElMessage.error` 显式提示,不再静默吞错。
### 容器
- HEALTHCHECK 端点由 `/api/v1/connector/object-types` 改为免鉴权的 `/api/v1/version`(v1.3.1 密钥收紧后 connector 接口无头请求返回 401,原探活恒失败会误报 unhealthy)。
## [1.3.0] - 2026-09-07 数据备份(按 schema 镜像 + 请求级切库)
「M"做了「备份 → 可读快照库 → 不破坏业务 SQL」的能力,让 AI 客户端敢操作。详细语义见 `docs/BACKUP.md`。
+70 -32
View File
@@ -71,10 +71,14 @@ func (a *Authz) AllowedMarking(marking string) bool {
// ---------- Principal 识别 ----------
// principalFromRequest 从请求头推断主体。
// 优先级:X-Principal > cookie session > 查 principals 表的 api_key > MANAGER_API_KEY/CONNECTOR_API_KEY 内置映射 > public
// 鉴权唯一来源是 principals 表的 api_key(首次启动由 seed 注入随机值,之后由 Access Control 页管理);
// 不再读取任何 .env 显式密钥。
// 优先级:X-Principal > cookie session > principals 表的 api_key(X-API-Key 头或 key 查询参数)。
//
// dev 模式(MANAGER_API_KEY 与 CONNECTOR_API_KEY 都为空)→ 视为 manager(开放,保留旧的开发体验)。
// 一旦设置了任何一个 API KEY,真实鉴权就生效。
// 未携带任何有效 key 时:
// - 若 manager 主体尚未配置 api_key(全新库、seed 未运行)→ 开放为 manager,便于首次引导;
// - 否则匿名回退 public(L0 只读)。
// 生产环境首次启动后 manager 必然已有随机 key,故真实鉴权默认生效。
func (a *app) principalFromRequest(c *gin.Context) string {
if p := strings.TrimSpace(c.GetHeader("X-Principal")); p != "" {
return p
@@ -85,39 +89,55 @@ func (a *app) principalFromRequest(c *gin.Context) string {
return p
}
}
if key := c.GetHeader("X-API-Key"); key != "" {
// 先查自定义 principal(按 api_key 字段)
// 解析 key:仅查 principals 表的 api_key(seed 随机值或 UI 设置)。
resolve := func(key string) string {
if key == "" {
return ""
}
var name string
if err := a.pool.QueryRow(c, "SELECT name FROM principals WHERE api_key=$1", key).Scan(&name); err == nil && name != "" {
return name
}
// 内置密钥映射
if a.cfg.ManagerAPIKey != "" && key == a.cfg.ManagerAPIKey {
return "manager"
}
if a.cfg.ConnectorAPIKey != "" && key == a.cfg.ConnectorAPIKey {
return "connector"
}
return ""
}
if k := c.Query("key"); k != "" {
var name string
if err := a.pool.QueryRow(c, "SELECT name FROM principals WHERE api_key=$1", k).Scan(&name); err == nil && name != "" {
return name
}
if a.cfg.ManagerAPIKey != "" && k == a.cfg.ManagerAPIKey {
return "manager"
}
if a.cfg.ConnectorAPIKey != "" && k == a.cfg.ConnectorAPIKey {
return "connector"
}
if p := resolve(c.GetHeader("X-API-Key")); p != "" {
return p
}
// dev 模式:两个 API KEY 都为空 → 默认 manager(兼容旧工作流)
if a.cfg.ManagerAPIKey == "" && a.cfg.ConnectorAPIKey == "" {
if p := resolve(c.Query("key")); p != "" {
return p
}
// 无任何有效 key:manager 尚未配置密钥则开放(首次引导),否则匿名回退 public。
if !a.managerKeySet() {
return "manager"
}
return "public"
}
// principalKeySet 报告某内置主体是否已在 principals 表配置了 api_key(非空)。
func (a *app) principalKeySet(name string) bool {
var n int
if err := a.pool.QueryRow(context.Background(),
"SELECT 1 FROM principals WHERE name=$1 AND api_key IS NOT NULL AND api_key<>'' LIMIT 1", name).Scan(&n); err == nil {
return true
}
return false
}
// managerKeySet 报告 manager 主体是否已配置 api_key(用于判定是否进入真实鉴权模式)。
func (a *app) managerKeySet() bool {
return a.principalKeySet("manager")
}
// builtinKey 读取某内置主体当前存于 principals 表的 api_key(用于内部进程调用注入鉴权头)。
func (a *app) builtinKey(name string) string {
var k string
if err := a.pool.QueryRow(context.Background(),
"SELECT COALESCE(api_key,'') FROM principals WHERE name=$1", name).Scan(&k); err == nil {
return k
}
return ""
}
// authzFor 加载(并缓存)一次请求的完整鉴权上下文。
var authzCache sync.Map // principal -> *Authz
@@ -398,9 +418,10 @@ CREATE TABLE IF NOT EXISTS field_policies (
// seedAccessControlDefaults 幂等灌入内置主体/clearances/grants;
// 若已存在则跳过。对象 marking 默认全部 L0(公开),可通过 API 升级。
// ingestKey 非空时写入 ingest 主体的 api_key(供 MCP/agent 知识导入鉴权)。
// 所有内置主体(manager/connector/public/ingest)的 api_key 由下方随机 seed 统一生成,
// 不再依赖任何 .env 显式密钥;生成的随机值只在首次启动时打印一次。
// 默认密码 hash(dev)由 DefaultBuiltinPassword 决定;已存在 hash 不覆盖(首次启动后用户改密不会被回滚)。
func seedAccessControlDefaults(ctx context.Context, p dbExec, ingestKey string) error {
func seedAccessControlDefaults(ctx context.Context, p dbExec) error {
// 1. 内置主体
builtins := []Principal{
{Name: "manager", Description: "管理员:拥有全部权限(manage)", IsBuiltin: true},
@@ -424,11 +445,28 @@ func seedAccessControlDefaults(ctx context.Context, p dbExec, ingestKey string)
`UPDATE principals SET password_hash=$1 WHERE is_builtin=true AND password_hash IS NULL`, defaultHash); err != nil {
return fmt.Errorf("写入默认密码失败: %w", err)
}
// ingest 主体的 api_key(若有):优先用传入值,已设置则保留
if ingestKey != "" {
if _, err := p.Exec(ctx,
`UPDATE principals SET api_key=$1 WHERE name='ingest' AND (api_key IS NULL OR api_key='')`, ingestKey); err != nil {
return err
// 内置主体默认 api_key:仅在为空时随机生成(幂等),避免空 key / 固定值被冒用或暴力破解。
// 生成的值只在生产首次启动时打印一次,之后由管理员在 Access Control 页查看/重置。
builtinKeys := []string{"manager", "connector", "public", "ingest"}
generated := map[string]string{}
for _, pn := range builtinKeys {
k := generateAPIKey()
tag, err := p.Exec(ctx,
`UPDATE principals SET api_key=$1 WHERE name=$2 AND (api_key IS NULL OR api_key='')`, k, pn)
if err != nil {
return fmt.Errorf("生成 %s 初始密钥失败: %w", pn, err)
}
if tag.RowsAffected() > 0 {
generated[pn] = k
}
}
if len(generated) > 0 {
log.Printf("[access] 已为内置主体生成随机初始 API Key(请妥善保存;首次启动后可在 Access Control 页重置):")
for _, pn := range builtinKeys {
if k, ok := generated[pn]; ok {
log.Printf("[access] %-9s = %s", pn, k)
}
}
}
+142
View File
@@ -568,6 +568,148 @@ func (a *app) classificationConfig(c *gin.Context) {
"hint": "levels 必须与 principal_clearances 使用同一套词汇,否则主体无任何交集 → 越级全屏蔽"})
}
// ---------- 管理接口:设置对象类型分级配置(v1.3.0) ----------
//
// 历史背景:
// - v1.2.0 加了 object_types.classification_property/_levels/_default 三列,但
// 只读路由 GET /classification/config 暴露,没配对应的 PUT/POST。
// - 后果:MCP 客户端 / 管理员 UI 无法把类型「启用分级」→ 587 个 data_level 实例
// 一直是裸属性,recomputeClassification 看到 enabled=false → 全部「(未分级)」。
// - 这次补 PUT 让管理员能真正写入配置;写完调用 recomputeClassification 把历史
// 裸属性一次性物化进 objects.classification 列。
//
// 设计要点:
// - 仅 manager 主体可调(mgmt.Use(loginRequired, managerAuth) 链已保证)。
// - 校验:levels 必须非空有序(低→高),default ∈ levels,property 是已存在
// 属性的 api_name(不强制强制,但建议对得上;不一致 recompute 会把空当未启用)。
// - 写库后 invalidateClassCache(),让下一次 GET config 立刻反映新值。
// - 不自动 recompute:管理员通常会一次性配齐多个类型后再统一重算;
// 自动重算会让单次 PUT 触发全库扫描 + 数百实例 write,前端体感会卡。
type setObjectTypeClassificationInput struct {
Property string `json:"classification_property"`
Levels []string `json:"classification_levels"`
Default string `json:"classification_default"`
}
// setObjectTypeClassification PUT /api/v1/ontology/object-types/:name/classification
//
// body 示例:
// {
// "classification_property": "data_level",
// "classification_levels": ["L0","L1","L2","L3"],
// "classification_default": "L0"
// }
//
// 响应:新配置快照 + recompute 提示(告诉调用方「下一步调 recompute_classification
// 让历史裸属性一次性物化」)。
func (a *app) setObjectTypeClassification(c *gin.Context) {
name := c.Param("name")
if name == "" {
c.JSON(400, gin.H{"error": "name 必填"})
return
}
var in setObjectTypeClassificationInput
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(400, gin.H{"error": "body 必须是合法 JSON: " + err.Error()})
return
}
// 关掉分级(property=空)允许 levels=[] 与 default=""
if in.Property == "" {
// property=空直接落库:levels 与 default 都以「空」处理(不会去校验词汇)
if _, err := a.pool.Exec(c,
`UPDATE object_types
SET classification_property='',
classification_levels='[]'::jsonb,
classification_default=''
WHERE api_name=$1`, name); err != nil {
c.JSON(500, gin.H{"error": "关闭分级失败: " + err.Error()})
return
}
invalidateClassCache()
c.JSON(200, gin.H{
"ok": true,
"api_name": name,
"enabled": false,
"classification_property": "",
"classification_levels": []string{},
"classification_default": "",
})
return
}
if len(in.Levels) == 0 {
c.JSON(400, gin.H{"error": "classification_levels 不能为空(property 已设,必须提供级别表)"})
return
}
for _, lv := range in.Levels {
if strings.TrimSpace(lv) == "" {
c.JSON(400, gin.H{"error": "classification_levels 不允许空字符串"})
return
}
}
if in.Default != "" {
ok := false
for _, lv := range in.Levels {
if lv == in.Default {
ok = true
break
}
}
if !ok {
c.JSON(400, gin.H{
"error": "classification_default 必须在 classification_levels 内",
"default": in.Default,
"levels": in.Levels,
"hint": "空字符串代表「不设默认」(写入时该属性缺失则 objects.classification 也为空)",
})
return
}
}
if in.Property != "" {
// 软校验:property 必须属于该类型(attribute-level safety)
var hit int
if err := a.pool.QueryRow(c,
`SELECT count(*) FROM properties p
JOIN object_types ot ON ot.id = p.object_type_id
WHERE ot.api_name=$1 AND p.api_name=$2`, name, in.Property).Scan(&hit); err != nil {
c.JSON(500, gin.H{"error": "校验 property 失败: " + err.Error()})
return
}
if hit == 0 {
c.JSON(400, gin.H{
"error": fmt.Sprintf("类型 %q 没有属性 %q,classification_property 必须指向已存在属性", name, in.Property),
"hint": "留空 = 关闭该类型的分级(enabled=false)",
})
return
}
}
// 落库
if _, err := a.pool.Exec(c,
`UPDATE object_types
SET classification_property=$1,
classification_levels=$2::jsonb,
classification_default=$3
WHERE api_name=$4`,
in.Property, mustJSON(in.Levels), in.Default, name); err != nil {
c.JSON(500, gin.H{"error": "更新分级配置失败: " + err.Error()})
return
}
invalidateClassCache()
enabled := in.Property != ""
c.JSON(200, gin.H{
"ok": true,
"api_name": name,
"enabled": enabled,
"classification_property": in.Property,
"classification_levels": in.Levels,
"classification_default": in.Default,
"next_step": "调用 recompute_classification({type: <this>, dry_run: true}) 验证影响面," +
"再 apply=true 一次性把历史裸属性物化进 objects.classification 列",
})
}
// ---------- 管理接口:批量重算(issue #5-⑩) ----------
type recomputeInput struct {
+203
View File
@@ -0,0 +1,203 @@
//go:build integration
package main
import (
"strconv"
"strings"
"testing"
)
// TestIntegration_SetObjectTypeClassification 验证「设置对象类型分级配置」端点
// 端到端能力:写入 → invalidateClassCache → GET config 立刻反映 → 不存在的 property 校验。
//
// 真实场景背景(v1.3.0 之前):
// - GET /classification/config 已存在很久(v1.2.0),但 PUT 端点缺失
// - 前端编辑「对象类型分级」保存按钮看似无反应(POST 到不存在的路由 → 404)
// - 后果:587 个打了 data_level 标签的实例是「裸属性」无法被分级引擎接管
func TestIntegration_SetObjectTypeClassification(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
// 用一个已有「真属性行」的类型,避免 setupTestEnv 新建的测试类型 properties 行为不同
// DataDemand 在本工作区有 64 个属性行(详见 docs/db/0910 schema)。
const fixedType = "DataDemand"
t.Cleanup(func() {
// 测试结束清理 DataDemand 的分级配置(避免污染其他测试)
env.httpDo(t, "PUT", "/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "",
"classification_levels": []string{},
"classification_default": "",
}, h)
})
// 1) PUT 设置分级属性(DataDemand 有 approval_status 字段)
code, body := env.httpDo(t, "PUT",
"/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "approval_status",
"classification_levels": []string{"1", "3-replaced"},
"classification_default": "1",
}, h)
if code != 200 {
t.Fatalf("PUT 应 200, got %d body=%v", code, body)
}
if body["enabled"] != true {
t.Errorf("enabled 应 true, got %v", body["enabled"])
}
// 2) GET config 立刻反映
_, getConfig := env.httpDo(t, "GET", "/api/v1/ontology/classification/config", nil, h)
var found map[string]any
for _, it := range getConfig["items"].([]any) {
m := it.(map[string]any)
if m["api_name"] == fixedType {
found = m
}
}
if found == nil {
t.Fatalf("GET config 应包含 %s, got %v", fixedType, getConfig)
}
if found["enabled"] != true || found["classification_property"] != "approval_status" {
t.Errorf("config 不匹配 PUT, got %+v", found)
}
// 3) 校验:levels 空但 property 已设 → 400(property=""+levels=[] 是关闭分级入口,合法)
code, _ = env.httpDo(t, "PUT",
"/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "approval_status",
"classification_levels": []string{},
}, h)
if code != 400 {
t.Errorf("property 已设但 levels=空 应 400, got %d", code)
}
// 4) 校验:default 不在 levels → 400
code, _ = env.httpDo(t, "PUT",
"/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "approval_status",
"classification_levels": []string{"1", "3-replaced"},
"classification_default": "GAMMA-OUT-OF-RANGE",
}, h)
if code != 400 {
t.Errorf("default 不在 levels 应 400, got %d", code)
}
// 5) 校验:property 指向不存在的属性 → 400
code, _ = env.httpDo(t, "PUT",
"/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "this_property_does_not_exist",
"classification_levels": []string{"x"},
}, h)
if code != 400 {
t.Errorf("property 不存在应 400, got %d", code)
}
// 6) PUT 关闭该类型分级(property=空)
code, body = env.httpDo(t, "PUT",
"/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "",
"classification_levels": []string{},
"classification_default": "",
}, h)
if code != 200 {
t.Fatalf("关闭分级应 200, got %d", code)
}
if body["enabled"] != false {
t.Errorf("property=空 时 enabled 应 false, got %v", body["enabled"])
}
// 7) GET config 立刻反映关闭
_, getConfig2 := env.httpDo(t, "GET", "/api/v1/ontology/classification/config", nil, h)
var found2 map[string]any
for _, it := range getConfig2["items"].([]any) {
m := it.(map[string]any)
if m["api_name"] == fixedType {
found2 = m
}
}
if found2["enabled"] != false {
t.Errorf("关闭后 GET 应 enabled=false, got %+v", found2)
}
}
// TestIntegration_SetClassificationThroughMCP 验证 MCP 工具 set_object_type_classification
// 是否正确代理到刚补的 REST PUT。需要 manager 主体。
func TestIntegration_SetClassificationThroughMCP(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
const fixedType = "DataDemand"
t.Cleanup(func() {
env.httpDo(t, "PUT", "/api/v1/ontology/object-types/"+fixedType+"/classification",
map[string]any{
"classification_property": "",
"classification_levels": []string{},
"classification_default": "",
}, h)
})
// 用 MCP 调用 set_object_type_classification
code, body := env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "1", "method": "tools/call",
"params": map[string]any{
"name": "set_object_type_classification",
"arguments": map[string]any{
"api_name": fixedType,
"classification_property": "approval_status",
"classification_levels": []string{"1", "3-replaced"},
"classification_default": "1",
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 调用应 200, got %d body=%v", code, body)
}
// 响应 result.content[0].text 是 JSON 字符串
result, _ := body["result"].(map[string]any)
if result == nil {
t.Fatalf("MCP 响应缺 result, got %v", body)
}
content, _ := result["content"].([]any)
if len(content) == 0 {
t.Fatalf("MCP 响应缺 content, got %v", result)
}
first, _ := content[0].(map[string]any)
text, _ := first["text"].(string)
if !strings.Contains(text, `"enabled":true`) {
t.Errorf("MCP 响应应 enabled:true, got %s", text)
}
// MCP 缺 levels 应报错(参数错误,levels 不能为空)
code, body = env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "2", "method": "tools/call",
"params": map[string]any{
"name": "set_object_type_classification",
"arguments": map[string]any{
"api_name": fixedType,
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 缺 levels 应 200 含错误信息, got %d", code)
}
r2, _ := body["result"].(map[string]any)
c2, _ := r2["content"].([]any)
if len(c2) == 0 {
t.Fatalf("MCP 响应缺 content")
}
t2, _ := c2[0].(map[string]any)["text"].(string)
if !strings.Contains(t2, "classification_levels") {
t.Errorf("MCP 缺 levels 应报错, got %s", t2)
}
_ = strconv.Itoa // 占位避免 unused
}
-6
View File
@@ -10,9 +10,6 @@ import (
type Config struct {
HTTPPort int
DatabaseURL string
ManagerAPIKey string // 管理类接口(写本体/实例/AI摄取)的鉴权 key,留空则关闭鉴权
ConnectorAPIKey string // 连接器查询接口的鉴权 key,留空则关闭鉴权
IngestAPIKey string // 知识导入接口(MCP/agent 写 KM)的鉴权 key,留空则 dev 模式默认 manager
AIBaseURL string // OpenAI 兼容大模型基地址,如 https://api.openai.com/v1
AIKey string // 大模型 API Key
AIModel string // 模型名,如 gpt-4o / deepseek-chat / qwen-max
@@ -26,9 +23,6 @@ func loadConfig() *Config {
c := &Config{
HTTPPort: getEnvInt("HTTP_PORT", 8081),
DatabaseURL: getEnv("DATABASE_URL", "postgres://dacli:dacli123@localhost:15432/shangshu?sslmode=disable"),
ManagerAPIKey: getEnv("MANAGER_API_KEY", ""),
ConnectorAPIKey: getEnv("CONNECTOR_API_KEY", ""),
IngestAPIKey: getEnv("INGEST_API_KEY", ""),
AIBaseURL: getEnv("AI_BASE_URL", "https://api.openai.com/v1"),
AIKey: getEnv("AI_KEY", ""),
AIModel: getEnv("AI_MODEL", "gpt-4o"),
+72 -14
View File
@@ -32,6 +32,8 @@ func (a *app) listPrincipals(c *gin.Context) {
HasAPIKey bool `json:"has_api_key"`
APIKeyHint string `json:"api_key_hint"`
APIKeyCreatedAt string `json:"api_key_created_at,omitempty"`
// 修复 issue #7:clearances 一并回显,否则管理员看不到当前主体的可见级别集。
Clearances []string `json:"clearances"`
}
var out []pRow
for rows.Next() {
@@ -40,7 +42,7 @@ func (a *app) listPrincipals(c *gin.Context) {
var builtin bool
if err := rows.Scan(&p.Name, &p.Description, &builtin, &key); err == nil {
p.IsBuiltin = builtin
row := pRow{Principal: p, HasAPIKey: key != ""}
row := pRow{Principal: p, HasAPIKey: key != "", Clearances: []string{}}
if key != "" {
row.APIKeyHint = maskAPIKey(key)
row.APIKeyCreatedAt = "已绑定"
@@ -48,10 +50,30 @@ func (a *app) listPrincipals(c *gin.Context) {
out = append(out, row)
}
}
// 单独查询所有 clearances(按 principal 分组),避免 N+1
if len(out) > 0 {
clRows, err := a.pool.Query(c, `SELECT principal, marking FROM principal_clearances ORDER BY principal, marking`)
if err == nil {
idx := map[string]int{}
for i, p := range out {
idx[p.Name] = i
}
for clRows.Next() {
var pn, mk string
if clRows.Scan(&pn, &mk) == nil {
if i, ok := idx[pn]; ok {
out[i].Clearances = append(out[i].Clearances, mk)
}
}
}
clRows.Close()
}
}
c.JSON(200, gin.H{"principals": out, "count": len(out)})
}
// getPrincipal 返回单个主体,manager 可拿到完整 api_key(仅展示一次以外不会在 list 中回)
// getPrincipal 返回单个主体,manager 可拿到完整 api_key(仅展示一次以外不会在 list 中回)。
// 修复 issue #7:响应同时回显 clearances 数组,否则前端拿不到主体可见级别集。
func (a *app) getPrincipal(c *gin.Context) {
name := c.Param("name")
var description string
@@ -75,6 +97,20 @@ func (a *app) getPrincipal(c *gin.Context) {
resp["api_key"] = key
resp["api_key_hint"] = maskAPIKey(key)
}
// 拉 clearances(保证非 nil,序列化成 [] 而不是 null)
cls := []string{}
clRows, clErr := a.pool.Query(c,
`SELECT marking FROM principal_clearances WHERE principal=$1 ORDER BY marking`, name)
if clErr == nil {
defer clRows.Close()
for clRows.Next() {
var m string
if clRows.Scan(&m) == nil {
cls = append(cls, m)
}
}
}
resp["clearances"] = cls
c.JSON(200, resp)
}
@@ -101,13 +137,18 @@ type principalInput struct {
}
type principalUpdateInput struct {
Description *string `json:"description"`
APIKey *string `json:"api_key"`
ClearAPIKey bool `json:"clear_api_key"`
GenerateAPIKey bool `json:"generate_api_key"`
Description *string `json:"description"`
APIKey *string `json:"api_key"`
ClearAPIKey bool `json:"clear_api_key"`
GenerateAPIKey bool `json:"generate_api_key"`
// 修复 issue #7:之前 PUT /principals/:name 完全不接受 clearances 字段(用户传时静默忽略),
// 现允许一次性替换主体的 clearance 集(与 PUT /principals/:name/clearances 同义)。
// nil=不动;[]=清空;非空=全量替换(DELETE + INSERT)。
Clearances *[]string `json:"clearances"`
}
// updatePrincipal 修改主体的说明和 api_key
// updatePrincipal 修改主体的说明、api_key、clearances(合并语义)。
// 修复 issue #7:之前 clearances 字段被静默忽略;现支持在同一次 PUT 中同时改 description / api_key / clearances。
func (a *app) updatePrincipal(c *gin.Context) {
name := c.Param("name")
var in principalUpdateInput
@@ -115,13 +156,9 @@ func (a *app) updatePrincipal(c *gin.Context) {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if name == "manager" || name == "connector" || name == "public" {
// 内置主体允许更新说明;不允许清空 key 或自动生成 key
if in.ClearAPIKey || in.GenerateAPIKey || (in.APIKey != nil && *in.APIKey != "") {
c.JSON(400, gin.H{"error": "内置主体不允许修改 api_key,请使用 .env 中的 MANAGER_API_KEY/CONNECTOR_API_KEY"})
return
}
}
// 内置主体(manager/connector/public)的 api_key 均允许通过管理接口设置/重置/清空。
// - 鉴权时 principalFromRequest 仅查 principals 表的 api_key(seed 随机值或 UI 设置),不再读 .env。
// - public 即便持有 key 也只是匿名 L0 只读身份,不会升权;DB 里的 key 仅作为其匿名身份的显式别名。
tx, err := a.pool.Begin(c)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
@@ -153,11 +190,29 @@ func (a *app) updatePrincipal(c *gin.Context) {
return
}
}
// 修复 issue #7:clearances 字段支持。nil=不动;非空数组(含 [])= 全量替换。
if in.Clearances != nil {
if _, err := tx.Exec(c, `DELETE FROM principal_clearances WHERE principal=$1`, name); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
for _, m := range *in.Clearances {
if m = strings.TrimSpace(m); m != "" {
if _, err := tx.Exec(c,
`INSERT INTO principal_clearances(principal,marking) VALUES($1,$2) ON CONFLICT DO NOTHING`,
name, m); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
}
}
}
if err := tx.Commit(c); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
a.InvalidateAuthzCache(name)
// 回读,让前端能立即核对(同时验证上面 writes)
resp := gin.H{"ok": true, "name": name}
if finalKey != "" {
resp["api_key"] = finalKey
@@ -168,6 +223,9 @@ func (a *app) updatePrincipal(c *gin.Context) {
} else {
resp["has_api_key"] = finalKey != ""
}
if in.Clearances != nil {
resp["clearances"] = *in.Clearances
}
c.JSON(200, resp)
}
+5 -5
View File
@@ -632,7 +632,7 @@ func (a *app) mcpManifest(c *gin.Context) {
"commit": Commit,
"base_url": "/api/v1/connector",
"mcp_url": "/api/v1/mcp",
"auth": authHint(a.cfg),
"auth": authHint(a),
"feedback": gin.H{
"issues": "https://oadfec13300ad18dm.mayishangshu.cn:82/ssw/ssw-ontology/issues",
"api": "POST /api/v1/feedback(公开,无需 token)body={\"title\":\"...\",\"body\":\"复现/期望/实际\",\"kind\":\"bug|suggestion\"};服务端自动建 issue 并返回 issue_url",
@@ -656,11 +656,11 @@ func (a *app) mcpManifest(c *gin.Context) {
})
}
func authHint(cfg *Config) string {
if cfg.ConnectorAPIKey == "" {
return "无需鉴权(可在 .env 设置 CONNECTOR_API_KEY 开启)"
func authHint(a *app) string {
if a.principalKeySet("connector") {
return "请求头携带 X-API-Key(密钥在 Access Control 页管理)"
}
return "请求头携带 X-API-Key"
return "无需鉴权(首次启动尚未生成 connector 密钥时开放)"
}
// itoa 局部整型转字符串,避免引入额外依赖
+197 -2
View File
@@ -205,6 +205,53 @@ func mcpToolList() []MCPTool {
"required": []string{"api_name", "display_name"},
},
},
{
// 修复 issue #6:MCP 工具集补齐「向已存在对象类型追加/更新属性」入口,
// 解决 587 个 data_level 孤儿(属性已写但 schema 未注册)无法被分类引擎接管的根因。
Name: "update_object_type",
Description: "【写入】更新已存在对象类型的元数据(display_name/icon/group/title_property 等),可一并 upsert properties(合并语义:同名属性更新元数据,新名属性新增;删除走 delete_property)。修复 issue #6 之前 PUT 端点静默忽略 properties 的 bug。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"api_name": map[string]interface{}{"type": "string", "description": "对象类型 api_name(必填,URL 路径)"},
"display_name": map[string]interface{}{"type": "string"},
"description": map[string]interface{}{"type": "string"},
"icon": map[string]interface{}{"type": "string"},
"group": map[string]interface{}{"type": "string"},
"title_property": map[string]interface{}{"type": "string"},
"subtitle_property": map[string]interface{}{"type": "string"},
"color": map[string]interface{}{"type": "string"},
"primary_key": map[string]interface{}{"type": "string"},
"classification_property": map[string]interface{}{"type": "string", "description": "留空=关闭分级;非空=启用并绑定到该属性"},
"classification_levels": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "分级词汇(有序),如 [L0,L1,L2,L3]"},
"classification_default": map[string]interface{}{"type": "string", "description": "默认级别(必须 ∈ classification_levels)"},
"properties": map[string]interface{}{"type": "array", "description": "可选:upsert 属性数组 [{api_name,display_name,data_type,required,enum_values,description,format,indexable,sensitivity}]"},
},
"required": []string{"api_name"},
},
},
{
// 修复 issue #6 方案 A:MCP 工具集补齐「加一个属性」入口(包装 POST /properties)。
// 与 update_object_type 的内联 properties 等价但更细粒度,适合"只补一个"场景。
Name: "add_object_type_property",
Description: "【写入】向已存在对象类型注册一个新属性(upsert:同名属性按非空字段更新,已存在则覆盖元数据)。用于解决「实例已有 X 属性但 schema 未注册」类缺口(如 587 个 data_level 孤儿)。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"api_name": map[string]interface{}{"type": "string", "description": "对象类型 api_name"},
"property_api_name": map[string]interface{}{"type": "string", "description": "新属性的稳定标识(必填)"},
"display_name": map[string]interface{}{"type": "string", "description": "新属性的中文显示名(必填)"},
"data_type": map[string]interface{}{"type": "string", "description": "string/number/boolean/date/enum/...(默认 string)"},
"required": map[string]interface{}{"type": "boolean"},
"enum_values": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "enum 约束,如 [L0,L1,L2,L3]"},
"description": map[string]interface{}{"type": "string"},
"format": map[string]interface{}{"type": "string"},
"indexable": map[string]interface{}{"type": "boolean"},
"sensitivity": map[string]interface{}{"type": "string", "description": "字段级敏感度(取自分级词汇)"},
},
"required": []string{"api_name", "property_api_name", "display_name"},
},
},
{
Name: "create_link_type",
Description: "【写入】新建链接类型(关系边),表达两个对象类型之间的关系,如 tds_uses_tee / consumes_ontology。",
@@ -383,6 +430,20 @@ func mcpToolList() []MCPTool {
},
},
},
{
Name: "set_object_type_classification",
Description: "【写入】配置对象类型的分级引擎:指定 classification_property(属性名)、classification_levels(有序级别数组,低→高)、classification_default(写入时属性缺失时的默认级别,可空)。设完后用 recompute_classification(dry_run=true) 验证影响面,再 apply=true 物化历史裸属性。需要 manager 主体。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"api_name": map[string]interface{}{"type": "string", "description": "对象类型 api_name"},
"classification_property": map[string]interface{}{"type": "string", "description": "承载分级值的属性名(留空=关闭该类型分级)"},
"classification_levels": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "有序级别列表(低→高),如 [\"L0\",\"L1\",\"L2\",\"L3\"]"},
"classification_default": map[string]interface{}{"type": "string", "description": "属性缺失时的默认级别(空=不设默认);必须在 levels 内"},
},
"required": []string{"api_name", "classification_levels"},
},
},
{
Name: "set_km_classification",
Description: "【写入】给 KM 源文件打分级,并把该文件已抽取实例的分级抬到对应下界(文件级高敏→产物也高敏)。",
@@ -452,6 +513,40 @@ func mcpToolList() []MCPTool {
"required": []string{"id"},
},
},
// 修复 issue #7:MCP 工具集补齐主体维度的读/写入口(之前 36 个工具缺这一片)。
// list_principals / get_principal 只读;set_principal_clearance 是写入(manager 主体)。
{
Name: "list_principals",
Description: "【只读】列出全部主体及其 clearance(分级可见级别)。用于核对「哪些主体能看哪些分级」。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{},
},
},
{
Name: "get_principal",
Description: "【只读】按名称取单个主体(含 description / has_api_key / clearances)。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string", "description": "主体名"},
},
"required": []string{"name"},
},
},
{
Name: "set_principal_clearance",
Description: "【写入】全量替换主体的 clearance 集(nil 数组=清空)。修复 issue #7 之前 MCP 工具集完全无法配置 clearance 的缺口。可让 connector 也能看 L3 等。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string", "description": "主体名"},
"clearances": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "标记集,如 [L0,L1,L2,L3];传 []=清空;alias: markings"},
"markings": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "alias 同 clearances(与 PUT /principals/:name/clearances 命名一致)"},
},
"required": []string{"name"},
},
},
}
}
@@ -714,6 +809,87 @@ func (a *app) mcpDispatchTool(c *gin.Context, name string, args map[string]inter
}
return t, false, false
// 修复 issue #6:之前 MCP 工具集没有"向已存在类型追加属性"的入口,
// 导致 587 个 data_level 孤儿无法被分类引擎接管(方案 A)。
case "update_object_type":
if !canWrite {
return denyWrite()
}
apiName, _ := args["api_name"].(string)
if apiName == "" {
return "参数错误:api_name 必填", false, true
}
body, _ := json.Marshal(args)
t, st := a.callHandler(a.updateObjectType, gin.Params{gin.Param{Key: "name", Value: apiName}}, body, principal)
return t, false, st >= 400
case "add_object_type_property":
if !canWrite {
return denyWrite()
}
apiName, _ := args["api_name"].(string)
propAPIName, _ := args["property_api_name"].(string)
disp, _ := args["display_name"].(string)
if apiName == "" || propAPIName == "" || disp == "" {
return "参数错误:api_name / property_api_name / display_name 必填", false, true
}
body, _ := json.Marshal(map[string]interface{}{
"api_name": propAPIName,
"display_name": disp,
"data_type": optStr(args, "data_type"),
"required": args["required"],
"enum_values": args["enum_values"],
"description": optStr(args, "description"),
"format": optStr(args, "format"),
"indexable": args["indexable"],
"sensitivity": optStr(args, "sensitivity"),
})
t, st := a.callHandler(a.addProperty, gin.Params{gin.Param{Key: "name", Value: apiName}}, body, principal)
return t, false, st >= 400
// 修复 issue #7:MCP 工具集补齐「按主体维度读/写 clearance」。
// 之前 36 个工具没有这俩,导致管理员改不了「connector 看不到 L3」之类配置。
case "list_principals":
t, st := a.callHandler(a.listPrincipals, nil, nil, principal)
return t, false, st >= 400
case "get_principal":
name, _ := args["name"].(string)
if name == "" {
return "参数错误:name 必填", false, true
}
t, st := a.callHandler(a.getPrincipal, gin.Params{gin.Param{Key: "name", Value: name}}, nil, principal)
return t, false, st >= 400
case "set_principal_clearance":
if !canWrite {
return denyWrite()
}
name, _ := args["name"].(string)
if name == "" {
return "参数错误:name 必填", false, true
}
// 接受 clearances / markings 两种命名(与 PUT /principals/:name/clearances 一致用 markings)
var marks []string
if raw, ok := args["clearances"].([]interface{}); ok {
for _, m := range raw {
if s, ok := m.(string); ok {
marks = append(marks, s)
}
}
}
if raw, ok := args["markings"].([]interface{}); ok {
marks = marks[:0]
for _, m := range raw {
if s, ok := m.(string); ok {
marks = append(marks, s)
}
}
}
body, _ := json.Marshal(map[string]interface{}{"markings": marks})
t, st := a.callHandler(a.putClearances, gin.Params{gin.Param{Key: "name", Value: name}}, body, principal)
return t, false, st >= 400
case "create_link_type":
if !canWrite {
return denyWrite()
@@ -837,6 +1013,24 @@ func (a *app) mcpDispatchTool(c *gin.Context, name string, args map[string]inter
t, st := a.mcpCall("POST", "/api/v1/ontology/classification/recompute", body, principal)
return t, false, st >= 400
case "set_object_type_classification":
if !canWrite {
return denyWrite()
}
apiName, _ := args["api_name"].(string)
if apiName == "" {
return "参数错误:api_name 必填", false, true
}
// 把 MCP 字段名(api_name)映射到路由参数(:name)+ body 嵌套字段
bodyIn := map[string]interface{}{
"classification_property": args["classification_property"],
"classification_levels": args["classification_levels"],
"classification_default": args["classification_default"],
}
body, _ := json.Marshal(bodyIn)
t, st := a.mcpCall("PUT", "/api/v1/ontology/object-types/"+url.PathEscape(apiName)+"/classification", body, principal)
return t, false, st >= 400
case "set_km_classification":
if !canWrite {
return denyWrite()
@@ -929,8 +1123,9 @@ func (a *app) callConn(method, path string, body []byte) string {
}
req := httptest.NewRequest(method, path, reader)
req.Header.Set("Content-Type", "application/json")
if a.cfg.ConnectorAPIKey != "" {
req.Header.Set("X-API-Key", a.cfg.ConnectorAPIKey)
// 内部调用连接器 handler:注入 connector 主体的 api_key 以通过 connectorAuth(密钥统一存于 principals 表)。
if k := a.builtinKey("connector"); k != "" {
req.Header.Set("X-API-Key", k)
}
w := httptest.NewRecorder()
a.engine.ServeHTTP(w, req)
+70
View File
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"fmt"
"strconv"
"github.com/gin-gonic/gin"
@@ -60,6 +61,10 @@ type objectTypeInput struct {
ClassificationProperty string `json:"classification_property"`
ClassificationLevels []string `json:"classification_levels"`
ClassificationDefault string `json:"classification_default"`
// 创建/更新对象类型时一并 upsert 的属性(issue #6)。upsert 语义:同 api_name 已存在则更新元数据,
// 不存在则新增;删除走 DELETE /properties/:id。这样既能一次性创建带属性的类型,
// 也能给已有类型补注册属性(解决"587 个 data_level 孤儿"这类缺口)。
Properties []propertyInput `json:"properties"`
}
func (a *app) createObjectType(c *gin.Context) {
@@ -98,6 +103,13 @@ func (a *app) createObjectType(c *gin.Context) {
c.JSON(409, gin.H{"error": "创建失败(可能 api_name 重复): " + err.Error()})
return
}
// 内联 upsert 属性(如提供)。与 updateObjectType 共用 upsertObjectTypeProperties,保持一致性。
if len(in.Properties) > 0 {
if err := a.upsertObjectTypeProperties(c, id, in.Properties); err != nil {
c.JSON(500, gin.H{"error": "属性写入失败: " + err.Error()})
return
}
}
c.JSON(201, gin.H{"id": id, "api_name": in.APIName})
}
@@ -163,9 +175,67 @@ func (a *app) updateObjectType(c *gin.Context) {
c.JSON(404, gin.H{"error": "对象类型不存在"})
return
}
// 修复 issue #6:之前 properties 字段被静默忽略,导致"已有类型补注册属性"无任何入口。
// 现在 in.Properties 非空时一并 upsert(与 createObjectType 走同一辅助函数,语义一致)。
if len(in.Properties) > 0 {
var oid int64
if err := a.pool.QueryRow(c, `SELECT id FROM object_types WHERE api_name=$1`, name).Scan(&oid); err != nil {
c.JSON(500, gin.H{"error": "取对象类型 id 失败: " + err.Error()})
return
}
if err := a.upsertObjectTypeProperties(c, oid, in.Properties); err != nil {
c.JSON(500, gin.H{"error": "属性写入失败: " + err.Error()})
return
}
}
c.JSON(200, gin.H{"ok": true})
}
// upsertObjectTypeProperties 在指定对象类型上批量 upsert 属性。同 api_name 已存在则按非空字段
// 更新元数据,不存在则新增。删除走 DELETE /properties/:id(保留审计粒度)。
func (a *app) upsertObjectTypeProperties(c *gin.Context, oid int64, props []propertyInput) error {
for _, p := range props {
if p.APIName == "" || p.DisplayName == "" {
return fmt.Errorf("属性 api_name 与 display_name 必填(api_name=%q)", p.APIName)
}
if p.DataType == "" {
p.DataType = "string"
}
enum := "[]"
if len(p.EnumValues) > 0 {
enum = mustJSON(p.EnumValues)
}
defVal := "null"
if p.DefaultValue != nil {
defVal = mustJSON(p.DefaultValue)
}
// upsert: 已存在则按非空字段更新;新建则插入完整记录。
// sensitivity 单独 CASE WHEN 控制(与 updateProperty 保持一致)。
_, err := a.pool.Exec(c,
`INSERT INTO properties(object_type_id,api_name,display_name,data_type,required,enum_values,description,
format,default_value,indexable,vector_index,backing_column,sensitivity)
VALUES($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9::jsonb,$10,$11,$12,$13)
ON CONFLICT(object_type_id,api_name) DO UPDATE SET
display_name=EXCLUDED.display_name,
data_type=EXCLUDED.data_type,
required=EXCLUDED.required,
enum_values=EXCLUDED.enum_values,
description=EXCLUDED.description,
format=EXCLUDED.format,
default_value=EXCLUDED.default_value,
indexable=EXCLUDED.indexable,
vector_index=EXCLUDED.vector_index,
backing_column=EXCLUDED.backing_column,
sensitivity=EXCLUDED.sensitivity`,
oid, p.APIName, p.DisplayName, p.DataType, p.Required, enum, p.Description,
p.Format, defVal, p.Indexable, p.VectorIndex, p.BackingColumn, p.Sensitivity)
if err != nil {
return err
}
}
return nil
}
func (a *app) deleteObjectType(c *gin.Context) {
name := c.Param("name")
tag, err := a.pool.Exec(c, `DELETE FROM object_types WHERE api_name=$1`, name)
+223
View File
@@ -0,0 +1,223 @@
//go:build integration
package main
import (
"strings"
"testing"
)
// TestIntegration_UpdateObjectType_MergesProperties 修复 issue #6:
// 之前 PUT /object-types/:name 静默忽略 properties 字段,导致「已有类型补注册属性」无入口。
// 验证:properties 数组非空时被 upsert(同名属性更新元数据,新名属性新增)。
func TestIntegration_UpdateObjectType_MergesProperties(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
// 用 setupTestEnv 已建的类型(test_UpdateMergeProp),保证隔离
key := "test_UpdateMergeProp"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "测试合并属性"}, h); code != 201 {
t.Fatalf("setup create failed: %d", code)
}
// 1) 第一次 PUT:追加 2 个属性
code, body := env.httpDo(t, "PUT", "/api/v1/ontology/object-types/"+key,
map[string]any{
"properties": []map[string]any{
{"api_name": "data_level", "display_name": "数据级别",
"data_type": "string", "enum_values": []string{"L0", "L1", "L2", "L3"}},
{"api_name": "owner_team", "display_name": "所属团队", "data_type": "string"},
},
}, h)
if code != 200 {
t.Fatalf("PUT 应 200, got %d body=%v", code, body)
}
// 2) GET object_type 应包含这两个属性
_, got := env.httpDo(t, "GET", "/api/v1/ontology/object-types/"+key, nil, h)
ot := got["object_type"].(map[string]any)
props := ot["properties"].([]any)
apiNames := map[string]bool{}
for _, p := range props {
apiNames[p.(map[string]any)["api_name"].(string)] = true
}
if !apiNames["data_level"] {
t.Errorf("data_level 未注册, props=%v", apiNames)
}
if !apiNames["owner_team"] {
t.Errorf("owner_team 未注册, props=%v", apiNames)
}
// 3) 第二次 PUT:更新 data_level 的 enum + 加新属性(merge 语义,已存在的应被覆盖而非新增)
code, _ = env.httpDo(t, "PUT", "/api/v1/ontology/object-types/"+key,
map[string]any{
"properties": []map[string]any{
{"api_name": "data_level", "display_name": "数据级别(已修订)",
"data_type": "string", "enum_values": []string{"L0", "L1", "L2", "L3", "L4"}},
{"api_name": "reviewer", "display_name": "审核人", "data_type": "string"},
},
}, h)
if code != 200 {
t.Fatalf("第二次 PUT 应 200, got %d", code)
}
_, got2 := env.httpDo(t, "GET", "/api/v1/ontology/object-types/"+key, nil, h)
ot2 := got2["object_type"].(map[string]any)
props2 := ot2["properties"].([]any)
var dlProps int
var foundReviewer bool
var dlEnum []any
for _, p := range props2 {
m := p.(map[string]any)
if m["api_name"] == "data_level" {
dlProps++
dlEnum = m["enum_values"].([]any)
}
if m["api_name"] == "reviewer" {
foundReviewer = true
}
}
if dlProps != 1 {
t.Errorf("data_level 应只 1 条(被更新而非新增), got %d", dlProps)
}
if len(dlEnum) != 5 {
t.Errorf("data_level enum 应被覆盖为 5 项, got %d (%v)", len(dlEnum), dlEnum)
}
if !foundReviewer {
t.Errorf("新属性 reviewer 未注册")
}
}
// TestIntegration_AddObjectTypeProperty_MCP 修复 issue #6 方案 A:
// MCP 工具集暴露 add_object_type_property(包装 POST /properties)。
// 验证 MCP 调用真的注册了属性,而不是空跑。
func TestIntegration_AddObjectTypeProperty_MCP(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
key := "test_AddPropertyMCP"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "测试 MCP 加属性"}, h); code != 201 {
t.Fatalf("setup create failed: %d", code)
}
// 通过 MCP 加一个属性
code, body := env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "1", "method": "tools/call",
"params": map[string]any{
"name": "add_object_type_property",
"arguments": map[string]any{
"api_name": key,
"property_api_name": "data_level",
"display_name": "数据级别",
"data_type": "string",
"enum_values": []string{"L0", "L1", "L2", "L3"},
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 应 200, got %d body=%v", code, body)
}
result := body["result"].(map[string]any)
content := result["content"].([]any)
text := content[0].(map[string]any)["text"].(string)
if !strings.Contains(text, `"ok"`) {
t.Errorf("MCP 响应应含 ok, got %s", text)
}
// 验证属性真的注册了
_, got := env.httpDo(t, "GET", "/api/v1/ontology/object-types/"+key, nil, h)
ot := got["object_type"].(map[string]any)
props := ot["properties"].([]any)
var found bool
for _, p := range props {
if p.(map[string]any)["api_name"] == "data_level" {
found = true
break
}
}
if !found {
t.Errorf("data_level 属性未注册, props=%v", props)
}
// MCP 缺 property_api_name 应报错
code, body = env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "2", "method": "tools/call",
"params": map[string]any{
"name": "add_object_type_property",
"arguments": map[string]any{
"api_name": key,
"display_name": "缺 api_name",
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 错误响应应 200, got %d", code)
}
r2 := body["result"].(map[string]any)
c2 := r2["content"].([]any)
t2 := c2[0].(map[string]any)["text"].(string)
if !strings.Contains(t2, "property_api_name") {
t.Errorf("MCP 缺 property_api_name 应报错, got %s", t2)
}
}
// TestIntegration_UpdateObjectType_MCP 验证 issue #6 方案 A 的另一半:
// MCP update_object_type 工具可一并 upsert properties。
func TestIntegration_UpdateObjectType_MCP(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
key := "test_UpdateOTMCP"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "测试 MCP update"}, h); code != 201 {
t.Fatalf("setup create failed: %d", code)
}
// MCP 更新 display_name + 追加属性
code, _ := env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "1", "method": "tools/call",
"params": map[string]any{
"name": "update_object_type",
"arguments": map[string]any{
"api_name": key,
"display_name": "测试 MCP update(已修订)",
"properties": []map[string]any{
{"api_name": "data_level", "display_name": "数据级别",
"data_type": "string", "enum_values": []string{"L0", "L1", "L2", "L3"}},
},
},
},
}, h)
if code != 200 {
t.Fatalf("MCP update_object_type 应 200, got %d", code)
}
_, got := env.httpDo(t, "GET", "/api/v1/ontology/object-types/"+key, nil, h)
ot := got["object_type"].(map[string]any)
if ot["display_name"] != "测试 MCP update(已修订)" {
t.Errorf("display_name 未更新, got %v", ot["display_name"])
}
var found bool
for _, p := range ot["properties"].([]any) {
if p.(map[string]any)["api_name"] == "data_level" {
found = true
}
}
if !found {
t.Errorf("data_level 未通过 MCP update_object_type 注册")
}
}
+225
View File
@@ -0,0 +1,225 @@
//go:build integration
package main
import (
"strings"
"testing"
)
// TestIntegration_UpdatePrincipal_Clearances 修复 issue #7:
// 之前 PUT /access/principals/:name 的 clearances 字段被静默忽略,
// 用户找不到任何「编辑主体 clearance」的入口。
// 验证:clearances 数组在 PUT 时一并落库(DELETE + INSERT 全量替换),
// GET /principals/:name 和 listPrincipals 都能回显。
func TestIntegration_UpdatePrincipal_Clearances(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
// 用一个非内置主体(避免污染 manager seed)
key := "test_principal_clearance"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/access/principals/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/access/principals",
map[string]any{"name": key, "description": "测试 clearance 配置"}, h); code != 201 {
t.Fatalf("create principal failed: %d", code)
}
// 1) PUT 设置 clearances
code, body := env.httpDo(t, "PUT", "/api/v1/access/principals/"+key,
map[string]any{"clearances": []string{"L0", "L1", "L2"}}, h)
if code != 200 {
t.Fatalf("PUT 应 200, got %d body=%v", code, body)
}
if got := body["clearances"]; got == nil {
t.Errorf("响应应回显 clearances, got %v", body)
}
// 2) GET /principals/:name 应回显
_, get := env.httpDo(t, "GET", "/api/v1/access/principals/"+key, nil, h)
cls := get["clearances"].([]any)
if len(cls) != 3 {
t.Errorf("GET 应回 3 项, got %d (%v)", len(cls), cls)
}
// 3) 再次 PUT 全量替换(含 L3)→ 验证替换语义
code, body = env.httpDo(t, "PUT", "/api/v1/access/principals/"+key,
map[string]any{"clearances": []string{"L0", "L1", "L2", "L3"}}, h)
if code != 200 {
t.Fatalf("PUT 应 200, got %d", code)
}
_, get2 := env.httpDo(t, "GET", "/api/v1/access/principals/"+key, nil, h)
cls2 := get2["clearances"].([]any)
if len(cls2) != 4 {
t.Errorf("替换后应 4 项, got %d (%v)", len(cls2), cls2)
}
// 4) PUT clearances=[] 清空
code, _ = env.httpDo(t, "PUT", "/api/v1/access/principals/"+key,
map[string]any{"clearances": []string{}}, h)
if code != 200 {
t.Fatalf("PUT 空数组应 200, got %d", code)
}
_, get3 := env.httpDo(t, "GET", "/api/v1/access/principals/"+key, nil, h)
cls3 := get3["clearances"].([]any)
if len(cls3) != 0 {
t.Errorf("清空后应 0 项, got %d (%v)", len(cls3), cls3)
}
// 5) PUT 不带 clearances 字段 → 不动(之前的 clearance 仍空)
code, _ = env.httpDo(t, "PUT", "/api/v1/access/principals/"+key,
map[string]any{"description": "只改 desc"}, h)
if code != 200 {
t.Fatalf("PUT 不带 clearances 应 200, got %d", code)
}
_, get4 := env.httpDo(t, "GET", "/api/v1/access/principals/"+key, nil, h)
cls4 := get4["clearances"].([]any)
if len(cls4) != 0 {
t.Errorf("未传 clearances 时应保留之前状态(空),got %v", cls4)
}
if get4["description"] != "只改 desc" {
t.Errorf("description 应被更新, got %v", get4["description"])
}
// 6) listPrincipals 应回显该主体的 clearance
_, list := env.httpDo(t, "GET", "/api/v1/access/principals", nil, h)
var found bool
for _, p := range list["principals"].([]any) {
m := p.(map[string]any)
if m["name"] == key {
if clsL := m["clearances"]; clsL == nil {
t.Errorf("listPrincipals 应回显 clearances, got nil")
}
found = true
}
}
if !found {
t.Errorf("listPrincipals 缺新建的 %s", key)
}
}
// TestIntegration_SetPrincipalClearance_MCP 修复 issue #7 方案 A:
// MCP set_principal_clearance 工具能写入;list_principals / get_principal 能读取。
func TestIntegration_SetPrincipalClearance_MCP(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
key := "test_mcp_clearance"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/access/principals/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/access/principals",
map[string]any{"name": key, "description": "MCP clearance 测试"}, h); code != 201 {
t.Fatalf("create principal failed: %d", code)
}
// 1) MCP set_principal_clearance
code, body := env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "1", "method": "tools/call",
"params": map[string]any{
"name": "set_principal_clearance",
"arguments": map[string]any{
"name": key,
"clearances": []string{"L0", "L1", "L2", "L3"},
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 应 200, got %d body=%v", code, body)
}
// 2) MCP get_principal 应回显
code, body = env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "2", "method": "tools/call",
"params": map[string]any{
"name": "get_principal",
"arguments": map[string]any{"name": key},
},
}, h)
if code != 200 {
t.Fatalf("get_principal 应 200, got %d", code)
}
result := body["result"].(map[string]any)
content := result["content"].([]any)
text := content[0].(map[string]any)["text"].(string)
if !strings.Contains(text, `"clearances"`) {
t.Errorf("get_principal 响应应含 clearances, got %s", text)
}
if !strings.Contains(text, `"L3"`) {
t.Errorf("get_principal 响应应含 L3, got %s", text)
}
// 3) MCP list_principals 应包含该主体
code, body = env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "3", "method": "tools/call",
"params": map[string]any{
"name": "list_principals",
"arguments": map[string]any{},
},
}, h)
if code != 200 {
t.Fatalf("list_principals 应 200, got %d", code)
}
result2 := body["result"].(map[string]any)
content2 := result2["content"].([]any)
text2 := content2[0].(map[string]any)["text"].(string)
if !strings.Contains(text2, key) {
t.Errorf("list_principals 应包含新建 %s, got %s", key, text2)
}
// 4) MCP 缺 name 应报错
code, body = env.httpDo(t, "POST", "/api/v1/mcp",
map[string]any{
"jsonrpc": "2.0", "id": "4", "method": "tools/call",
"params": map[string]any{
"name": "set_principal_clearance",
"arguments": map[string]any{
"clearances": []string{"L0"},
},
},
}, h)
if code != 200 {
t.Fatalf("MCP 错误应 200, got %d", code)
}
r4 := body["result"].(map[string]any)
c4 := r4["content"].([]any)
t4 := c4[0].(map[string]any)["text"].(string)
if !strings.Contains(t4, "name") {
t.Errorf("MCP 缺 name 应报错, got %s", t4)
}
}
// TestIntegration_PutClearances_Rest 顺带验证既有的
// `PUT /principals/:name/clearances` 端点仍然有效(用户不知道有这个端点)。
// 这是 issue #7 的关键发现:端点一直都在,只是用户认知里没有。
func TestIntegration_PutClearances_Rest(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
key := "test_legacy_clearance_path"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/access/principals/"+key, nil, h)
})
if code, _ := env.httpDo(t, "POST", "/api/v1/access/principals",
map[string]any{"name": key, "description": "测试旧端点"}, h); code != 201 {
t.Fatalf("create principal failed: %d", code)
}
// 用 PUT /principals/:name/clearances(既有的专用端点)
code, _ := env.httpDo(t, "PUT", "/api/v1/access/principals/"+key+"/clearances",
map[string]any{"markings": []string{"L0", "L2"}}, h)
if code != 200 {
t.Fatalf("PUT clearances 应 200, got %d", code)
}
// GET /principals/:name/clearances(既有只读端点)
_, get := env.httpDo(t, "GET", "/api/v1/access/principals/"+key+"/clearances", nil, h)
cls := get["clearances"].([]any)
if len(cls) != 2 {
t.Errorf("既有专用端点 GET 应 2 项, got %d", len(cls))
}
}
+28 -13
View File
@@ -67,7 +67,7 @@ func run() error {
if err := ensureAccessControlSchema(ctx, pool); err != nil {
log.Printf("[boot] 访问控制 schema 警告: %v", err)
}
if err := seedAccessControlDefaults(ctx, pool, cfg.IngestAPIKey); err != nil {
if err := seedAccessControlDefaults(ctx, pool); err != nil {
log.Printf("[boot] 访问控制种子警告: %v", err)
}
// Kinetic 层 ⑤Function builtin 函数同步
@@ -171,7 +171,7 @@ func registerRoutes(r *gin.Engine, a *app) {
api.GET("/auth/me", a.authMe)
api.POST("/auth/change-password", a.changePassword)
// 管理类接口(本体/实例/AI摄取),可配置 MANAGER_API_KEY
// 管理类接口(本体/实例/AI摄取):需 manager 主体(密码登录或 manager 的 api_key)
mgmt := api.Group("")
mgmt.Use(a.loginRequired(), a.managerAuth())
{
@@ -188,6 +188,9 @@ func registerRoutes(r *gin.Engine, a *app) {
// 数据分级(issue #5):类型级分级配置总览 + 实例生效分级批量重算(默认 dry_run)。
// 挂在本组而非 /objects 下,避免与 /objects/:type/:pk 参数路由冲突被抢占匹配。
ot.GET("/classification/config", a.classificationConfig)
// 管理员设置对象类型的分级配置(v1.3.0):之前只有 GET 没有 PUT,导致前端保存失败
// 「对象类型分级」路由按对象名(/object-types/:name/classification)放,方便前端「按类型编辑」
ot.PUT("/object-types/:name/classification", a.setObjectTypeClassification)
ot.POST("/classification/recompute", a.recomputeClassification)
ot.GET("/link-types", a.listLinkTypes)
@@ -288,7 +291,7 @@ func registerRoutes(r *gin.Engine, a *app) {
km.POST("/connections/extract", a.kmExtractConnections)
}
// 连接器接口(只读查询),可配置 CONNECTOR_API_KEY,供 WorkBuddy 等接入
// 连接器接口(只读查询):connector 主体已配置 api_key 时须在 X-API-Key 携带,供 WorkBuddy 等接入
conn := api.Group("/connector")
conn.Use(a.connectorAuth())
{
@@ -365,14 +368,14 @@ func (a *app) managerAuth() gin.HandlerFunc {
}
// loginRequired 强制要求已登录(cookie session 或 X-API-Key)。
// dev 模式(两个 API KEY env 都为空)→ 跳过,保持旧开发体验。
// 真实鉴权模式开启时,凡到达此中间件的请求必须带 session 或 API Key,否则 401。
// manager 主体尚未配置 api_key(全新库、seed 未运行)→ 跳过,便于首次引导。
// 真实鉴权模式(manager 已有 key)下,到达此中间件的请求必须带 session 或 API Key,否则 401。
// 注意:本中间件不区分角色(manager/ingest/connector 都可过);
// 角色门由 managerAuth / ingestOrManagerAuth 等下游中间件把控。
func (a *app) loginRequired() gin.HandlerFunc {
return func(c *gin.Context) {
// dev 模式保留旧体验:无人也能进(默认 manager)
if a.cfg.ManagerAPIKey == "" && a.cfg.ConnectorAPIKey == "" {
// manager 尚未配置密钥时保留开放体验:无人也能进(默认 manager)
if !a.managerKeySet() {
c.Next()
return
}
@@ -385,22 +388,34 @@ func (a *app) loginRequired() gin.HandlerFunc {
}
}
// connectorAuth 连接器入口鉴权:connector 主体已配置 api_key 时须在 X-API-Key(或 key 查询参数)
// 携带该 key;未配置 key 的部署则放行(兼容无密钥只读场景)。
func (a *app) connectorAuth() gin.HandlerFunc {
return func(c *gin.Context) {
if a.cfg.ConnectorAPIKey == "" {
key := c.GetHeader("X-API-Key")
if key == "" {
key = c.Query("key")
}
if key == "" {
if a.principalKeySet("connector") {
c.AbortWithStatusJSON(401, gin.H{"error": "连接器接口需要 X-API-Key"})
return
}
c.Next()
return
}
if c.GetHeader("X-API-Key") != a.cfg.ConnectorAPIKey && c.Query("key") != a.cfg.ConnectorAPIKey {
c.AbortWithStatusJSON(401, gin.H{"error": "需要 X-API-Key 连接器鉴权"})
var name string
if err := a.pool.QueryRow(c,
"SELECT name FROM principals WHERE name='connector' AND api_key=$1", key).Scan(&name); err == nil && name != "" {
c.Next()
return
}
c.Next()
c.AbortWithStatusJSON(401, gin.H{"error": "连接器密钥无效"})
}
}
// ingestOrManagerAuth 知识管理写接口鉴权:仅放行 manager 或 ingest 主体。
// ingest 主体由 MCP/agent 使用(持有 INGEST_API_KEY),可按需限定 clearance 与 grant。
// ingest 主体由 MCP/agent 使用(持有 seed 随机 key 或 UI 设置的 api_key),可按需限定 clearance 与 grant。
func (a *app) ingestOrManagerAuth() gin.HandlerFunc {
return func(c *gin.Context) {
p := a.principalFromRequest(c)
@@ -414,7 +429,7 @@ func (a *app) ingestOrManagerAuth() gin.HandlerFunc {
}
// mcpAuth MCP 端点鉴权:允许 manager/ingest/connector 调用;生产环境拒绝匿名 public。
// dev 模式(MANAGER_API_KEY 与 CONNECTOR_API_KEY 均为空)下 principalFromRequest 返回 manager,自然放行。
// manager 尚未配置 key(全新库)时 principalFromRequest 返回 manager,自然放行,便于首次引导。
func (a *app) mcpAuth() gin.HandlerFunc {
return func(c *gin.Context) {
p := a.principalFromRequest(c)
+2 -2
View File
@@ -137,7 +137,7 @@ func TestIntegration_SnapshotByTimestamp(t *testing.T) {
env.httpDo(t, "DELETE", "/api/v1/backups/"+strconv.FormatInt(snapID, 10), nil, h)
})
// 取快照的 created_at unix 时间戳
// 取快照的 created_at unix 时间戳(+1 防毫秒向下取整丢失)
pool, _ := initDB(context.Background(), testDSN())
defer pool.Close()
var createdUnix int64
@@ -148,7 +148,7 @@ func TestIntegration_SnapshotByTimestamp(t *testing.T) {
// 用 ts 头读:应见快照库
code, _ := env.httpDo(t, "GET", "/api/v1/connector/object-types",
nil, h,
map[string]string{"X-Snapshot-Ts": strconv.FormatInt(createdUnix, 10)})
map[string]string{"X-Snapshot-Ts": strconv.FormatInt(createdUnix+1, 10)})
if code != 200 {
t.Errorf("X-Snapshot-Ts 应能切库, got %d", code)
}
+1 -1
View File
@@ -126,7 +126,7 @@ Streamable HTTP / JSON-RPC 2.0;响应为 SSE 流(`event: message\ndata: {...
改完在连接器页「自定义连接器」点「信任」。
### ⚠️ 身份陷阱(必读)
- 主体:dev 模式无 key → 默认 `manager`;`X-Principal` 可直接指定;`X-API-Key` 命中 principals 表 → 该主体;否则按 `MANAGER_API_KEY`/`CONNECTOR_API_KEY` 映射。
- 主体:dev 模式无 key(manager 尚未配置 api_key 的全新库)→ 默认 `manager`;`X-Principal` 可直接指定;`X-API-Key` 命中 principals 表 → 该主体。所有内置主体密钥均由首次启动时随机 seed 生成,不再读取 .env。
- **写权限**仅 `manager` / `ingest`;只读用 `analyst-key-001`。
- **WorkBuddy MCP client 会自动注入 analyst 身份**,删掉 X-API-Key 或换 server name 都无效——要用 `ingest-key-001`(具备 manage 覆盖的 ingest 主体)才能跑 KM 写路径。
+19 -11
View File
@@ -427,15 +427,19 @@ async function saveEditPrincipal() {
} else if (editPrincipalForm.api_key) {
payload.api_key = editPrincipalForm.api_key
}
const resp = await api.updatePrincipal(editPrincipalForm.name, payload)
ElMessage.success('已保存')
dlgEditPrincipal.value = false
try {
const resp = await api.updatePrincipal(editPrincipalForm.name, payload)
ElMessage.success('已保存')
dlgEditPrincipal.value = false
loadPrincipals()
if (resp && resp.api_key) {
revealedKey.value = resp.api_key
revealPrincipal.value = editPrincipalForm.name
dlgRevealKey.value = true
}
} catch (e) {
ElMessage.error('保存失败:' + (e.message || e))
}
}
const dlgRevealKey = ref(false)
@@ -449,14 +453,18 @@ async function revealPrincipalKey(row) {
dlgRevealKey.value = true
}
async function regeneratePrincipalKey(row) {
await ElMessageBox.confirm(`重新生成 "${row.name}" 的 API Key?旧 key 立即失效。`, '确认', { type: 'warning' })
const resp = await api.updatePrincipal(row.name, { generate_api_key: true })
ElMessage.success('已重置')
loadPrincipals()
if (resp && resp.api_key) {
revealedKey.value = resp.api_key
revealPrincipal.value = row.name
dlgRevealKey.value = true
try {
await ElMessageBox.confirm(`重新生成 "${row.name}" 的 API Key?旧 key 立即失效。`, '确认', { type: 'warning' })
const resp = await api.updatePrincipal(row.name, { generate_api_key: true })
ElMessage.success('已重置')
loadPrincipals()
if (resp && resp.api_key) {
revealedKey.value = resp.api_key
revealPrincipal.value = row.name
dlgRevealKey.value = true
}
} catch (e) {
if (e !== 'cancel' && !(e && e.message === 'cancel')) ElMessage.error('重置失败:' + (e.message || e))
}
}
async function copyRevealedKey() {
+1 -1
View File
@@ -4,7 +4,7 @@
<el-alert type="info" :closable="false" show-icon style="margin-bottom:14px">
<template #title>本体即服务</template>
任何应用(含 WorkBuddy)可通过只读连接器 API 随时查询最新本体;配置 CONNECTOR_API_KEY 后需在请求头携带 X-API-Key。
任何应用(含 WorkBuddy)可通过只读连接器 API 随时查询最新本体;首次启动会自动为 connector 主体生成随机 api_key(写入 principals 表),之后所有请求须在请求头携带 `X-API-Key`(或 `key=` 查询参数)。密钥在 Access Control 页查看/重置。
</el-alert>
<div class="row main">