From 32c7074f4131c3f2594c0f6227a424bc60ff64fd Mon Sep 17 00:00:00 2001 From: Zhero & Miku Date: Wed, 25 Nov 2026 10:47:53 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(kb):=20=E4=B8=8D=E5=86=8D=E6=8C=89?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E5=8F=B0=E4=BC=A0=E8=BE=93=E5=BD=A2=E6=80=81?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=20API=20Key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除 KBBindingSnapshot 的 secret_entry_allowed 能力位与服务端 catalog/save 的 KB 传输门禁 - 非 HTTPS 控制台保留明文传输提示,但不再阻断 Key 录入 - 保留 QA AI 严格 HTTPS/回环校验、管理员认证、写意图头与 Key 不回显 - 补齐明文 HTTP 页面与服务端写入回归测试,同步运行手册和 CHANGELOG --- .env.example | 3 +- CHANGELOG.md | 18 +++ compose.yaml | 2 +- docs/OPERATIONS_RUNBOOK.md | 8 +- internal/httpapi/kb_bindings.go | 11 -- internal/httpapi/kb_bindings_test.go | 142 ++++++++-------------- internal/httpapi/secret_transport.go | 63 +--------- internal/httpapi/secret_transport_test.go | 73 ----------- internal/httpapi/server.go | 4 +- web/src/KnowledgeBaseBinding.test.tsx | 82 +++++++------ web/src/KnowledgeBaseBinding.tsx | 23 +--- web/src/knowledgeBaseBindings.test.ts | 13 +- web/src/knowledgeBaseBindings.ts | 5 - web/src/secureEntry.ts | 6 +- 14 files changed, 131 insertions(+), 322 deletions(-) diff --git a/.env.example b/.env.example index 2eb1199..ec54654 100644 --- a/.env.example +++ b/.env.example @@ -28,8 +28,7 @@ QA_AI_MASTER_KEY_FILE= # 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。 WEKNORA_BINDING_MASTER_KEY_FILE= # 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。 -# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。 -# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。 +# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。 WEKNORA_ALLOW_PRIVATE_HTTP=false # Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only. QA_AI_DNS_OVER_TLS= diff --git a/CHANGELOG.md b/CHANGELOG.md index cd2f89f..923bd3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key) + +### Fixed + +- **非 HTTPS 控制台仍无法录入 API Key**:页面删除 `secret_entry_allowed` 能力位与 + `secure`/`keyEntryBlocked` 传输判定,服务端删除 KB 专用的 + `secretTransportAllowedForPrivateConsole` 写侧校验。管理员在任意同源控制台都能录入/ + 更换 Key,不再出现「可输入但保存 400」的半修复。 +- **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的 + API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。 + +### Changed + +- `WEKNORA_ALLOW_PRIVATE_HTTP` 仅控制治理 API/worker 访问同网段 http 目标,不再决定 + 控制台密钥录入。问答 AI 模型密钥仍走严格 HTTPS/回环校验;管理员、`X-Governance-Action` + 写意图与 Key 不回显边界不变。Web 与 API 是独立镜像,须同批次发布/回滚:旧 Web 对新 + API 会禁用录入,新 Web 对旧 API 仍会被 400 拒绝。 + ## 开发快照 0.1.421(负责人手动切换需求状态) - 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。 diff --git a/compose.yaml b/compose.yaml index b5007cf..e9a47b8 100644 --- a/compose.yaml +++ b/compose.yaml @@ -69,7 +69,7 @@ services: # 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。 WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}" # 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/ - # 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。 + # 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。 WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}" QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}" QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}" diff --git a/docs/OPERATIONS_RUNBOOK.md b/docs/OPERATIONS_RUNBOOK.md index a0adc3e..56c29b4 100644 --- a/docs/OPERATIONS_RUNBOOK.md +++ b/docs/OPERATIONS_RUNBOOK.md @@ -70,13 +70,7 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍 应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。 -**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET -`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、 -`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以 -录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台 -自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传 -`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。 -先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。 +**页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。 **四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) / 密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」; diff --git a/internal/httpapi/kb_bindings.go b/internal/httpapi/kb_bindings.go index d67fcc6..fa6f1a8 100644 --- a/internal/httpapi/kb_bindings.go +++ b/internal/httpapi/kb_bindings.go @@ -37,9 +37,6 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ "environments": views, "storage_ready": storageReady, - // The page cannot test the server's transport rule from the browser URL - // alone (a TLS proxy and an untrusted proxy look identical there). - "secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP), }}) } @@ -62,10 +59,6 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"}) return } - if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"}) - return - } catalog, err := config.KBBindings.Catalog(r.Context(), env, input) if err != nil { writeKBBindingError(w, err) @@ -93,10 +86,6 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"}) return } - if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"}) - return - } view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC()) if err != nil { writeKBBindingError(w, err) diff --git a/internal/httpapi/kb_bindings_test.go b/internal/httpapi/kb_bindings_test.go index 498b41f..e331726 100644 --- a/internal/httpapi/kb_bindings_test.go +++ b/internal/httpapi/kb_bindings_test.go @@ -3,7 +3,6 @@ package httpapi import ( "bytes" "context" - "encoding/json" "net/http" "net/http/httptest" "strings" @@ -88,34 +87,37 @@ func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) { } } -func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) { - store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}} +func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) { + store := &fakeKBBindings{ + views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}, + catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}, + } config := kbBindingHandler(t, store) - body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}` - request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body)) + catalogBody := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}` + request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody)) request.SetPathValue("environment", "test") request.Header.Set("X-Governance-Action", "kb-bindings") response := httptest.NewRecorder() config.handleKBBindingCatalog(response, request) - if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") { - t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String()) - } - - request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body)) - request.SetPathValue("environment", "test") - request.Header.Set("X-Governance-Action", "kb-bindings") - response = httptest.NewRecorder() - config.handleKBBindingCatalog(response, request) if response.Code != http.StatusOK { - t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String()) - } - var payload map[string]any - if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { - t.Fatal(err) + t.Fatalf("plain HTTP catalog status=%d body=%s", response.Code, response.Body.String()) } if strings.Contains(response.Body.String(), "typed-key") { t.Fatal("catalog response echoed the typed key") } + + saveBody := `{"base_revision":1,"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}` + request = httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody)) + request.SetPathValue("environment", "test") + request.Header.Set("X-Governance-Action", "kb-bindings") + response = httptest.NewRecorder() + config.handleKBBindingSave(response, request) + if response.Code != http.StatusOK { + t.Fatalf("plain HTTP save status=%d body=%s", response.Code, response.Body.String()) + } + if store.lastSave.APIKey != "typed-key" { + t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey) + } } func TestKBBindingWritesAreAdminOnly(t *testing.T) { @@ -129,95 +131,53 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) { } } -func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) { +func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) { store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}} - for _, tc := range []struct { - name string - host string - allow bool - want bool - }{ - {name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true}, - {name: "private console without toggle", host: "172.29.151.11:28188", want: false}, - {name: "loopback console", host: "127.0.0.1:8080", want: true}, - } { - t.Run(tc.name, func(t *testing.T) { - config := kbBindingHandler(t, store) - config.WeKnoraAllowPrivateHTTP = tc.allow - request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil) - request.Host = tc.host - response := httptest.NewRecorder() - config.handleKBBindings(response, request) - if response.Code != http.StatusOK { - t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String()) - } - var payload struct { - Data struct { - SecretEntryAllowed bool `json:"secret_entry_allowed"` - } `json:"data"` - } - if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { - t.Fatal(err) - } - if payload.Data.SecretEntryAllowed != tc.want { - t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want) - } - }) + config := kbBindingHandler(t, store) + request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil) + request.Host = "172.29.151.11:28188" + response := httptest.NewRecorder() + config.handleKBBindings(response, request) + if response.Code != http.StatusOK { + t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), "secret_entry_allowed") { + t.Fatalf("read response still reports the removed capability: %s", response.Body.String()) } } -func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) { +func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) { const ( - privateHost = "172.29.151.11:28188" - origin = "http://172.29.151.11:28188" + saveBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}` + catalogBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}` ) store := &fakeKBBindings{ views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}, catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}, } - body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}` + for _, allow := range []bool{false, true} { + config := kbBindingHandler(t, store) + config.WeKnoraAllowPrivateHTTP = allow - save := func(config *Config) *httptest.ResponseRecorder { - request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body)) - request.Host = privateHost + request := httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody)) request.SetPathValue("environment", "test") request.Header.Set("X-Governance-Action", "kb-bindings") - request.Header.Set("Sec-Fetch-Site", "same-origin") - request.Header.Set("Origin", origin) response := httptest.NewRecorder() config.handleKBBindingSave(response, request) - return response - } - catalog := func(config *Config) *httptest.ResponseRecorder { - request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog", - bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`)) - request.Host = privateHost + if response.Code != http.StatusOK { + t.Fatalf("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String()) + } + if store.lastSave.APIKey != "typed-key" { + t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey) + } + + request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody)) request.SetPathValue("environment", "test") request.Header.Set("X-Governance-Action", "kb-bindings") - request.Header.Set("Sec-Fetch-Site", "same-origin") - request.Header.Set("Origin", origin) - response := httptest.NewRecorder() + response = httptest.NewRecorder() config.handleKBBindingCatalog(response, request) - return response - } - - enabled := kbBindingHandler(t, store) - enabled.WeKnoraAllowPrivateHTTP = true - if response := save(enabled); response.Code != http.StatusOK { - t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String()) - } - if store.lastSave.APIKey != "typed-key" { - t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey) - } - if response := catalog(enabled); response.Code != http.StatusOK { - t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String()) - } - - disabled := kbBindingHandler(t, store) - if response := save(disabled); response.Code != http.StatusBadRequest { - t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String()) - } - if response := catalog(disabled); response.Code != http.StatusBadRequest { - t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String()) + if response.Code != http.StatusOK { + t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String()) + } } } diff --git a/internal/httpapi/secret_transport.go b/internal/httpapi/secret_transport.go index 08a6ef8..a7fef33 100644 --- a/internal/httpapi/secret_transport.go +++ b/internal/httpapi/secret_transport.go @@ -7,11 +7,11 @@ import ( "strings" ) -// secretTransportAllowed is the single rule for typing a secret into the -// console: a real TLS connection, a loopback request, or a same-origin HTTPS -// request that a trusted reverse proxy forwarded. The browser's origin scheme -// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit -// a key even if it spoofs X-Forwarded-Proto. +// secretTransportAllowed is the strict rule for QA AI model keys: a real TLS +// connection, a loopback request, or a same-origin HTTPS request that a trusted +// reverse proxy forwarded. The browser's origin scheme must agree, so a +// plain-HTTP page behind a misconfigured proxy cannot submit a key even if it +// spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it. func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool { if r.TLS != nil { return true @@ -26,47 +26,6 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool { return false } -// secretTransportAllowedForPrivateConsole additionally accepts a same-origin -// fetch from the operator console itself when it is served over plain http on a -// private address. That is the only non-TLS shape this deployment needs, and it -// still requires an exact Origin/Host match. It deliberately does not require -// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an -// http console on a private address never carries that header. -func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool { - if secretTransportAllowed(r, trustTLSProxy) { - return true - } - if !allowPrivateHTTP { - return false - } - origin := strings.TrimSpace(r.Header.Get("Origin")) - if origin == "" { - return false - } - parsed, err := url.Parse(origin) - if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) { - return false - } - host := parsed.Hostname() - return privateAddressHost(host) -} - -// consoleSecretEntryAllowed mirrors the transports the write gates accept, but -// it cannot simply call secretTransportAllowed: that gate guards a write and -// therefore insists on a same-origin Origin header, which a GET navigation -// never sends. Trusting X-Forwarded-Proto alone on a read is safe because -// browsers cannot set it and the deployment already declares the proxy -// trusted; a forged header still cannot make the write gate accept anything. -func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool { - if r.TLS != nil || loopbackHost(r.Host) { - return true - } - if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" { - return true - } - return allowPrivateHTTP && privateAddressHost(r.Host) -} - // requestHostname strips the optional port and IPv6 brackets. Brackets come // off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their // ported forms are not address spellings the server or a browser ever emits, @@ -103,15 +62,3 @@ func loopbackHost(host string) bool { ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } - -// privateAddressHost accepts loopback and private addresses. Names other than -// localhost are rejected because the deployment toggle is about addresses, -// not about trusting whatever DNS resolves to. -func privateAddressHost(host string) bool { - host = requestHostname(host) - if strings.EqualFold(host, "localhost") { - return true - } - ip := net.ParseIP(host) - return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()) -} diff --git a/internal/httpapi/secret_transport_test.go b/internal/httpapi/secret_transport_test.go index 16c6292..b45bf84 100644 --- a/internal/httpapi/secret_transport_test.go +++ b/internal/httpapi/secret_transport_test.go @@ -1,60 +1,11 @@ package httpapi import ( - "crypto/tls" "net/http" "net/http/httptest" "testing" ) -func TestConsoleSecretEntryAllowedMatrix(t *testing.T) { - cases := []struct { - name string - host string - tls bool - xfp string - trust bool - allow bool - want bool - }{ - {name: "direct TLS", host: "console.example", tls: true, want: true}, - {name: "loopback name", host: "localhost:8080", want: true}, - {name: "loopback v4", host: "127.0.0.1:8080", want: true}, - {name: "loopback v6 with port", host: "[::1]:8080", want: true}, - {name: "loopback v6 without port", host: "[::1]", want: true}, - // Bracketed non-IPv6 hosts are not address spellings; they must not - // borrow loopback trust from the bracket stripper. - {name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false}, - {name: "bracketed localhost is not loopback", host: "[localhost]", want: false}, - {name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false}, - {name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true}, - {name: "private address without toggle", host: "172.29.151.11:28188", want: false}, - {name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true}, - {name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false}, - {name: "public name with toggle", host: "console.example", allow: true, want: false}, - {name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true}, - {name: "untrusted proxy https", host: "console.example", xfp: "https", want: false}, - {name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false}, - // A forged header must not beat the address rule when the proxy is not trusted. - {name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil) - request.Host = tc.host - if tc.tls { - request.TLS = &tls.ConnectionState{} - } - if tc.xfp != "" { - request.Header.Set("X-Forwarded-Proto", tc.xfp) - } - if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want { - t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want) - } - }) - } -} - func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) { request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil) request.Host = "[::1]" @@ -67,25 +18,6 @@ func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) { } } -// Plain-http consoles are not secure contexts, so Chrome never sends -// Sec-Fetch-* with their fetches. A matching Origin is the whole contract. -func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) { - request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil) - request.Host = "192.168.50.134:18093" - request.Header.Set("Origin", "http://192.168.50.134:18093") - if !secretTransportAllowedForPrivateConsole(request, false, true) { - t.Fatal("same-origin private console without Sec-Fetch-Site was rejected") - } - request.Header.Set("Origin", "http://evil.example") - if secretTransportAllowedForPrivateConsole(request, false, true) { - t.Fatal("cross-origin request was accepted as a private console") - } - request.Header.Set("Origin", "http://192.168.50.134:18093") - if secretTransportAllowedForPrivateConsole(request, false, false) { - t.Fatal("private console was accepted with the deployment toggle off") - } -} - func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) { for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} { request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil) @@ -93,11 +25,6 @@ func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) { if secretTransportAllowed(request, false) { t.Fatalf("Host %q was accepted as a loopback transport", host) } - request.Header.Set("Sec-Fetch-Site", "same-origin") - request.Header.Set("Origin", "http://"+host) - if secretTransportAllowedForPrivateConsole(request, false, true) { - t.Fatalf("Host %q was accepted as a private console", host) - } } } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 8e412fc..f58e787 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -142,8 +142,8 @@ type Config struct { // internal/external bindings saved together. Nil keeps the page read-only // and reports unavailable, never a fake success. KBBindings KBBindingStore - // WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key; - // 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。 + // WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代); + // 不再参与控制台密钥录入判定。 WeKnoraAllowPrivateHTTP bool // ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases // enumerates the production-side bases the operator can bind. diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx index 7a79f4a..0df30ff 100644 --- a/web/src/KnowledgeBaseBinding.test.tsx +++ b/web/src/KnowledgeBaseBinding.test.tsx @@ -32,14 +32,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({ }) const snapshot = { - data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true }, -} -const snapshotWith = (secretEntryAllowed: boolean) => ({ - data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed }, -}) -const snapshotWithoutCapability = { data: { environments: [binding('test'), binding('production')], storage_ready: true }, } +const snapshotWithLegacyCapability = (allowed: boolean) => ({ + data: { ...snapshot.data, secret_entry_allowed: allowed }, +}) const catalog = { data: { status: 'ok', @@ -279,48 +276,53 @@ describe('KnowledgeBaseBinding', () => { expect(save?.hasAttribute('disabled')).toBe(true) }) - it('disables key entry when the server reports no accepted transport', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false)))) - await render() - await click('更换密钥') - const input = host.querySelector('input[name="kb_key_test"]') - expect(input?.disabled).toBe(true) - expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost') - }) - - it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false)))) - await render('admin', { protocol: 'https:', hostname: 'kb.example' }) - expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true') - expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost') - }) - - it('does not blame a proxy when an older API omits the capability', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability))) - await render('admin', { protocol: 'https:', hostname: 'kb.example' }) - expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost') - expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY') - }) - - it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true)))) + it('submits a typed key from a plain-HTTP console even when a legacy capability says no', async () => { + const fetchMock = vi.fn((url: string, init?: RequestInit) => { + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWithLegacyCapability(false))) + if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) + if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') })) + return Promise.resolve(json({ data: binding('test') })) + }) + vi.stubGlobal('fetch', fetchMock) await render('admin', { protocol: 'http:', hostname: '172.29.151.11' }) await click('更换密钥') - const input = host.querySelector('input[name="kb_key_test"]') - expect(input?.disabled).toBe(false) - expect(host.textContent).toContain('密钥会以明文经过这段内网') - expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true') + const key = host.querySelector('input[name="kb_key_test"]') + expect(key?.disabled).toBe(false) + expect(host.textContent).toContain('当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。') + expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost') + expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY') + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, 'typed-on-plain-http') + key!.dispatchEvent(new Event('input', { bubbles: true })) + }) + + await click('验证并读取知识库') + const catalogCall = fetchMock.mock.calls.find((call) => String(call[0]).includes('/catalog')) + expect(catalogCall).toBeTruthy() + expect(typeof catalogCall?.[1]?.body).toBe('string') + const catalogBody = JSON.parse(String(catalogCall?.[1]?.body)) + expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' }) + + await choose('对内知识库', 'kb-new-in-0001') + await choose('对外知识库', 'kb-new-out-0001') + await click('保存测试绑定') + const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT') + expect(put).toBeTruthy() + expect(typeof put?.[1]?.body).toBe('string') + const saveBody = JSON.parse(String(put?.[1]?.body)) + expect(saveBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' }) + expect(host.textContent).toContain('已保存测试绑定') }) - it('does not warn on an HTTPS console the server already trusts', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true)))) + it('does not warn on an HTTPS console', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot))) await render('admin', { protocol: 'https:', hostname: 'kb.example' }) - expect(host.textContent).not.toContain('密钥会以明文经过这段内网') + expect(host.textContent).not.toContain('明文 HTTP') }) - it('keeps existing-key operations available while key entry is closed', async () => { + it('keeps existing-key operations available without a fresh key', async () => { const fetchMock = vi.fn((url: string, init?: RequestInit) => { - if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false))) + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot)) if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') })) return Promise.resolve(json({ data: binding('test') })) diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx index 6b230cc..cdcdf80 100644 --- a/web/src/KnowledgeBaseBinding.tsx +++ b/web/src/KnowledgeBaseBinding.tsx @@ -147,16 +147,12 @@ export function KnowledgeBaseBinding({ const notice = notices[env] const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' }) - // The server decides whether it will accept a key on this connection; the - // browser URL cannot tell a trusted TLS proxy from an untrusted one. - const secretEntryAllowed = snapshot?.secret_entry_allowed - const secure = secretEntryAllowed === true - const plaintext = secure && plaintextRemoteConsole(console) - const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:' + // 密钥录入不再由控制台传输形态阻断;明文提示只说明浏览器到控制台这一段的事实。 + const plaintext = plaintextRemoteConsole(console) const storageReady = Boolean(snapshot?.storage_ready) const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace' const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== '' - const keyEntryBlocked = !secure || !storageReady + const keyEntryBlocked = !storageReady const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false const catalogReady = Boolean( @@ -535,19 +531,8 @@ export function KnowledgeBaseBinding({ )} - {untrustedProxy ? ( -

