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]>
This commit is contained in:
adminandClaude Code committed 2026-10-17 12:14:47 +08:00
1 parent 1e0807ea7a
commit 25bbd15fd6
13 files changed
+293 -110

No files matched your search

+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)
}
}