Files
knowledge-governance/internal/httpapi/kb_bindings_test.go
Zhero & Rin 9ddc3291cc fix(kb): 保存 API Key 时落来源审计
- 修订历史新增 source_address/source_origin:操作人、时间、环境之外,
  再记录客户端地址与控制台来源,明文录入事后可追溯。
- 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信,
  直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。
- 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。
- 迁移 083 只追加列,回滚只删这两列。
2026-11-25 12:06:36 +08:00

243 lines
10 KiB
Go

package httpapi
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/kbbinding"
)
type fakeKBBindings struct {
views []kbbinding.View
catalog kbbinding.Catalog
saveErr error
catalogErr error
lastSave kbbinding.SaveInput
lastActor string
}
func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) {
return fake.views, nil
}
func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) {
return fake.catalog, fake.catalogErr
}
func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) {
fake.lastSave = input
fake.lastActor = actor
if fake.saveErr != nil {
return kbbinding.View{}, fake.saveErr
}
return fake.views[0], nil
}
func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" }
func kbBindingHandler(t *testing.T, store KBBindingStore) *Config {
t.Helper()
config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }}
return config
}
func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{
Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example",
KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部",
ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true,
}}}
config := kbBindingHandler(t, store)
response := httptest.NewRecorder()
config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil))
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
body := response.Body.String()
for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} {
if strings.Contains(body, forbidden) {
t.Fatalf("read response exposes %q: %s", forbidden, body)
}
}
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
request.SetPathValue("environment", "test")
response = httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusForbidden {
t.Fatalf("save without intent status = %d", response.Code)
}
}
func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}},
saveErr: kbbinding.ErrConflict,
}
config := kbBindingHandler(t, store)
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") {
t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String())
}
}
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)
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.StatusOK {
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) {
for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} {
if role := classifyRole(http.MethodPut, path); role != roleAdmin {
t.Fatalf("PUT %s role = %s, want admin", path, role)
}
if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer {
t.Fatalf("GET bindings role = %s, want viewer", role)
}
}
}
func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
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 TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
const (
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},
}
for _, allow := range []bool{false, true} {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = allow
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("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")
response = httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusOK {
t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
}
}
}
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)
}
})
}
}