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
+43
View File
@@ -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
}
+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)
}
})
}
}