ce2a155ebc
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥, 也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址 与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与 绑定,回读真实生效值。 服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件 凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥 不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储 解析当前连接,避免只保存了页面数据。 验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错; make verify 在本提交上执行(结果见交付说明)。
180 lines
7.1 KiB
Go
180 lines
7.1 KiB
Go
package kbbinding_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"knowledge-governance/internal/kbbinding"
|
|
postgresstore "knowledge-governance/internal/platform/postgres"
|
|
"knowledge-governance/internal/platform/postgres/pgtest"
|
|
)
|
|
|
|
// testSecret() 在运行时拼出测试夹具密钥,避免把任何字面量误当成真实凭据入库。
|
|
func testSecret() string { return "fixture-" + strings.Repeat("k", 24) }
|
|
|
|
func fakeCandidate(t *testing.T) *httptest.Server {
|
|
t.Helper()
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("X-API-Key") != testSecret() {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
switch {
|
|
case r.URL.Path == "/api/v1/knowledge-bases":
|
|
_, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`))
|
|
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`))
|
|
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`))
|
|
default:
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}))
|
|
t.Cleanup(server.Close)
|
|
return server
|
|
}
|
|
|
|
func masterKey(t *testing.T) string {
|
|
t.Helper()
|
|
path := filepath.Join(t.TempDir(), "binding-master.key")
|
|
if err := os.WriteFile(path, []byte(strings.Repeat("k", 32)), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return path
|
|
}
|
|
|
|
func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing.T) {
|
|
databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
|
if databaseURL == "" {
|
|
t.Skip("TEST_DATABASE_URL is not set")
|
|
}
|
|
ctx := context.Background()
|
|
pool, err := pgxpool.New(ctx, databaseURL)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer pool.Close()
|
|
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := pool.Exec(ctx, `
|
|
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
|
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
|
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope');
|
|
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
|
('version-kbb','item-kbb','locator:r1',NULL,'unknown');
|
|
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
|
('pub-kbb','version-kbb','kb-old','planned','pending','internal');
|
|
`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
server := fakeCandidate(t)
|
|
store := kbbinding.New(pool, kbbinding.Options{
|
|
MasterKeyFile: masterKey(t),
|
|
Timeout: 2 * time.Second,
|
|
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
|
RoutingDefaults: func() (string, string) { return "env-in", "env-out" },
|
|
})
|
|
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
|
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
|
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
|
}, "admin", now)
|
|
if err != nil {
|
|
t.Fatalf("Save() error = %v", err)
|
|
}
|
|
if view.Revision != 1 || !view.KeyConfigured || view.InternalKBName != "内部技术资料" || view.ExternalKBName != "客户使用手册" {
|
|
t.Fatalf("view = %#v", view)
|
|
}
|
|
if view.Replanned != 1 {
|
|
t.Fatalf("replanned = %d, want 1", view.Replanned)
|
|
}
|
|
target, err := store.Resolve(ctx, kbbinding.EnvTest)
|
|
if err != nil || target.BaseURL != server.URL || target.APIKey != testSecret() || target.Revision != 1 {
|
|
t.Fatalf("Resolve() = %#v, %v", target, err)
|
|
}
|
|
var routingInternal, routingExternal string
|
|
if err := pool.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal, &routingExternal); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if routingInternal != "kb-in" || routingExternal != "kb-out" {
|
|
t.Fatalf("routing binding = %s/%s", routingInternal, routingExternal)
|
|
}
|
|
var pendingKB string
|
|
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&pendingKB); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if pendingKB != "kb-in" {
|
|
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
|
}
|
|
|
|
// A stale revision must not overwrite the saved connection or re-point work.
|
|
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "keep",
|
|
InternalKBID: "kb-out", ExternalKBID: "kb-in",
|
|
}, "admin", now.Add(time.Minute))
|
|
if !errors.Is(err, kbbinding.ErrConflict) {
|
|
t.Fatalf("stale save error = %v, want ErrConflict", err)
|
|
}
|
|
unchanged, err := store.Resolve(ctx, kbbinding.EnvTest)
|
|
if err != nil || unchanged.APIKey != testSecret() {
|
|
t.Fatalf("connection changed after conflict: %#v, %v", unchanged, err)
|
|
}
|
|
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if routingInternal != "kb-in" {
|
|
t.Fatalf("routing binding changed after conflict: %s", routingInternal)
|
|
}
|
|
|
|
// A base from another instance (404 here) must be refused and leave no row
|
|
// for a different environment.
|
|
if _, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
|
InternalKBID: "not-there", ExternalKBID: "kb-out",
|
|
}, "admin", now); !errors.Is(err, kbbinding.ErrRejected) {
|
|
t.Fatalf("unknown base error = %v, want ErrRejected", err)
|
|
}
|
|
var count int
|
|
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM weknora_environment_bindings WHERE environment='production'`).Scan(&count); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if count != 0 {
|
|
t.Fatalf("failed production save wrote %d rows", count)
|
|
}
|
|
|
|
// The old key must never be forwarded: keep is only legal for the saved URL.
|
|
if _, err := store.Catalog(ctx, kbbinding.EnvTest, kbbinding.CatalogInput{
|
|
BaseURL: "https://another.example", KeyAction: "keep", Page: 1, PageSize: 20,
|
|
}); !errors.Is(err, kbbinding.ErrKeyForwarding) {
|
|
t.Fatalf("keep with another address = %v, want ErrKeyForwarding", err)
|
|
}
|
|
|
|
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
|
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
|
}, "admin", now)
|
|
if err != nil {
|
|
t.Fatalf("production Save() error = %v", err)
|
|
}
|
|
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 {
|
|
t.Fatalf("production view = %#v", prodView)
|
|
}
|
|
var productionInternal string
|
|
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if productionInternal != "kb-in" {
|
|
t.Fatalf("production binding = %s", productionInternal)
|
|
}
|
|
}
|