3 Commits
Author SHA1 Message Date
adminandClaude Code 27d0e28703 docs(plan): 多本体/多租户设计标注为「仅规划,不执行」
上一提交 1e0807e 归档的 spec 补上状态行:用户 2026-10-17 确认多租户本身
不做,只作设计存档,不进实施计划、不排期、不写代码。补重启条件——用户
明确说「开始做多租户」时,先复核 §8 风险表(X-Principal 越权洞已于
v1.5.3 封堵)是否仍成立,再进 writing-plans。

Co-Authored-By: Claude Code <[email protected]>
2026-10-17 12:15:02 +08:00
adminandClaude Code 25bbd15fd6 fix(authz): 封堵 X-Principal 头越权洞(裸头即可取得 manager)
principalFromRequest 曾把客户端可任意设置的 X-Principal 请求头列为最高
优先级、且完全不校验地决定主体。任何能发 HTTP 请求的一方带一个
X-Principal: manager 即取得平台最高权限;managerAuth /
ingestOrManagerAuth / mcpAuth / connectorAuth 读路径过滤全部沦陷。
该头排在真实凭据之前,合法的低权限 key 配该头即提权。

修复:外部入口一律不认该头,主体只来自真实凭据。
- 新增 server/principal_ctx.go:主体挂在 *http.Request 的 context 上。
  context 由代码构造、网络请求携带不了,外部伪造不命中。
- callHandler / mcpCall 两处进程内自调用改走 context 注入。
  callConn 不动(v2 已透传调用方真实 api_key / session cookie)。
- review-kit 代理 mcp-review-proxy.js 的 CORS 允许头去掉 X-Principal:
  该代理是 Access-Control-Allow-Origin: * 且原本显式放行该头,
  任意网页 JS 可借它伪造身份(main.go 的 corsMiddleware 管不到这条路)。

不采用降优先级 / 回环 IP 白名单 / 内部签名头——三者都仍留下一条外部
可构造的提权路径。

测试:新增 server/xprincipal_authz_test.go 覆盖匿名伪造(managerAuth 401 /
ingestOrManagerAuth 403 / mcpAuth 401)、该头不覆盖已解析的真实主体、
真实 manager key 仍放行;集成测试 60 处 X-Principal: manager 测试捷径
改为查库取真实 api_key。变异检查确认 MCP 进程内路径确实依赖新注入。

顺带转绿既有的 TestIntegration_ClassificationFilter:共享测试库 5 个主体
均已配 api_key,connectorAuth 要求 X-API-Key 而该测试只带 X-Principal,
迁移后自然修复。

