1f5bf72aec
网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。 克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个 目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项, 执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以 release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。 测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前 连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。 「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署 默认 ID,避免换绑实例后带过去旧对象的默认库。 验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户 的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。
186 lines
7.6 KiB
Go
186 lines
7.6 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":"内部技术资料","tenant_id":10000}}`))
|
|
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
|
|
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},
|
|
})
|
|
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
|
if _, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
|
InternalKBID: "kb-in",
|
|
}, "admin", now); !errors.Is(err, kbbinding.ErrInvalid) {
|
|
t.Fatalf("save with an unbound side = %v, want ErrInvalid", err)
|
|
}
|
|
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, productionURL string
|
|
var productionTenant uint64
|
|
if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if productionInternal != "kb-in" || productionURL != server.URL || productionTenant != 10000 {
|
|
t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
|
|
}
|
|
}
|