package kbbinding import ( "bytes" "context" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strconv" "strings" "testing" "time" "github.com/jackc/pgx/v5" "knowledge-governance/internal/platform/weknora" "knowledge-governance/internal/secretbox" ) type emptyDB struct{} func (emptyDB) QueryRow(context.Context, string, ...any) pgx.Row { return emptyRow{} } func (emptyDB) Begin(context.Context) (pgx.Tx, error) { return nil, errors.New("no transaction in unit test") } type emptyRow struct{} func (emptyRow) Scan(...any) error { return pgx.ErrNoRows } // fakeWeKnora serves the two reads the candidate validation makes: one page of // knowledge bases and a single base by id. func fakeWeKnora(t *testing.T, wantKey string, bases []struct{ id, name string }, total int64) *httptest.Server { t.Helper() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got := r.Header.Get("X-API-Key"); got != wantKey { w.WriteHeader(http.StatusUnauthorized) return } if r.URL.Path == "/api/v1/knowledge-bases" { items := make([]string, 0, len(bases)) for _, base := range bases { items = append(items, `{"id":"`+base.id+`","name":"`+base.name+`","knowledge_count":2}`) } _, _ = w.Write([]byte(`{"success":true,"data":[` + strings.Join(items, ",") + `],"total":` + strconv.FormatInt(total, 10) + `}`)) return } if strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/") { id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/") for _, base := range bases { if base.id == id { _, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + base.id + `","name":"` + base.name + `"}}`)) return } } w.WriteHeader(http.StatusNotFound) return } w.WriteHeader(http.StatusNotFound) })) t.Cleanup(server.Close) return server } func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) { ctx := context.Background() store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}}) empty := fakeWeKnora(t, "key-1", nil, 0) catalog, err := store.Catalog(ctx, EnvTest, CatalogInput{ BaseURL: empty.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, }) if err != nil || catalog.Status != statusEmpty || catalog.Total != 0 { t.Fatalf("empty catalog = %#v, %v", catalog, err) } denied := fakeWeKnora(t, "another-key", nil, 0) catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{ BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, }) if err != nil || catalog.Status != statusKeyInvalid { t.Fatalf("denied catalog = %#v, %v", catalog, err) } down := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) downURL := down.URL down.Close() catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{ BaseURL: downURL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, }) if err != nil || catalog.Status != statusUnreachable { t.Fatalf("unreachable catalog = %#v, %v", catalog, err) } } func TestCatalogPaginatesAndReturnsNamesWithShortIDsAreStable(t *testing.T) { server := fakeWeKnora(t, "key-1", []struct{ id, name string }{{"kb-1", "技术资料"}}, 1) store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}}) catalog, err := store.Catalog(context.Background(), EnvTest, CatalogInput{ BaseURL: server.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, }) if err != nil || catalog.Status != statusOK || len(catalog.Options) != 1 || catalog.Options[0].Name != "技术资料" { t.Fatalf("catalog = %#v, %v", catalog, err) } } func TestKeyActionRulesRejectForwardingAndInvalidInput(t *testing.T) { store := New(emptyDB{}, Options{}) saved := stored{Environment: EnvTest, Revision: 1, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")} if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://new.example", "", saved, true); !errors.Is(err, ErrKeyForwarding) { t.Fatalf("keep with a new address = %v, want ErrKeyForwarding", err) } if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) { t.Fatalf("keep with a typed key = %v, want ErrInvalid", err) } if _, err := store.keyFor(context.Background(), EnvTest, "replace", "https://new.example", " ", saved, true); !errors.Is(err, ErrInvalid) { t.Fatalf("replace with blank key = %v, want ErrInvalid", err) } } func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) { now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) store := New(emptyDB{}, Options{Now: func() time.Time { return now }}) for _, input := range []SaveInput{ {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"}, {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"}, {BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"}, } { if _, err := store.Save(context.Background(), EnvTest, input, "admin", now); !errors.Is(err, ErrInvalid) { t.Fatalf("input %#v error = %v, want ErrInvalid", input, err) } } } func TestCatalogDistinguishesInvalidKeyFromForbiddenKey(t *testing.T) { invalid := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusUnauthorized}) if invalid.Status != "key_invalid" || !strings.Contains(invalid.Message, "密钥无效") { t.Fatalf("401 -> %+v", invalid) } forbidden := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusForbidden}) if forbidden.Status != "key_forbidden" || !strings.Contains(forbidden.Message, "无权限") { t.Fatalf("403 -> %+v", forbidden) } dead := catalogFailure(context.DeadlineExceeded) if dead.Status != "unreachable" || !(strings.Contains(dead.Message, "超时") || strings.Contains(dead.Message, "不可达")) { t.Fatalf("timeout -> %+v", dead) } if dead.Status == invalid.Status || invalid.Status == forbidden.Status { t.Fatal("the three outcomes must stay distinguishable") } } func TestClearKeyIsASeparateAction(t *testing.T) { store := New(emptyDB{}, Options{}) saved := stored{Environment: EnvTest, Revision: 2, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")} key, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "", saved, true) if err != nil || key != "" { t.Fatalf("clear = %q, %v", key, err) } if _, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) { t.Fatalf("clear with a typed key = %v, want ErrInvalid", err) } } func TestKeyTailShowsOnlyFourCharacters(t *testing.T) { path := filepath.Join(t.TempDir(), "master.key") if err := os.WriteFile(path, bytes.Repeat([]byte{7}, 32), 0o600); err != nil { t.Fatal(err) } box, err := secretbox.Load(path) if err != nil { t.Fatalf("secretbox.Load: %v", err) } sealed, err := box.Seal([]byte("sk-live-abcd"), keyAAD(EnvTest, 3)) if err != nil { t.Fatal(err) } store := New(emptyDB{}, Options{MasterKeyFile: path}) tail, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 3}, EnvTest) if !ok || tail != "abcd" { t.Fatalf("tail = %q %v", tail, ok) } // A different revision must not open — the tail must never leak from a // ciphertext that no longer matches the row. if _, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 4}, EnvTest); ok { t.Fatal("tail opened with the wrong revision") } } func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) { store := New(emptyDB{}, Options{LegacyBinding: func(context.Context, string) (string, string, error) { return "legacy-in-0001", "legacy-out-0001", nil }}) view := View{Environment: EnvTest} store.fillFallbacks(context.Background(), EnvTest, &view) if view.InternalFallback != "legacy-in-0001" || view.ExternalFallback != "legacy-out-0001" { t.Fatalf("test fallbacks = %+v", view) } production := View{Environment: EnvProduction} store.fillFallbacks(context.Background(), EnvProduction, &production) if production.InternalFallback != "same-id" || production.ExternalFallback != "same-id" { t.Fatalf("production fallbacks = %+v", production) } bound := View{Environment: EnvTest, InternalKBID: "a", ExternalKBID: "b"} store.fillFallbacks(context.Background(), EnvTest, &bound) if bound.InternalFallback != "" || bound.ExternalFallback != "" { t.Fatalf("bound view must not claim a fallback: %+v", bound) } }