Files
knowledge-governance/internal/httpapi/kb_bindings_test.go
T
狐友 GXXP & Miku 8c84c9c601
build / build (push) Successful in 2m26s
fix(kb-bindings): allow key entry on private HTTP consoles
- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
2026-11-24 11:22:06 +08:00

224 lines
9.2 KiB
Go

package httpapi
import (
"bytes"
"context"
"encoding/json"
"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 TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
store := &fakeKBBindings{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))
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)
}
if strings.Contains(response.Body.String(), "typed-key") {
t.Fatal("catalog response echoed the typed key")
}
}
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 TestKBBindingsReadReportsSecretEntryCapability(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)
}
})
}
}
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
const (
privateHost = "172.29.151.11:28188"
origin = "http://172.29.151.11:28188"
)
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"}`
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.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
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.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())
}
}