验证:go test ./server/... 与 go test -tags=integration ./server/... 全绿;
./build.sh 通过(server/reviewkit 是 //go:embed 的,需重新编译进二进制)。
server/ai 的 TestHeuristicA5 仍红,是仓库外硬编码 fixture 路径不存在,
与本次无关。

Co-Authored-By: Claude Code <[email protected]>
2026-10-17 12:14:47 +08:00
adminandClaude 1e0807ea7a docs(design): 多本体/多租户设计(每租户一套 schema + 1:1 隐式路由)
- 选型:多本体(schema-per-tenant),非行级 tenant_id
- 控制面(ontologies 表 + 管理页)留在默认租户 public,租户 schema 只装业务本体
- 主体↔租户 1:1,不带 ontology_id 时隐式落到家租户,替换原 ACL 名单方案
- 前置项:ctxPool 修 a.pool 全局替换的并发串味(零 handler 改动)
- migrate() 拆带版本号迁移段,启动按 schema_version 自动补跑
- 备份按租户切,snapshot_path 与 tenant_path 同句叠加;补表数完整性硬约束
- 记录现存越权洞:X-Principal 头无鉴权,多租户下会放大为跨租户洞

Co-Authored-By: Claude <[email protected]>
2026-10-17 11:39:07 +08:00
14 changed files with 563 additions and 110 deletions

No files matched your search

@@ -0,0 +1,270 @@
# 多本体 / 多租户设计
> 目标:一套部署跑若干个彼此隔离的本体,每个租户一套完整 schema。
> 生成时间:2026-10-17。上游讨论:2026-09-08 会话提出的「动态切 schema 的第二个用法:多本体」。
> 状态:**仅规划,不执行**(2026-10-17 用户确认)。本文档只作为设计存档,不进入实施计划、不排期、不写代码。
> 重启条件:用户明确说「开始做多租户」时,先复核 §8 风险表(尤其 `X-Principal` 越权洞)是否仍成立,再进 writing-plans。
## TL;DR
选**多本体(每租户一整套 schema)**,不是行级 `tenant_id`,也不只是分级/域。
- 隔离层:PostgreSQL schema,请求级 `SET LOCAL search_path` 切换,复用现有 `snapshot_router.go` 的 `dbRunner`/`txPool` 机制
- 控制面:租户注册表 + 管理页留在**默认租户 `public`**;租户 schema 只装业务本体
- 路由:主体与租户 **1:1**,请求不带 `ontology_id` 时隐式落到主体的「家租户」
- 结构同步:`migrate()` 拆成带版本号的迁移段,启动时按 `schema_version` 给落后的租户自动补跑
- 备份:每租户各备各的,快照层与租户层在同一条 `search_path` 上叠加
- 前端:只做「租户生死」管理页,不做切换器,不做跨租户检索
**历史数据零迁移**:现有 3000+ 实例原地留在 `public`,`public` 就是默认租户。
## 1. 数据模型
### 1.1 ontologies(控制面表,只存在于默认租户)
```sql
CREATE TABLE IF NOT EXISTS ontologies (
id TEXT PRIMARY KEY, -- 'alpha',同时是 schema 名后缀
schema_name TEXT NOT NULL, -- 'ontology_alpha';默认租户为 'public'
display_name TEXT NOT NULL,
home_principal TEXT NOT NULL, -- 家主体(1:1),指向 principals.name
schema_version INT NOT NULL DEFAULT 0, -- 该租户已应用到的迁移版本
status TEXT NOT NULL DEFAULT 'active', -- active | dropped
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_by TEXT NOT NULL DEFAULT '',
dropped_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_ontologies_home ON ontologies(home_principal);
CREATE INDEX IF NOT EXISTS idx_ontologies_status ON ontologies(status);
```
约束:
- `id` 只允许 `[a-z0-9_-]{1,32}`,全小写——它会拼进 schema 名,必须挡住注入
- `schema_name` 由 `id` 派生(`public` 除外),不单独自由输入
- **`public` 自己建成一条记录**(`id='public'`、`schema_name='public'`、`home_principal='manager'`),保证「家租户指向 public」和「家租户指向 alpha」走同一套逻辑,不留双分支
- 默认租户记录**不允许删除或改家主体**
### 1.2 principals 加一列
```sql
ALTER TABLE principals ADD COLUMN IF NOT EXISTS home_ontology TEXT NOT NULL DEFAULT 'public';
```
1:1 之后不再需要 ACL 名单表——「谁能进这个租户」就是这一列。上次讨论里的 `principals_allowed JSONB` 方案作废。
### 1.3 每个租户 schema 内的 schema_meta
```sql
CREATE TABLE IF NOT EXISTS schema_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- key='schema_version'
```
与 `public` 里那张 append-only 的 `schema_versions`(审计流水,与 `ontology_audit_log` 同点挂钩)**不是一回事**,后者不动。前者是「这个租户的结构到第几段了」,后者是「变更历史」,跨租户共享一份全局流水。
## 2. 请求路由
### 2.1 入口
```
HTTP: X-Ontology-Id: alpha (REST / 管理页 / MCP 透传)
MCP: arguments.ontology_id: "alpha" (可选;不传 = 主体家租户)
```
两条都支持,MCP 参数在 `callConn`/`mcpCall` 里翻译成内层请求的 `X-Ontology-Id` 头——和现有 `X-Snapshot-Id` 透传是同一处、同一写法。
### 2.2 ontologyMiddleware
挂在 `/api/v1` 组最前,与 `snapshotMiddleware` 并列:
```go
api.Use(a.snapshotMiddleware(), a.ontologyMiddleware())
```
五步:
1. **定租户**:无 `X-Ontology-Id` 头 → 取主体的 `home_ontology`(默认 `public`);有头 → 用头里的值
2. **定主体**:调 `a.principalFromRequest(c)`(既有单一入口,复用不违背设计)
3. **校验**:查 `ontologies`(**用真池查,不能被切 schema 影响**)
- 无记录 / `status='dropped'` → 404
- `home_principal != 调用主体` 且调用主体不是 `manager` → 403
- `manager` 可进任意 active 租户(运维/评审需要)
4. **切**:`BeginTx` → `SET LOCAL search_path TO <tenant>, public` → tx 挂进请求 context(见 §3)
5. **收尾**:`defer` 里 `c.IsAborted()` → rollback,否则 commit
### 2.3 中间件顺序的坑
`principalFromRequest` 现在由 `loginRequired`/`managerAuth` 调用,而 `ontologyMiddleware` 必须挂在它们**之前**(否则 managerAuth 查库就已经切到错租户了)。解法:`ontologyMiddleware` 自己调一次 `principalFromRequest`。
这之所以安全:它内部用 `a.pool` 解析 api_key,而此时请求 context 里**还没有 tx**(第 4 步才挂),`ctxPool` 会落到真池 → 查的是 `public.principals` → 正确。
### 2.4 MCP 侧
`callConn`(`handlers_mcp.go:1265`)已透传 `X-API-Key` 和 session cookie,加两行:
```go
if v := c.GetHeader("X-Ontology-Id"); v != "" {
req.Header.Set("X-Ontology-Id", v)
}
```
工具参数表给所有工具加可选 `ontology_id`;不传即主体家租户——**现有 MCP 客户端一行配置都不用改**。
新增 4 个管理工具(manager 限定):`list_ontologies` / `create_ontology` / `set_home_ontology` / `delete_ontology`。
## 3. 并发安全(前置项,必须先做)
### 3.1 现状缺陷
`snapshot_router.go` 的 `snapshotMiddleware` 这样切库:
```go
origDB := a.pool
a.pool = &txPool{tx: tx} // 改 app 结构体上的共享字段,全程无锁
defer func() { a.pool = origDB }()
```
两个并发请求:A 换成 `txPoolA`,B 又换成 `txPoolB`,A 的 handler 随后读 `a.pool` 拿到的是 **B 的事务**——跨请求串味。快照模式因为用得少、且全只读,撞上了不易发现;**多租户是每个请求都走这条路,必然踩**。
### 3.2 修法:ctxPool(零 handler 改动)
启动时**一次性**把 `a.pool` 设成永久的 `ctxPool`,此后永不改动:
```go
type ctxPool struct{ base *pgxpool.Pool }
func (p *ctxPool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok { return tx.Query(ctx, sql, args...) }
return p.base.Query(ctx, sql, args...)
}
// QueryRow / Exec / Begin / BeginTx / Close 同构
```
中间件把 tx 塞进请求 context:
```go
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), txKey{}, tx))
```
业务代码仍写 `a.pool.Query(c, sql, ...)`——`c` 是 `gin.Context`,实现 `context.Context`,其 `Value()` 会代理到请求 context → 自动命中事务。**几百个 handler 一个都不用改**,且天然并发安全。
`dbRunner` 接口保留(`txPool` 降级为内部类型或直接删除,由 §3.3 决定)。
### 3.3 snapshotMiddleware 一并改造
改造后快照中间件不再替换 `a.pool`,同样走 context 挂载。两个中间件叠加时:
```go
SET LOCAL search_path TO backups_<id>, <tenant>, public
```
一条语句搞定,顺序即优先级。
## 4. 迁移分段
### 4.1 现状
`migrate(ctx, p dbExec)`(`db.go:37`)是一整段 DDL 字符串 + 若干后置修复(`backfillMissingIRI`、seed),硬编码跑在 `public` 上。
### 4.2 目标
```go
type migration struct {
Version int
Name string
SQL string // 或 func(ctx context.Context, p dbExec) error
}
var migrations = []migration{
{Version: 1, Name: "schema_meta", SQL: `CREATE TABLE IF NOT EXISTS schema_meta(...)`},
{Version: 2, Name: "core_objects", SQL: `...object_types/properties/objects/links...`},
// …按现有 DDL 的自然边界切分,每段内部保持幂等
}
func (a *app) migrateSchema(ctx context.Context, db dbExec, upTo int) error
```
`migrate(ctx, p)` 保留为「跑全部段到 public」的薄封装,调用点不变。
### 4.3 只对默认租户执行的部分
`backfillMissingIRI` 和 `seedIfEmpty` 是**存量修复/演示种子**,不能对每个新租户跑:
- `backfillMissingIRI` → 迁移段的一种,只对已有数据的 schema 有意义
- `seedIfEmpty`(「合作企业」示例)→ 迁到 `initDB` 里对 `public` 单独调用
### 4.4 启动时自动补跑
```go
func (a *app) syncTenantSchemas(ctx context.Context) error {
// 1. 从 public.ontologies 列出所有 active 租户
// 2. 对每个租户读 schema_meta 的 schema_version
// 3. version < len(migrations) 的,补跑缺失段(逐租户独立事务)
// 4. 单个租户失败 → 记日志 + 该租户标记 degraded,继续处理其他
}
```
在 `initDB` 之后、`seedIfEmpty` 之后调用。失败**不阻断启动**——一个坏租户不该拖垮整台服务。
### 4.5 建租户
```
create_ontology(id, display_name, home_principal)
1. 校验 id 词法 + 未重名
2. CREATE SCHEMA ontology_<id>
3. 开事务 SET LOCAL search_path TO ontology_<id>, public → migrateSchema(upTo=len)
4. 事务提交后写 ontologies 记录
```
任一步失败 → `DROP SCHEMA` 回滚,不留半成品。
## 5. 备份 / 快照
### 5.1 语义
`backup_create` 作用于**当前租户**:只把该租户 schema 的全部表复制到 `backups_<id>`。默认租户(public)行为不变。
### 5.2 硬约束(会静默出错,必须防)
快照 schema 必须**完整包含源租户的全部表**。否则 `search_path TO backups_x, tenant_y, public` 在缺表时会**漏到下一级**,读出「一部分快照 + 一部分活库」的混合数据,且不报错。
在建快照时断言:源租户表数 == 快照表数,不等则拒绝创建并报错。
### 5.3 快照元数据
`backup_inspect` / `backup_list` 增加 `source_ontology` 字段(从 `backups.snapshot_runs` 读)。`switch_via` 提示文案补充 `X-Ontology-Id`。
### 5.4 reviewkit 工具链
`server/reviewkit/` 内嵌二进制 + reviewkit.go 要能接受并透传 `ontology_id`,否则对接核对会在默认租户上跑,结论失真。
## 6. 管理页(前端)
新增「多租户」tab,**只管生死**:
- 列表:名称 / 家主体 / 实例数 / 创建时间 / 结构版本 / 状态
- 操作:新建、改家主体、删除
- 实例数:管理 handler 里对每个 active 租户 schema 单独 `count`(租户数量级小,可接受;不做跨租户联合查询)
删除租户:`status='dropped'` 软标记 + 二次确认;`DROP SCHEMA` 单独一步(可保留 dropped 状态的 schema 数据,人工确认后再物理清)。参考现有 `objects.deleted` 的软删除做法。
## 7. 明确不做
- 跨租户联合查询 / 全景检索(跨 N 个 schema 联合分页,成本高且易错)
- 前端全局租户切换器(管理页之外,前端所有请求不带 `ontology_id`,各管各的)
- 行级 `tenant_id`(选了 schema-per-tenant 就没有这条路)
- 租户级对象类型模板/市场
- 跨租户物化、跨租户 AI 摄取
## 8. 风险与未决
| 项 | 说明 | 处置 |
|---|---|---|
| 迁移分段回归 | 现有 DDL 切段时切错边界,老租户结构不完整 | 切完在默认租户上验证表/列与切段前逐一对齐 |
| 串味 | §3.2 的 `ctxPool` 是所有后续工作的前置 | 单独一个 commit,先跑并发集成测试验证 |
| 快照表数断言 | §5.2 | 建快照时硬校验,不等即失败 |
| **`X-Principal` 头越权(现存洞,多租户会放大)** | `principalFromRequest`(`access_control.go:83`)把 `X-Principal` 头作为最高优先级且**完全无鉴权**地决定主体。任何请求 `X-Principal: manager` 即取得 manager 身份。多租户下再配一个 `X-Ontology-Id`,即可无凭据进入任意租户 | **多租户上线前必须先封**:外部入口一律不接受 `X-Principal` 头,该头只允许来自进程内自调用(`callHandler`/`mcpCall`,`handlers_mcp.go:1219/1246`)。建议同时清理进程内自调用改为在 context 里带主体 |
| 租户数量 | 每租户一整套 schema,25 张表 | 暂不设上限;上千租户时应评估「行级」或混合方案 |
+13
View File
@@ -18,6 +18,19 @@ AI 客户端在使用本平台过程中发现 bug 或有改进建议,**请提
## 版本历史
## [1.5.3] - 2026-10-17 X-Principal 头越权洞修复
**影响**:修复前,任何能发 HTTP 请求的一方带一个 `X-Principal: manager` 头即可取得平台最高权限——管理接口、知识库写接口、MCP 端点、连接器读路径的身份过滤全部沦陷,且该头排在真实凭据之前,合法低权限 key 配该头即提权。修复后主体只来自真实凭据(api_key / 会话 cookie),裸头一律按匿名处理。
**改动**:
- `principalFromRequest` 不再读取 `X-Principal` 请求头;最高优先级改为进程内注入的 request context,其后仍是会话 cookie → `principals.api_key` → dev 兜底,优先级链其余部分不变
- 新增 `withInjectedPrincipal` / `injectedPrincipal`(`server/principal_ctx.go`):MCP 的 `callHandler` / `mcpCall` 两处进程内自调用改在 `*http.Request` 的 context 上带主体。context 由代码构造、网络请求无法携带,故外部伪造不命中
- review-kit 代理 `mcp-review-proxy.js` 的 CORS 允许头去掉 `X-Principal`(此前为 `*` origin + 显式放行该头,任意网页 JS 可借该代理伪造身份)
- 新增 `server/xprincipal_authz_test.go`:覆盖匿名伪造(managerAuth 401 / ingestOrManagerAuth 403 / mcpAuth 401)、该头不覆盖已解析的真实主体、真实 manager key 仍放行三条链路
- 集成测试 60 处 `X-Principal: manager` 测试捷径改为查库取真实 api_key(`principalKey` / `authHeaderFor` helper)
**设计**:不采用「降优先级」「回环 IP 白名单」「内部签名头」——三者都保留了一条外部可构造的提权路径。多租户(每租户一套 schema)会把该洞放大成跨租户洞,故在多租户立项前先行封堵;多租户本身仍为「仅规划,不执行」。
## [1.5.2] - 2026-10-15 场景指南内置 + 扫描工具包内嵌
**影响**:AI 客户端接入本体后「怎么用」不再依赖外部资源——场景 SOP 由服务端工具直接下发,差距扫描器随二进制分发,对外部署零 git 依赖、零 skill 安装。
+7 -2
View File
@@ -73,14 +73,19 @@ func (a *Authz) AllowedMarking(marking string) bool {
// principalFromRequest 从请求头推断主体。
// 鉴权唯一来源是 principals 表的 api_key(首次启动由 seed 注入随机值,之后由 Access Control 页管理);
// 不再读取任何 .env 显式密钥。
// 优先级:X-Principal > cookie session > principals 表的 api_key(X-API-Key 头或 key 查询参数)。
// 优先级:进程内注入的 request context > cookie session > principals 表的 api_key(X-API-Key 头或 key 查询参数)。
//
// 未携带任何有效 key 时:
// - 若 manager 主体尚未配置 api_key(全新库、seed 未运行)→ 开放为 manager,便于首次引导;
// - 否则匿名回退 public(L0 只读)。
// 生产环境首次启动后 manager 必然已有随机 key,故真实鉴权默认生效。
//
// 2026-10-17 修复越权洞:原实现把 `X-Principal` 请求头列为最高优先级且完全不校验,
// 而该头客户端可任意设置 → 任何请求 `X-Principal: manager` 即取得平台最高权限。
// 该头已彻底移除;进程内自调用改走 request context(见 principal_ctx.go)。
func (a *app) principalFromRequest(c *gin.Context) string {
if p := strings.TrimSpace(c.GetHeader("X-Principal")); p != "" {
// 进程内自调用注入的主体(外部不可伪造)。
if p := injectedPrincipal(c.Request.Context()); p != "" {
return p
}
// cookie session(账号密码登录后写入)
+4 -4
View File
@@ -16,8 +16,8 @@ import (
// - 前端编辑「对象类型分级」保存按钮看似无反应(POST 到不存在的路由 → 404)
// - 后果:587 个打了 data_level 标签的实例是「裸属性」无法被分级引擎接管
func TestIntegration_SetObjectTypeClassification(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 用一个已有「真属性行」的类型,避免 setupTestEnv 新建的测试类型 properties 行为不同
// DataDemand 在本工作区有 64 个属性行(详见 docs/db/0910 schema)。
@@ -129,8 +129,8 @@ func TestIntegration_SetObjectTypeClassification(t *testing.T) {
// 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"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
const fixedType = "DataDemand"
t.Cleanup(func() {
+49 -49
View File
@@ -14,8 +14,8 @@ import (
// GET /ontology/meta:自描述 IRI 命名空间与依据标准。
func TestIntegration_OntologyMeta(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
code, body := env.httpDo(t, "GET", "/api/v1/ontology/meta", nil, h)
if code != 200 {
t.Fatalf("meta 应 200, got %d", code)
@@ -30,8 +30,8 @@ func TestIntegration_OntologyMeta(t *testing.T) {
// 创建类型后 GET 详情应带 iri = base_iri + "#" + api_name。
func TestIntegration_CreateObjectType_HasIRI(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h)
@@ -53,7 +53,7 @@ func TestIntegration_CreateObjectType_HasIRI(t *testing.T) {
// listObjectTypes 返回裸 JSON 数组(httpDo 解码进 map 会丢),须裸 http 读 body。
func TestIntegration_ListAndConnector_HasIRI(t *testing.T) {
env, a := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
key := env.typeKey
const propName = "echo_prop"
wantOT := "http://example.org/standard-ontology#" + key
@@ -76,7 +76,7 @@ func TestIntegration_ListAndConnector_HasIRI(t *testing.T) {
if err != nil {
t.Fatalf("req: %v", err)
}
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, err := env.srv.Client().Do(req)
if err != nil {
t.Fatalf("do: %v", err)
@@ -119,7 +119,7 @@ func TestIntegration_ListAndConnector_HasIRI(t *testing.T) {
}
// 3) 连接器视图应带 iri(测试库主体已配置 api_key 时 connectorAuth 要求 X-API-Key)
connH := map[string]string{"X-Principal": "manager"}
connH := authHeaderFor(t, a, "manager")
var apiKey string
_ = a.pool.QueryRow(context.Background(),
`SELECT api_key FROM principals WHERE name='manager' AND COALESCE(api_key,'')<>''`).Scan(&apiKey)
@@ -148,15 +148,15 @@ func TestIntegration_ListAndConnector_HasIRI(t *testing.T) {
// 导出端点:建类型+链接 → turtle 文本含两类三元组。
func TestIntegration_ExportTurtle(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "导出体"}, h)
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
@@ -186,8 +186,8 @@ func TestIntegration_ExportTurtle(t *testing.T) {
// 类型编辑(经 schemaAudit)应同步产生版本行,且 before/after 完整可查。
// 走只读端点 GET /ontology/versions(列表) + GET /ontology/versions/:version(详情)。
func TestIntegration_SchemaVersions(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "版本前"}, h)
@@ -237,14 +237,14 @@ func TestIntegration_SchemaVersions(t *testing.T) {
// 建版本端点前先验写入:schemaAudit 挂钩是否落 schema_versions。
func TestIntegration_SchemaVersionsWritten(t *testing.T) {
env, app := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": "写入验证"}, h)
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
var n int
err := app.pool.QueryRow(context.Background(),
err := a.pool.QueryRow(context.Background(),
`SELECT count(*) FROM schema_versions WHERE target_name=$1`, key).Scan(&n)
if err != nil {
t.Fatal(err)
@@ -256,8 +256,8 @@ func TestIntegration_SchemaVersionsWritten(t *testing.T) {
// 非法字符 api_name 在创建类型时被守卫拦截。
func TestIntegration_InvalidIRIName_Rejected(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
bad := "含 空格"
code, body := env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": bad, "display_name": "x"}, h)
@@ -268,8 +268,8 @@ func TestIntegration_InvalidIRIName_Rejected(t *testing.T) {
// 新 escaper 不再产出 \a/\v(上轮遗留:导出会被 rapper 拒绝)。
func TestIntegration_TurtleExportEscapesControlChars(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
if code, _ := env.httpDo(t, "POST", "/api/v1/ontology/object-types",
map[string]any{"api_name": key, "display_name": " 控制"}, h); code != 201 {
@@ -277,7 +277,7 @@ func TestIntegration_TurtleExportEscapesControlChars(t *testing.T) {
}
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
@@ -289,8 +289,8 @@ func TestIntegration_TurtleExportEscapesControlChars(t *testing.T) {
// 公理随 Turtle 导出为 OWL 公理(disjointWith / equivalentClass / inverseOf / FunctionalProperty)。
// dateOrder 是跨属性时序规则,OWL2 不可表达——不导出,运行期由 validateDateOrder 统一守约。
func TestIntegration_ExportIncludesAxioms(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key, other := env.typeKey, env.typeKey+"_o"
ltName := env.typeKey + "_lnk"
t.Cleanup(func() {
@@ -314,7 +314,7 @@ func TestIntegration_ExportIncludesAxioms(t *testing.T) {
}}, h)
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
@@ -339,8 +339,8 @@ func TestIntegration_ExportIncludesAxioms(t *testing.T) {
// 创建/读取公理回显(本任务只覆盖创建路径的写入回显;update 在任务 3 联调)。
func TestIntegration_AxiomsRoundTrip(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
// 任务 3 接入 schema 良构校验后,disjointWith/equivalentTo 引用的类型必须存在。
// 提前创建 Other / Alias 两个被引用类型。
@@ -388,8 +388,8 @@ func TestIntegration_AxiomsRoundTrip(t *testing.T) {
// 各项良构校验的可达性都靠此测试覆盖(任务 3 前 schema 校验尚未接通,全部应 400/合法)。
func TestIntegration_AxiomsWellFormed(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
keyA, keyB := env.typeKey, env.typeKey+"_b"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+keyA, nil, h)
@@ -454,11 +454,11 @@ func TestIntegration_AxiomsWellFormed(t *testing.T) {
// functionalLinks 边写入校验:同 source 第二次不同 target → 400;同 target 重设 → 201。
func TestIntegration_FunctionalLinkEnforced(t *testing.T) {
env, a := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
keyA, keyB, keyC := env.typeKey, env.typeKey+"_b", env.typeKey+"_c"
// 连接器接口(批量)在全库任意主体已配 api_key 时强制要求 X-API-Key。
// 测试库常处于 manager 已配 key 状态,带上以保通用。
connH := map[string]string{"X-Principal": "manager"}
connH := authHeaderFor(t, a, "manager")
var apiKey string
_ = a.pool.QueryRow(context.Background(),
`SELECT api_key FROM principals WHERE name='manager' AND COALESCE(api_key,'')<>''`).Scan(&apiKey)
@@ -515,8 +515,8 @@ func TestIntegration_FunctionalLinkEnforced(t *testing.T) {
// parent_id SubclassOf:基本读写、环校验、父子互斥、rdfs:subClassOf 导出。
func TestIntegration_ParentSubclassOf(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
root, child := env.typeKey, env.typeKey+"_c"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+root, nil, h)
@@ -570,7 +570,7 @@ func TestIntegration_ParentSubclassOf(t *testing.T) {
}
// 导出 rdfs:subClassOf
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
@@ -584,8 +584,8 @@ func TestIntegration_ParentSubclassOf(t *testing.T) {
// 修复前 bug:C 已 disjointWith:[B],PUT C {"parent":"B"} → 守卫只看空新公理 → 放行,
// 落库父子互斥矛盾(导出同对既发 rdfs:subClassOf 又发 owl:disjointWith)。
func TestIntegration_SetParentChecksExistingDisjoint(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
child, parent := env.typeKey, env.typeKey+"_b"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+child, nil, h)
@@ -623,8 +623,8 @@ func TestIntegration_SetParentChecksExistingDisjoint(t *testing.T) {
// dateOrder 在 applyObjectUpsert 路径上生效;validate_axioms=false 豁免。
func TestIntegration_DateOrderWriteCheck(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
// 先建类型,后加属性,最后挂公理(公理形状校验要求属性先存在)。
@@ -672,8 +672,8 @@ func TestIntegration_DateOrderWriteCheck(t *testing.T) {
// parent_id 三态契约回归:PUT 不带 parent 字段不应清空既有 parent。
// 修复前 bug:updateObjectType 无条件写 parent_id=$17 (nil → NULL),每次更新即清空。
func TestIntegration_ParentTriState_PreserveOnMissing(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
root, child := env.typeKey, env.typeKey+"_c"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+child, nil, h)
@@ -719,8 +719,8 @@ func TestIntegration_ParentTriState_PreserveOnMissing(t *testing.T) {
// COALESCE($16::jsonb, axioms) 永不落回 → 任何 PUT(如仅改名)静默洗掉公理。
// 规约:不带/null → 保持;显式 {} → 清空。与 parent 三态同款问题。
func TestIntegration_AxiomsTriState_PreserveOnMissing(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key, other := env.typeKey, env.typeKey+"_o"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h)
@@ -776,8 +776,8 @@ func TestIntegration_AxiomsTriState_PreserveOnMissing(t *testing.T) {
// 父声明属性 + 枚举;子继承(读路径合并)+ enum 校验闭包生效。
func TestIntegration_PropertyInheritance(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
root, child := env.typeKey, env.typeKey+"_c"
t.Cleanup(func() {
env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+child, nil, h)
@@ -864,7 +864,7 @@ func TestIntegration_PropertyInheritance(t *testing.T) {
// 步骤顺序利用 60s TTL 窗口,无需 sleep 即确定性覆盖"建子类型后闭包未即时生效"回归。
func TestIntegration_ParentEnumFreshCacheAfterCreate(t *testing.T) {
env, a := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
root, child := env.typeKey, env.typeKey+"_fc"
t.Cleanup(func() {
_, _ = a.pool.Exec(context.Background(), `DELETE FROM objects WHERE type_api_name=$1`, child)
@@ -899,8 +899,8 @@ func TestIntegration_ParentEnumFreshCacheAfterCreate(t *testing.T) {
// 多语标签:入参校验、读写回显、Turtle @tag 输出。
func TestIntegration_DisplayNameLang(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
// 非法 lang → 400
@@ -920,7 +920,7 @@ func TestIntegration_DisplayNameLang(t *testing.T) {
}
// Turtle 含 @tag
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
@@ -932,8 +932,8 @@ func TestIntegration_DisplayNameLang(t *testing.T) {
// uri data_type:写入校验 + xsd:anyURI 导出。
// 注:创建实例统一走 POST /api/v1/objects(type 在 body),无 /objects/{type} 创建路由。
func TestIntegration_URIDataType(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := env.typeKey
t.Cleanup(func() { env.httpDo(t, "DELETE", "/api/v1/ontology/object-types/"+key, nil, h) })
env.httpDo(t, "POST", "/api/v1/ontology/object-types",
@@ -952,7 +952,7 @@ func TestIntegration_URIDataType(t *testing.T) {
}
// 导出 xsd:anyURI
req, _ := http.NewRequest("GET", env.srv.URL+"/api/v1/ontology/export?format=turtle", nil)
req.Header.Set("X-Principal", "manager")
req.Header.Set("X-API-Key", principalKey(t, a, "manager"))
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
+4 -4
View File
@@ -1212,11 +1212,11 @@ func (a *app) mcpDispatchTool(c *gin.Context, name string, args map[string]inter
}
// callHandler 进程内直接调用本体管理 handler,绕过 HTTP 中间件(managerAuth 仅放行 manager),
// 由调用方 mcpDispatchTool 的 canWrite 统一放行 manager/ingest。X-Principal 透传以走正常鉴权链路。
// 由调用方 mcpDispatchTool 的 canWrite 统一放行 manager/ingest。主体经 request context 透传以走正常鉴权链路。
func (a *app) callHandler(h gin.HandlerFunc, params gin.Params, body []byte, principal string) (string, int) {
req := httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Principal", principal)
req = withInjectedPrincipal(req, principal)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = req
@@ -1234,7 +1234,7 @@ func optStr(m map[string]interface{}, k string) string {
return ""
}
// mcpCall 进程内把请求路由到 KM/管理 handler,并携带当前 MCP 主体身份(X-Principal),
// mcpCall 进程内把请求路由到 KM/管理 handler,并携带当前 MCP 主体身份(request context),
// 使 ingestOrManagerAuth 中间件能正确放行(manager/ingest),复用现有逻辑、零漂移。
func (a *app) mcpCall(method, path string, body []byte, principal string) (string, int) {
var reader io.Reader
@@ -1243,7 +1243,7 @@ func (a *app) mcpCall(method, path string, body []byte, principal string) (strin
}
req := httptest.NewRequest(method, path, reader)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Principal", principal)
req = withInjectedPrincipal(req, principal)
w := httptest.NewRecorder()
a.engine.ServeHTTP(w, req)
return w.Body.String(), w.Code
+19 -19
View File
@@ -139,9 +139,9 @@ func (e *testEnv) httpDo(t *testing.T, method, path string, body any, headers ma
// ---------- 1. 枚举写入校验(issue #5-①,含修复后的变量遮蔽 bug)----------
func TestIntegration_EnumValidation(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
key := env.typeKey
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
// 建类型 + 枚举属性
if code, body := env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
@@ -191,11 +191,11 @@ func TestIntegration_EnumValidation(t *testing.T) {
// ---------- 2. 分级过滤(issue #5-③④)----------
func TestIntegration_ClassificationFilter(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
key := env.typeKey
// 建类型(带分级)+ 枚举属性 + 插入 analyst clearance(L0,L1)
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
if code, _ := env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
"api_name": key, "display_name": "回归-分级过滤",
"classification_property": "level",
@@ -209,7 +209,7 @@ func TestIntegration_ClassificationFilter(t *testing.T) {
"enum_values": []string{"L0", "L1", "L2", "L3"},
}, h)
// 注入 analyst clearance:L0+L1(principal 名与 GET 时 X-Principal 一致)
// 注入 analyst clearance:L0+L1(principal 名与 GET 时带的 analyst api_key 对应主体一致)
pool, _ := initDB(context.Background(), testDSN())
defer pool.Close()
_, _ = pool.Exec(context.Background(),
@@ -236,7 +236,7 @@ func TestIntegration_ClassificationFilter(t *testing.T) {
// analyst(L0,L1) → 只见到 L0/L1
_, body = env.httpDo(t, "GET", "/api/v1/connector/objects/"+key+"?limit=50", nil,
map[string]string{"X-Principal": "analyst"})
authHeaderFor(t, a, "analyst"))
total := int(body["total"].(float64))
if total != 2 {
t.Errorf("analyst 应见 2 个, got %d, items=%v", total, body["items"])
@@ -251,7 +251,7 @@ func TestIntegration_ClassificationFilter(t *testing.T) {
// analyst 直取 L2 实例 → 404(fail-closed:不泄漏存在性)
code, _ := env.httpDo(t, "GET", "/api/v1/connector/object/"+key+"/a_l2", nil,
map[string]string{"X-Principal": "analyst"})
authHeaderFor(t, a, "analyst"))
if code != 404 {
t.Errorf("analyst 直取 L2 应 404, got %d", code)
}
@@ -260,9 +260,9 @@ func TestIntegration_ClassificationFilter(t *testing.T) {
// ---------- 3. 字段级分级脱敏(issue #5-②)----------
func TestIntegration_FieldSensitivity(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
key := env.typeKey
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
"api_name": key, "display_name": "回归-字段脱敏",
@@ -305,7 +305,7 @@ func TestIntegration_FieldSensitivity(t *testing.T) {
// analyst(L0,L1) → secret_id 应被 redact 为 ***
_, body = env.httpDo(t, "GET", "/api/v1/connector/object/"+key+"/u1", nil,
map[string]string{"X-Principal": "analyst"})
authHeaderFor(t, a, "analyst"))
props = body["properties"].(map[string]any)
if props["secret_id"] != "***" {
t.Errorf("analyst 应见 secret_id='***', got %v", props["secret_id"])
@@ -318,9 +318,9 @@ func TestIntegration_FieldSensitivity(t *testing.T) {
// ---------- 4. 删除 → 恢复关系边(issue #4)----------
func TestIntegration_RestoreEdges(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
key := env.typeKey
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
pool, _ := initDB(context.Background(), testDSN())
defer pool.Close()
@@ -385,9 +385,9 @@ func TestIntegration_RestoreEdges(t *testing.T) {
// ---------- 5. recompute 落库(issue #5-⑩)----------
func TestIntegration_RecomputeApply(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
key := env.typeKey
h := map[string]string{"X-Principal": "manager"}
h := authHeaderFor(t, a, "manager")
env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
"api_name": key, "display_name": "回归-recompute",
@@ -445,8 +445,8 @@ func TestIntegration_RecomputeApply(t *testing.T) {
// ---------- 6. 数据备份 (v1.3.0) 端到端:create → list → inspect → diff → download → delete ----------
func TestIntegration_BackupLifecycle(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 当前 public 的 objects 表应有内容(>0 行),diff 才有意义
pool, _ := initDB(context.Background(), testDSN())
@@ -562,7 +562,7 @@ func TestIntegration_BackupLifecycle(t *testing.T) {
// 7) connector 主体应被拒(managerAuth 中间件 → 401)
code, body = env.httpDo(t, "GET", "/api/v1/backups", nil,
map[string]string{"X-Principal": "connector"})
authHeaderFor(t, a, "connector"))
if code != 401 {
t.Errorf("非 manager 应被拒 401, got %d, body=%v", code, body)
}
@@ -581,8 +581,8 @@ func TestIntegration_BackupLifecycle(t *testing.T) {
// TestIntegration_BackupDiffAfterMutation 验证「改动前/后各打一份 → diff 可见」
// 这正是「敢操作」的工作流核心。
func TestIntegration_BackupDiffAfterMutation(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 创建测试类型 + 一个实例
env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
+6 -6
View File
@@ -11,8 +11,8 @@ import (
// 之前 PUT /object-types/:name 静默忽略 properties 字段,导致「已有类型补注册属性」无入口。
// 验证:properties 数组非空时被 upsert(同名属性更新元数据,新名属性新增)。
func TestIntegration_UpdateObjectType_MergesProperties(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 用 setupTestEnv 已建的类型(test_UpdateMergeProp),保证隔离
key := "test_UpdateMergeProp"
@@ -96,8 +96,8 @@ func TestIntegration_UpdateObjectType_MergesProperties(t *testing.T) {
// 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"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := "test_AddPropertyMCP"
t.Cleanup(func() {
@@ -174,8 +174,8 @@ func TestIntegration_AddObjectTypeProperty_MCP(t *testing.T) {
// 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"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := "test_UpdateOTMCP"
t.Cleanup(func() {
+6 -6
View File
@@ -13,8 +13,8 @@ import (
// 验证: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"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 用一个非内置主体(避免污染 manager seed)
key := "test_principal_clearance"
@@ -102,8 +102,8 @@ func TestIntegration_UpdatePrincipal_Clearances(t *testing.T) {
// 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"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := "test_mcp_clearance"
t.Cleanup(func() {
@@ -197,8 +197,8 @@ func TestIntegration_SetPrincipalClearance_MCP(t *testing.T) {
// `PUT /principals/:name/clearances` 端点仍然有效(用户不知道有这个端点)。
// 这是 issue #7 的关键发现:端点一直都在,只是用户认知里没有。
func TestIntegration_PutClearances_Rest(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := "test_legacy_clearance_path"
t.Cleanup(func() {
+9 -9
View File
@@ -135,14 +135,14 @@ func seedConnectorForTest(t *testing.T) string {
// get_object_types / get_facets)一律以 connector 主体执行——manager 走
// MCP 也只能看到 connector clearance(L0-L2)下的数据,违反 v1.2.0 「manager 不受影响」。
//
// 新行为:callConn 接受 principal 参数,内层请求同时注入
// X-API-Key=<connector>(让 connectorAuth 放行)+ X-Principal=<实际 caller>
// 让 principalFromRequest 走 X-Principal 分支,读 filter 按真实身份工作。
// 新行为:callConn 透传调用方真实 X-API-Key / session cookie,内层 principalFromRequest
// 自然解析到调用方主体,读 filter 按真实身份工作。
// (2026-10-17 变更:此前内层注入 `X-Principal` 头,该头可被外部伪造,已改为透传真实 key。)
func TestIntegration_MCPRead_RespectsPrincipal(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
seedConnectorForTest(t)
hMgr := map[string]string{"X-Principal": "manager"}
hMgr := authHeaderFor(t, a, "manager")
// 建一个含 L0/L1/L3 三档的测试类型 + 3 个实例
key := "test_mcp_read_principal"
@@ -222,10 +222,10 @@ func TestIntegration_MCPRead_RespectsPrincipal(t *testing.T) {
// TestIntegration_MCPRead_QueryRelatedPrincipal 通过 MCP /api/v1/mcp 端点
// 验证 callConn 修复:manager 走 query_related 应能见 L3,connector 只能见 L0。
func TestIntegration_MCPRead_QueryRelatedPrincipal(t *testing.T) {
env, _ := setupTestEnv(t)
env, a := setupTestEnv(t)
seedConnectorForTest(t)
hMgr := map[string]string{"X-Principal": "manager"}
hMgr := authHeaderFor(t, a, "manager")
key := "test_mcp_query_related"
t.Cleanup(func() {
@@ -297,8 +297,8 @@ func TestIntegration_MCPRead_QueryRelatedPrincipal(t *testing.T) {
// PUT /access/principals/:name 只传 description 不传 api_key 时,响应 has_api_key
// 应反映 DB 真实状态,而非误报 false。
func TestIntegration_UpdatePrincipal_NotTouchKeyHasAPIEchoTrue(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
key := "test_not_touch_key"
t.Cleanup(func() {
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"context"
"net/http"
"strings"
)
// 进程内主体传递:修复 X-Principal 头越权洞(2026-10-17)。
//
// 背景:principalFromRequest 曾把客户端可任意设置的 `X-Principal` 请求头作为最高优先级、
// 完全无鉴权地决定主体。任何 HTTP 客户端带 `X-Principal: manager` 即取得平台最高权限。
//
// 本文件提供进程内自调用(callHandler / mcpCall)传递当前主体的唯一通道:
// 主体挂在 *http.Request 的 context 上,而非 HTTP 头。context 由代码构造、
// 网络请求无法携带,故外部伪造不可能命中。
//
// 严禁改回「设 X-Principal 头」——那正是被封掉的洞。
// principalCtxKey 私有类型,避免与外部包/未来 context key 撞名。
type principalCtxKey struct{}
// withInjectedPrincipal 返回一个携带指定主体的 request 副本(原 request 不变)。
// 主体为空时原样返回,调用方可无条件套用。
func withInjectedPrincipal(req *http.Request, principal string) *http.Request {
p := strings.TrimSpace(principal)
if req == nil || p == "" {
return req
}
return req.WithContext(context.WithValue(req.Context(), principalCtxKey{}, p))
}
// injectedPrincipal 读出进程内注入的主体;外部请求恒为空串。
func injectedPrincipal(ctx context.Context) string {
if ctx == nil {
return ""
}
p, _ := ctx.Value(principalCtxKey{}).(string)
return strings.TrimSpace(p)
}
+2 -2
View File
@@ -46,7 +46,7 @@ function sendCors(res, status, body, type = 'application/json') {
'Content-Type': type,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, X-Principal, Accept',
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, Accept',
'Access-Control-Max-Age': '86400',
});
res.end(body);
@@ -71,7 +71,7 @@ function proxyToTarget(req, res) {
const headers = { ...proxyRes.headers };
headers['access-control-allow-origin'] = '*';
headers['access-control-allow-methods'] = 'GET, POST, OPTIONS';
headers['access-control-allow-headers'] = 'Content-Type, X-API-Key, X-Principal, Accept';
headers['access-control-allow-headers'] = 'Content-Type, X-API-Key, Accept';
res.writeHead(proxyRes.statusCode, headers);
proxyRes.pipe(res); // 流式透传,SSE 也能正常转发
});
+9 -9
View File
@@ -15,8 +15,8 @@ import (
// 3) 写路径带快照头:直接 403(不改活库、不污染事务)
// 4) 同事务内 search_path 不影响 information_schema(catalog 表独立)
func TestIntegration_SnapshotRouter(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
// 1) 建一个测试类型 + 一个实例(作为「快照前」状态)
env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
@@ -64,7 +64,7 @@ func TestIntegration_SnapshotRouter(t *testing.T) {
// 5) 快照头读:应见 before=v=1、无 after(快照取的是改前那一刻)
_, snapBody := env.httpDo(t, "GET", "/api/v1/connector/objects/"+env.typeKey+"?limit=50",
nil, h,
map[string]string{"X-Principal": "manager", "X-Snapshot-Id": strconv.FormatInt(snapID, 10)})
map[string]string{"X-Snapshot-Id": strconv.FormatInt(snapID, 10)})
snapItems, _ := snapBody["items"].([]any)
snapSet := map[string]string{}
for _, it := range snapItems {
@@ -97,8 +97,8 @@ func TestIntegration_SnapshotRouter(t *testing.T) {
// TestIntegration_SnapshotSearchPathPersist 验证 search_path 不污染下一个请求:
// - 跑完一个 snapshot 请求后,下一个活库请求仍走 public
func TestIntegration_SnapshotSearchPathPersist(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
env.httpDo(t, "POST", "/api/v1/ontology/object-types", map[string]any{
"api_name": env.typeKey, "display_name": "persist-test",
@@ -127,8 +127,8 @@ func TestIntegration_SnapshotSearchPathPersist(t *testing.T) {
// TestIntegration_SnapshotByTimestamp 验证 X-Snapshot-Ts 也能切库
func TestIntegration_SnapshotByTimestamp(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
_, body := env.httpDo(t, "POST", "/api/v1/backups",
map[string]any{"name": uniqSnapshotName(t)}, h)
@@ -156,8 +156,8 @@ func TestIntegration_SnapshotByTimestamp(t *testing.T) {
// TestIntegration_SnapshotDeleteCleansSchema 验证 delete 真清掉对应 schema
func TestIntegration_SnapshotDeleteCleansSchema(t *testing.T) {
env, _ := setupTestEnv(t)
h := map[string]string{"X-Principal": "manager"}
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
_, body := env.httpDo(t, "POST", "/api/v1/backups",
map[string]any{"name": uniqSnapshotName(t)}, h)
+125
View File
@@ -0,0 +1,125 @@
//go:build integration
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"testing"
)
// principalKey 返回某主体在共享测试库里的真实 api_key。
// 历史测试用 `X-Principal: manager` 头当捷径,该头已于 2026-10-17 封禁(外部可伪造 → 越权),
// 统一改走真实凭据。
func principalKey(t *testing.T, a *app, principal string) string {
t.Helper()
var key string
err := a.pool.QueryRow(context.Background(),
`SELECT api_key FROM principals WHERE name=$1 AND COALESCE(api_key,'')<>''`, principal).Scan(&key)
if err != nil || key == "" {
t.Fatalf("测试库缺少主体 %s 的 api_key(err=%v);请先跑 seedAccessControlDefaults 或 issue8 的 seed", principal, err)
}
return key
}
// authHeaderFor 同 principalKey,但返回 env.httpDo 用的 header map。
func authHeaderFor(t *testing.T, a *app, principal string) map[string]string {
t.Helper()
return map[string]string{"X-API-Key": principalKey(t, a, principal)}
}
// doRaw 发一条不带 JSON 解码的请求(部分端点返回非 JSON)。
func (e *testEnv) doRaw(t *testing.T, method, path string, headers map[string]string) (int, []byte) {
t.Helper()
req, err := http.NewRequest(method, e.srv.URL+path, nil)
if err != nil {
t.Fatalf("req: %v", err)
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := e.srv.Client().Do(req)
if err != nil {
t.Fatalf("do: %v", err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
func postMCP(t *testing.T, e *testEnv, headers map[string]string) (int, map[string]any) {
t.Helper()
body, _ := json.Marshal(map[string]any{
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "t", "version": "1"}},
})
req, err := http.NewRequest("POST", e.srv.URL+"/api/v1/mcp", bytes.NewReader(body))
if err != nil {
t.Fatalf("req: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := e.srv.Client().Do(req)
if err != nil {
t.Fatalf("do: %v", err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
var out map[string]any
_ = json.Unmarshal(raw, &out)
return resp.StatusCode, out
}
// TestXPrincipal_AnonymousForgeRejected 断言:匿名请求伪造 X-Principal: manager 不得取得 manager 身份。
// 覆盖 managerAuth(401) / ingestOrManagerAuth(403) / mcpAuth(401) 三条鉴权链路。
func TestXPrincipal_AnonymousForgeRejected(t *testing.T) {
env, a := setupTestEnv(t)
if !a.managerKeySet() {
t.Skip("共享测试库 manager 尚未配置 api_key(dev 开放模式),无法验证真实鉴权")
}
forged := map[string]string{"X-Principal": "manager"}
if code, _ := env.httpDo(t, "GET", "/api/v1/ontology/object-types", nil, forged); code != 401 {
t.Errorf("managerAuth: 匿名伪造 X-Principal 应 401, got %d", code)
}
if code, _ := env.httpDo(t, "GET", "/api/v1/km/tree", nil, forged); code != 403 {
t.Errorf("ingestOrManagerAuth: 匿名伪造 X-Principal 应 403, got %d", code)
}
if code, _ := postMCP(t, env, forged); code != 401 {
t.Errorf("mcpAuth: 匿名伪造 X-Principal 应 401, got %d", code)
}
}
// TestXPrincipal_DoesNotOverrideRealCredential 断言:X-Principal 不得覆盖已解析出的真实主体。
// 低权限主体的合法 key + X-Principal: manager 仍应被 managerAuth 拒。
func TestXPrincipal_DoesNotOverrideRealCredential(t *testing.T) {
env, a := setupTestEnv(t)
analyst := authHeaderFor(t, a, "analyst")
analyst["X-Principal"] = "manager"
if code, _ := env.httpDo(t, "GET", "/api/v1/ontology/object-types", nil, analyst); code != 401 {
t.Errorf("analyst key + X-Principal: manager 应仍被 managerAuth 拒(401), got %d", code)
}
if code, _ := env.httpDo(t, "GET", "/api/v1/km/tree", nil, analyst); code != 403 {
t.Errorf("analyst key + X-Principal: manager 应仍被 ingestOrManagerAuth 拒(403), got %d", code)
}
}
// TestXPrincipal_RealCredentialStillWorks 反向断言:换成真实 manager key 后同一端点放行,
// 确保上一条不是「因为端点坏了才通过」。
func TestXPrincipal_RealCredentialStillWorks(t *testing.T) {
env, a := setupTestEnv(t)
h := authHeaderFor(t, a, "manager")
if code, _ := env.httpDo(t, "GET", "/api/v1/ontology/object-types", nil, h); code != 200 {
t.Errorf("manager 真实 key 应放行 managerAuth, got %d", code)
}
if code, _ := env.httpDo(t, "GET", "/api/v1/km/tree", nil, h); code != 200 {
t.Errorf("manager 真实 key 应放行 ingestOrManagerAuth, got %d", code)
}
}