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) } } }