feat(settings): 知识库绑定按环境一次保存连接与内外库

原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥,
也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址
与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与
绑定,回读真实生效值。

服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件
凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥
不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储
解析当前连接,避免只保存了页面数据。

验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错;
make verify 在本提交上执行(结果见交付说明)。
This commit is contained in:
姚章浩
2026-11-19 14:43:51 +08:00
parent df69b278ce
commit ce2a155ebc
53 changed files with 3367 additions and 601 deletions
@@ -0,0 +1,3 @@
-- 回滚只删本迁移新增的审计与配置表;旧部署的 file 凭据/绑定表不受影响。
DROP TABLE IF EXISTS weknora_environment_binding_history;
DROP TABLE IF EXISTS weknora_environment_bindings;
@@ -0,0 +1,36 @@
-- 「知识库绑定」按环境保存一组连接与内外库绑定:测试与生产各自一行,
-- 一次保存同时写连接(地址 + 加密密钥)与对内/对外目标。没有行时消费者
-- 继续使用旧部署的文件凭据/默认绑定,所以升级不需要回填。
--
-- key_ciphertext 只存密文;主密钥在独立文件里(WEKNORA_BINDING_MASTER_KEY_FILE),
-- 不进库、不进备份、不经页面回显。verification 记录最近一次真实列库/选库核验。
CREATE TABLE weknora_environment_bindings (
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
revision BIGINT NOT NULL CHECK (revision > 0),
base_url TEXT NOT NULL DEFAULT '',
key_ciphertext BYTEA NOT NULL DEFAULT ''::bytea,
internal_kb_id VARCHAR(128) NOT NULL DEFAULT '',
external_kb_id VARCHAR(128) NOT NULL DEFAULT '',
internal_kb_name TEXT NOT NULL DEFAULT '',
external_kb_name TEXT NOT NULL DEFAULT '',
verification TEXT NOT NULL DEFAULT 'not_configured'
CHECK (verification IN ('not_configured','verified','empty','unreachable','rejected')),
checked_at TIMESTAMPTZ,
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- 修订历史只记录“是否配置了密钥”,绝不复制密文或明文,供审计回答谁在何时
-- 把哪个环境指向了哪里。
CREATE TABLE weknora_environment_binding_history (
environment VARCHAR(16) NOT NULL,
revision BIGINT NOT NULL,
base_url TEXT NOT NULL,
key_configured BOOLEAN NOT NULL,
internal_kb_id VARCHAR(128) NOT NULL,
external_kb_id VARCHAR(128) NOT NULL,
verification TEXT NOT NULL,
actor TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (environment, revision)
);
@@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 80 {
t.Fatalf("migration count = %d, want 80", len(migrations))
if len(migrations) != 81 {
t.Fatalf("migration count = %d, want 81", len(migrations))
}
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
if binding := migrations[80]; binding.Version != 81 ||
!strings.Contains(binding.UpSQL, "weknora_environment_bindings") ||
!strings.Contains(binding.UpSQL, "key_ciphertext") ||
!strings.Contains(binding.DownSQL, "DROP TABLE IF EXISTS weknora_environment_bindings") {
t.Fatalf("migration 81 = %#v", binding)
}
// 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥,
// 证据按 target_id 落库(换目标旧证据自动失效)。
@@ -39,14 +39,26 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
if now.IsZero() {
return errors.New("production binding save requires a timestamp")
}
if _, err := s.db.Exec(ctx, `
if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
return errors.New("save production kb bindings")
}
return nil
}
const productionBindingUpsertSQL = `
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
updated_at=EXCLUDED.updated_at`
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
// update the same row inside its own transaction, so connection and bindings
// cannot be half-written.
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
return errors.New("save production kb bindings")
}
return nil
+25 -4
View File
@@ -121,6 +121,22 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
return result, fmt.Errorf("begin routing binding save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := SaveRoutingKBBindingsTx(ctx, tx, internalID, externalID, updatedBy, now); err != nil {
return result, err
}
result, err = ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now)
if err != nil {
return RoutingBindingReplanResult{}, err
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit routing binding save: %w", err)
}
return result, nil
}
// SaveRoutingKBBindingsTx is the binding upsert, shared by the settings page and
// the environment-scoped 「知识库绑定」save so the two entries cannot drift.
func SaveRoutingKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
if _, err := tx.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
@@ -129,8 +145,16 @@ ON CONFLICT(id) DO UPDATE SET
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
return result, errors.New("save routing kb bindings")
return errors.New("save routing kb bindings")
}
return nil
}
// ReplanPendingPublicationsTx re-points untouched 待入库 rows at the new targets
// inside the caller's transaction. It only moves rows that were never uploaded
// anywhere; anything already in flight keeps its frozen target.
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, effectiveInternal, effectiveExternal string, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
for _, scope := range []struct{ name, kbID string }{
{"internal", effectiveInternal},
{"external", effectiveExternal},
@@ -149,8 +173,5 @@ ON CONFLICT(id) DO UPDATE SET
result.RetiredDuplicates += int(retired.RowsAffected())
result.Replanned += int(moved.RowsAffected())
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit routing binding save: %w", err)
}
return result, nil
}