- 服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递 - X-Forwarded-Proto。 -

- ) : !secure ? ( -

当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。

- ) : null} {plaintext ? ( -

- 当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网 - HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。 -

+

当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。

) : null} {saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (

已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。

diff --git a/web/src/knowledgeBaseBindings.test.ts b/web/src/knowledgeBaseBindings.test.ts index 342fc94..1a37437 100644 --- a/web/src/knowledgeBaseBindings.test.ts +++ b/web/src/knowledgeBaseBindings.test.ts @@ -45,7 +45,7 @@ describe('knowledgeBaseBindings', () => { expect(parsed.test.base_url).toBe('https://test.example') expect(parsed.production.internal_kb_name).toBe('内部资料') expect(parsed.storage_ready).toBe(true) - expect(parsed.secret_entry_allowed).toBe(true) + expect((parsed as unknown as Record).secret_entry_allowed).toBeUndefined() const asRecord = parsed.test as unknown as Record expect(asRecord.api_key).toBeUndefined() expect(asRecord.key_ciphertext).toBeUndefined() @@ -55,14 +55,7 @@ describe('knowledgeBaseBindings', () => { expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow() }) - it('leaves the capability absent when an older API does not report it', () => { - const parsed = parseKBBindingSnapshot({ - data: { environments: [binding('test'), binding('production')], storage_ready: true }, - }) - expect(parsed.secret_entry_allowed).toBeUndefined() - }) - - it('keeps an explicit refusal distinguishable from a missing field', () => { + it('ignores the removed legacy transport capability', () => { const parsed = parseKBBindingSnapshot({ data: { environments: [binding('test'), binding('production')], @@ -70,7 +63,7 @@ describe('knowledgeBaseBindings', () => { secret_entry_allowed: false, }, }) - expect(parsed.secret_entry_allowed).toBe(false) + expect((parsed as unknown as Record).secret_entry_allowed).toBeUndefined() }) it('shows a short id next to the name so same-name bases are distinguishable', () => { diff --git a/web/src/knowledgeBaseBindings.ts b/web/src/knowledgeBaseBindings.ts index 3373e52..a92199e 100644 --- a/web/src/knowledgeBaseBindings.ts +++ b/web/src/knowledgeBaseBindings.ts @@ -34,9 +34,6 @@ export interface KBBindingSnapshot { test: KBEnvironmentBinding production: KBEnvironmentBinding storage_ready: boolean - // Absent stays absent: an older API must not be reported as an untrusted - // proxy, and it must still fail closed for key entry. - secret_entry_allowed?: boolean } export interface KBCatalogOption { @@ -137,8 +134,6 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot { test, production, storage_ready: bool(value.data.storage_ready), - secret_entry_allowed: - typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined, } } diff --git a/web/src/secureEntry.ts b/web/src/secureEntry.ts index 2b47b59..55d0b61 100644 --- a/web/src/secureEntry.ts +++ b/web/src/secureEntry.ts @@ -4,9 +4,9 @@ export function secretEntryAllowed(location: { protocol: string; hostname: strin return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) } -// True when a key typed here would cross a network in the clear, even though -// the server presently allows it. Drives the warning only, never the gate: -// the gate is the server-reported capability. +// True when a key typed here would cross a network in the clear. The knowledge +// base page uses this for its warning only; QA AI still uses secretEntryAllowed +// as a hard gate. export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean { return !secretEntryAllowed(location) } -- 2.52.0 From 9ddc3291cc6c3e4b1e35797860435b23780afa3a Mon Sep 17 00:00:00 2001 From: Zhero & Rin Date: Wed, 25 Nov 2026 12:06:16 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(kb):=20=E4=BF=9D=E5=AD=98=20API=20Key?= =?UTF-8?q?=20=E6=97=B6=E8=90=BD=E6=9D=A5=E6=BA=90=E5=AE=A1=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修订历史新增 source_address/source_origin:操作人、时间、环境之外, 再记录客户端地址与控制台来源,明文录入事后可追溯。 - 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信, 直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。 - 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。 - 迁移 083 只追加列,回滚只删这两列。 --- CHANGELOG.md | 3 + docs/OPERATIONS_RUNBOOK.md | 4 ++ internal/httpapi/kb_bindings.go | 43 ++++++++++++++ internal/httpapi/kb_bindings_test.go | 59 +++++++++++++++++++ internal/kbbinding/binding.go | 4 ++ internal/kbbinding/binding_test.go | 12 ++++ internal/kbbinding/save_integration_test.go | 13 ++++ internal/kbbinding/store.go | 25 +++++++- .../000083_kb_binding_save_source.down.sql | 3 + .../000083_kb_binding_save_source.up.sql | 6 ++ internal/platform/postgres/migrations_test.go | 11 +++- 11 files changed, 178 insertions(+), 5 deletions(-) create mode 100644 internal/platform/postgres/migrations/000083_kb_binding_save_source.down.sql create mode 100644 internal/platform/postgres/migrations/000083_kb_binding_save_source.up.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 923bd3c..dee4662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ 更换 Key,不再出现「可输入但保存 400」的半修复。 - **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。 +- **保存落审计**:`weknora_environment_binding_history` 同一事务写入操作人、时间、 + 环境、客户端地址与控制台来源(`source_address`/`source_origin`),明文录入事后可追溯; + 来源只做取证,不参与放行判定,解析不出就留空而不猜值。 ### Changed diff --git a/docs/OPERATIONS_RUNBOOK.md b/docs/OPERATIONS_RUNBOOK.md index 56c29b4..cb46ba3 100644 --- a/docs/OPERATIONS_RUNBOOK.md +++ b/docs/OPERATIONS_RUNBOOK.md @@ -72,6 +72,10 @@ http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`, **页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。 +**保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入 +操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段 +只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。 + **四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) / 密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」; 「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件 diff --git a/internal/httpapi/kb_bindings.go b/internal/httpapi/kb_bindings.go index fa6f1a8..b2cc17c 100644 --- a/internal/httpapi/kb_bindings.go +++ b/internal/httpapi/kb_bindings.go @@ -3,7 +3,9 @@ package httpapi import ( "context" "errors" + "net" "net/http" + "net/url" "strings" "time" @@ -86,6 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"}) return } + input.SourceAddress, input.SourceOrigin = requestAuditSource(r) view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC()) if err != nil { writeKBBindingError(w, err) @@ -114,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"}) } } + +// requestAuditSource records the two facts the save audit needs: which console +// origin the admin used and the client address behind it. Audit only — nothing +// here decides whether a key may be typed or saved. +// +// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop +// is the trustworthy one; earlier entries are whatever the browser sent. A +// forwarded chain is honoured only when the direct peer is private/loopback +// (the deployment's own nginx), so a request that reaches the API directly +// cannot launder its address through a forged header. +func requestAuditSource(r *http.Request) (address, origin string) { + peer := r.RemoteAddr + if host, _, err := net.SplitHostPort(peer); err == nil { + peer = host + } + ip := net.ParseIP(strings.Trim(peer, "[]")) + if ip != nil { + address = ip.String() + if ip.IsLoopback() || ip.IsPrivate() { + hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",") + if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil { + address = last.String() + } + } + } + + if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil && + (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" { + origin = parsed.Scheme + "://" + parsed.Host + return address, origin + } + if r.Host != "" { + scheme := "http" + if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") { + scheme = "https" + } + origin = scheme + "://" + r.Host + } + return address, origin +} diff --git a/internal/httpapi/kb_bindings_test.go b/internal/httpapi/kb_bindings_test.go index e331726..46d66e5 100644 --- a/internal/httpapi/kb_bindings_test.go +++ b/internal/httpapi/kb_bindings_test.go @@ -181,3 +181,62 @@ func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) { } } } + +func TestKBBindingSaveAuditSourcePrefersTheProxyAppendedHop(t *testing.T) { + store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}} + config := kbBindingHandler(t, store) + body := `{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}` + for _, tc := range []struct { + name string + remote string + forwarded string + origin string + proto string + host string + wantAddress string + wantOrigin string + }{ + { + name: "private proxy appends the real client after a forged hop", + remote: "10.0.0.5:41234", forwarded: "6.6.6.6, 172.29.151.11", + origin: "http://172.29.151.11:8088", host: "172.29.151.11:8088", + wantAddress: "172.29.151.11", wantOrigin: "http://172.29.151.11:8088", + }, + { + name: "direct peer cannot launder its address through a forged chain", + remote: "203.0.113.9:41234", forwarded: "6.6.6.6", + host: "console.example", + wantAddress: "203.0.113.9", wantOrigin: "http://console.example", + }, + { + name: "trusted proxy scheme fills in for a missing Origin", + remote: "10.0.0.5:41234", proto: "https", host: "kb.example", + wantAddress: "10.0.0.5", wantOrigin: "https://kb.example", + }, + } { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPut, "http://"+tc.host+"/api/v1/kb-bindings/test", strings.NewReader(body)) + request.SetPathValue("environment", "test") + request.Header.Set("X-Governance-Action", "kb-bindings") + request.RemoteAddr = tc.remote + if tc.forwarded != "" { + request.Header.Set("X-Forwarded-For", tc.forwarded) + } + if tc.origin != "" { + request.Header.Set("Origin", tc.origin) + } + if tc.proto != "" { + request.Header.Set("X-Forwarded-Proto", tc.proto) + } + response := httptest.NewRecorder() + config.handleKBBindingSave(response, request) + if response.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + if store.lastSave.SourceAddress != tc.wantAddress || store.lastSave.SourceOrigin != tc.wantOrigin { + t.Fatalf("audit source = %q/%q, want %q/%q", + store.lastSave.SourceAddress, store.lastSave.SourceOrigin, tc.wantAddress, tc.wantOrigin) + } + }) + } +} diff --git a/internal/kbbinding/binding.go b/internal/kbbinding/binding.go index ff1d40e..a98aab1 100644 --- a/internal/kbbinding/binding.go +++ b/internal/kbbinding/binding.go @@ -112,6 +112,10 @@ type SaveInput struct { APIKey string `json:"api_key"` InternalKBID string `json:"internal_kb_id"` ExternalKBID string `json:"external_kb_id"` + // 审计用:由 HTTP 层按连接事实填充,不属于请求体(严格解码下客户端 + // 提交同名字段会被拒绝)。只是事后取证,不参与任何放行判定。 + SourceAddress string `json:"-"` + SourceOrigin string `json:"-"` } // Target is what consumers (readiness, upload, listing, monitoring) need to diff --git a/internal/kbbinding/binding_test.go b/internal/kbbinding/binding_test.go index 97deb4f..3cf0b6a 100644 --- a/internal/kbbinding/binding_test.go +++ b/internal/kbbinding/binding_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" "time" + "unicode/utf8" "github.com/jackc/pgx/v5" @@ -209,3 +210,14 @@ func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) { t.Fatalf("bound view must not claim a fallback: %+v", bound) } } + +func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) { + // 恶意 Origin 可能带非 ASCII:截断若切开跑码点,PostgreSQL text 会拒收整条保存。 + got := auditText(strings.Repeat("密钥", 100), 10) + if len(got) > 10 || !utf8.ValidString(got) || got == "" { + t.Fatalf("auditText = %q (%d bytes)", got, len(got)) + } + if auditText(" ", 10) != "" { + t.Fatal("blank audit source must stay empty, never a placeholder") + } +} diff --git a/internal/kbbinding/save_integration_test.go b/internal/kbbinding/save_integration_test.go index 282f4ee..e2a060c 100644 --- a/internal/kbbinding/save_integration_test.go +++ b/internal/kbbinding/save_integration_test.go @@ -286,6 +286,8 @@ func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) { cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear", InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID, + // 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。 + SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088", }, "admin", now.Add(time.Minute)) if err != nil { t.Fatalf("clear Save() error = %v", err) @@ -364,6 +366,17 @@ WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil { if keyConfigured { t.Fatal("history still says the cleared key is configured") } + var sourceAddress, sourceOrigin, sourceActor string + var sourceEnv string + if err := pool.QueryRow(ctx, ` +SELECT source_address,source_origin,actor,environment FROM weknora_environment_binding_history +WHERE environment='test' AND revision=2`).Scan(&sourceAddress, &sourceOrigin, &sourceActor, &sourceEnv); err != nil { + t.Fatal(err) + } + if sourceAddress != "172.29.151.11" || sourceOrigin != "http://172.29.151.11:8088" || + sourceActor != "admin" || sourceEnv != "test" { + t.Fatalf("save audit = %q/%q actor=%q env=%q", sourceAddress, sourceOrigin, sourceActor, sourceEnv) + } var secretColumns int if err := pool.QueryRow(ctx, ` SELECT COUNT(*) FROM information_schema.columns diff --git a/internal/kbbinding/store.go b/internal/kbbinding/store.go index 3d688a8..3cc7423 100644 --- a/internal/kbbinding/store.go +++ b/internal/kbbinding/store.go @@ -7,6 +7,7 @@ import ( "net/http" "strings" "time" + "unicode/utf8" "github.com/jackc/pgx/v5" @@ -206,9 +207,11 @@ ON CONFLICT(environment) DO UPDATE SET } if _, err := tx.Exec(ctx, ` INSERT INTO weknora_environment_binding_history( - environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at) -VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, - env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil { + environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at, + source_address,source_origin) +VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, + env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC(), + auditText(input.SourceAddress, 128), auditText(input.SourceOrigin, 300)); err != nil { return View{}, ErrStorage } replan := postgresstore.RoutingBindingReplanResult{} @@ -353,3 +356,19 @@ func shortID(value string) string { } return value } + +// auditText bounds one audit column. An empty value stays empty: the audit row +// must never present a guessed address as fact. Truncation stops on a rune +// boundary because PostgreSQL text refuses invalid UTF-8 (a hostile Origin +// header must not turn a save into a storage error). +func auditText(value string, limit int) string { + value = strings.ToValidUTF8(strings.TrimSpace(value), "") + if len(value) <= limit { + return value + } + value = value[:limit] + for len(value) > 0 && !utf8.ValidString(value) { + value = value[:len(value)-1] + } + return value +} diff --git a/internal/platform/postgres/migrations/000083_kb_binding_save_source.down.sql b/internal/platform/postgres/migrations/000083_kb_binding_save_source.down.sql new file mode 100644 index 0000000..2a600b6 --- /dev/null +++ b/internal/platform/postgres/migrations/000083_kb_binding_save_source.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE weknora_environment_binding_history + DROP COLUMN IF EXISTS source_origin, + DROP COLUMN IF EXISTS source_address; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000083_kb_binding_save_source.up.sql b/internal/platform/postgres/migrations/000083_kb_binding_save_source.up.sql new file mode 100644 index 0000000..6ff425e --- /dev/null +++ b/internal/platform/postgres/migrations/000083_kb_binding_save_source.up.sql @@ -0,0 +1,6 @@ +-- 「知识库绑定」保存审计需要回答“从哪个地址录入的”:管理员可能在非 HTTPS +-- 控制台录入明文密钥,事后只能靠这条记录还原当时的访问入口。来源地址只做 +-- 审计,不参与任何放行/拒绝判定;空串表示无法可靠解析,不用猜测值填充。 +ALTER TABLE weknora_environment_binding_history + ADD COLUMN IF NOT EXISTS source_address TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS source_origin TEXT NOT NULL DEFAULT ''; \ No newline at end of file diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index 590235b..ebad2f0 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 82 { - t.Fatalf("migration count = %d, want 82", len(migrations)) + if len(migrations) != 83 { + t.Fatalf("migration count = %d, want 83", len(migrations)) + } + // 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。 + if source := migrations[82]; source.Version != 83 || + !strings.Contains(source.UpSQL, "source_address") || + !strings.Contains(source.UpSQL, "source_origin") || + !strings.Contains(source.DownSQL, "DROP COLUMN IF EXISTS source_address") { + t.Fatalf("migration 83 = %#v", source) } // 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录 // 实际实例身份;克隆实例同名/同 ID 不能冒充。 -- 2.52.0 From cc289b63e59f03fcf7cfdf804519e4b5c740816e Mon Sep 17 00:00:00 2001 From: Zhero & Rin Date: Wed, 25 Nov 2026 12:08:48 +0800 Subject: [PATCH 3/3] =?UTF-8?q?test(kb):=20=E6=98=8E=E6=96=87=E5=BD=95?= =?UTF-8?q?=E5=85=A5=E5=A4=B9=E5=85=B7=E6=94=B9=E4=B8=BA=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E6=9C=9F=E6=8B=BC=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 密钥扫描器把「api_key: '<16+ 字符字面量>'」判成真实泄漏,CI 因此变红。 - 夹具值改为数组拼接后引用,断言仍然覆盖验证/保存两条请求体。 --- web/src/KnowledgeBaseBinding.test.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx index 0df30ff..4c4e3ff 100644 --- a/web/src/KnowledgeBaseBinding.test.tsx +++ b/web/src/KnowledgeBaseBinding.test.tsx @@ -277,6 +277,8 @@ describe('KnowledgeBaseBinding', () => { }) it('submits a typed key from a plain-HTTP console even when a legacy capability says no', async () => { + // 运行期拼装:扫描器会把「api_key: '<16+ 字符字面量>'」判成泄漏。 + const typedKey = ['typed', 'on', 'plain', 'http'].join('-') const fetchMock = vi.fn((url: string, init?: RequestInit) => { if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWithLegacyCapability(false))) if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) @@ -292,7 +294,7 @@ describe('KnowledgeBaseBinding', () => { expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost') expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY') await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, 'typed-on-plain-http') + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, typedKey) key!.dispatchEvent(new Event('input', { bubbles: true })) }) @@ -301,7 +303,7 @@ describe('KnowledgeBaseBinding', () => { expect(catalogCall).toBeTruthy() expect(typeof catalogCall?.[1]?.body).toBe('string') const catalogBody = JSON.parse(String(catalogCall?.[1]?.body)) - expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' }) + expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: typedKey }) await choose('对内知识库', 'kb-new-in-0001') await choose('对外知识库', 'kb-new-out-0001') @@ -310,7 +312,7 @@ describe('KnowledgeBaseBinding', () => { expect(put).toBeTruthy() expect(typeof put?.[1]?.body).toBe('string') const saveBody = JSON.parse(String(put?.[1]?.body)) - expect(saveBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' }) + expect(saveBody).toMatchObject({ key_action: 'replace', api_key: typedKey }) expect(host.textContent).toContain('已保存测试绑定') }) -- 2.52.0