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 不能冒充。