fix(kb): 保存 API Key 时落来源审计

- 修订历史新增 source_address/source_origin:操作人、时间、环境之外,
  再记录客户端地址与控制台来源,明文录入事后可追溯。
- 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信,
  直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。
- 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。
- 迁移 083 只追加列,回滚只删这两列。
This commit is contained in:
Zhero & Rin
2026-11-25 12:06:16 +08:00
committed by 姚章浩
parent 32c7074f41
commit 9ddc3291cc
11 changed files with 178 additions and 5 deletions
+59
View File
@@ -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)
}
})
}
}