feat(settings): 页面录入测试/生产 WeKnora 连接与密钥并收敛可达性判定

连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥,
页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功,
换地址或换密钥必须测通才能保存(迁移 000083)。

可达性判定收敛为 weknora.HTTPAllowed,客户端与监控探活共用;新增
WEKNORA_ALLOW_PRIVATE_HTTP 只放行 RFC1918/回环/链路本地。生产绑定只保留下拉,
保存后回报冻结/未冻结条数,已冻结目标不被改写。

(cherry picked from commit ad02e8bb9c)
This commit is contained in:
狐友 GXXP & Miku
2026-11-22 15:05:48 +08:00
committed by 姚章浩
parent 8c76c54d8e
commit 8b900a9ffb
44 changed files with 2798 additions and 198 deletions
@@ -0,0 +1,3 @@
DROP TABLE IF EXISTS weknora_environment_connection_tests;
DROP TABLE IF EXISTS weknora_environment_connection_history;
DROP TABLE IF EXISTS weknora_environment_connections;
@@ -0,0 +1,45 @@
-- 连接是「地址 + 写-only 密钥」的一份状态,绑定仍然是「对内/对外目标库」的另一份
-- 状态(routing_kb_bindings / production_kb_bindings)。两者刻意不合并:现场那张
-- 把两者塞进一张表的孤表正是重复列的来源。
--
-- 编号从 000083 起:现场 0.9.0 的 schema_migrations 已登记到 82,而迁移器按号跳过、
-- 没有顺序守卫 —— 76..82 号会被静默丢弃。仓内最大号到 75 不影响 83 的排序与执行。
CREATE TABLE weknora_environment_connections (
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0),
endpoint TEXT NOT NULL DEFAULT '',
key_ciphertext BYTEA NOT NULL DEFAULT '\x',
key_tail VARCHAR(8) NOT NULL DEFAULT '',
verification TEXT NOT NULL DEFAULT 'not_configured'
CHECK (verification IN ('not_configured','ok','unreachable','key_invalid','key_forbidden')),
library_count INTEGER NOT NULL DEFAULT 0 CHECK (library_count >= 0),
checked_at TIMESTAMPTZ,
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- 历史只记「有没有配过密钥」,不记尾号也不记密文:一个可审计的时间线不需要能
-- 反推出任何一位密钥。
CREATE TABLE weknora_environment_connection_history (
environment VARCHAR(16) NOT NULL CHECK (environment IN ('test','production')),
revision BIGINT NOT NULL,
endpoint TEXT NOT NULL,
key_configured BOOLEAN NOT NULL,
verification TEXT NOT NULL,
actor TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (environment, revision)
);
-- 「测通才可保存」需要一条可核对的证据:这次测试用的是哪个地址、哪把密钥(只存
-- 指纹)、结论如何。保存时按 (environment, endpoint, key_fingerprint, ok) 匹配。
CREATE TABLE weknora_environment_connection_tests (
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
endpoint TEXT NOT NULL,
key_fingerprint CHAR(64) NOT NULL CHECK (key_fingerprint ~ '^[0-9a-f]{64}$'),
outcome TEXT NOT NULL
CHECK (outcome IN ('ok','unreachable','key_invalid','key_forbidden')),
library_count INTEGER NOT NULL DEFAULT 0 CHECK (library_count >= 0),
message TEXT NOT NULL DEFAULT '',
checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
+20 -12
View File
@@ -11,51 +11,59 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 75 {
t.Fatalf("migration count = %d, want 75", len(migrations))
if len(migrations) != 76 {
t.Fatalf("migration count = %d, want 76", len(migrations))
}
// 83 把「连接(地址 + 写-only 密钥)」从文件引用搬进治理库;编号必须 ≥83,
// 因为现场 0.9.0 的 schema_migrations 已到 82,迁移器按号跳过且无顺序守卫。
if connections := migrations[len(migrations)-1]; connections.Version != 83 ||
!strings.Contains(connections.UpSQL, "weknora_environment_connections") ||
!strings.Contains(connections.UpSQL, "key_ciphertext") ||
!strings.Contains(connections.DownSQL, "DROP TABLE IF EXISTS weknora_environment_connections") {
t.Fatalf("migration 83 = %#v", connections)
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-1]; baseline.Version != 75 ||
if baseline := migrations[len(migrations)-2]; baseline.Version != 75 ||
!strings.Contains(baseline.UpSQL, "library_jobs_write_target") ||
!strings.Contains(baseline.UpSQL, "'baseline'") {
t.Fatalf("migration 75 = %#v", baseline)
}
// 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。
if executor := migrations[len(migrations)-2]; executor.Version != 74 ||
if executor := migrations[len(migrations)-3]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-3]; release.Version != 73 ||
if release := migrations[len(migrations)-4]; release.Version != 73 ||
!strings.Contains(release.UpSQL, "library_dead_letter_releases") {
t.Fatalf("migration 73 = %#v", release)
}
// 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。
if instance := migrations[len(migrations)-4]; instance.Version != 72 ||
if instance := migrations[len(migrations)-5]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-5]; level.Version != 71 ||
if level := migrations[len(migrations)-6]; level.Version != 71 ||
!strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") {
t.Fatalf("migration 71 = %#v", level)
}
if maint := migrations[len(migrations)-6]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[len(migrations)-7]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-7]; tail.Version != 69 ||
if tail := migrations[len(migrations)-8]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-8]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[len(migrations)-9]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-9]; last.Version != 67 ||
if last := migrations[len(migrations)-10]; last.Version != 67 ||
!strings.Contains(last.UpSQL, "library_release_authorizations") ||
!strings.Contains(last.UpSQL, "params_digest") {
t.Fatalf("migration 67 = %#v", last)
}
if flow := migrations[len(migrations)-10]; flow.Version != 66 ||
if flow := migrations[len(migrations)-11]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)
@@ -0,0 +1,203 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
)
// WeKnoraConnection is one environment's 地址 + 写-only 密钥. The ciphertext is
// opened only in the service layer; everything below this line treats it as an
// opaque blob so no query result can accidentally be rendered as a secret.
type WeKnoraConnection struct {
Environment string
Revision int64
Endpoint string
KeyCiphertext []byte
KeyTail string
Verification string
LibraryCount int
CheckedAt *time.Time
UpdatedBy string
UpdatedAt time.Time
}
// WeKnoraConnectionTest is the evidence a save needs: which endpoint, which key
// (fingerprint only) and what the last real listing said.
type WeKnoraConnectionTest struct {
Environment string
Endpoint string
KeyFingerprint string
Outcome string
LibraryCount int
Message string
CheckedAt time.Time
}
// LoadWeKnoraConnections reads both environments. A missing row is simply absent
// from the result: 「未配置」 is a state, not an error.
func (s *Store) LoadWeKnoraConnections(ctx context.Context) ([]WeKnoraConnection, error) {
rows, err := s.db.Query(ctx, `
SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at
FROM weknora_environment_connections
ORDER BY environment`)
if err != nil {
return nil, errors.New("load weknora connections")
}
defer rows.Close()
connections := make([]WeKnoraConnection, 0, 2)
for rows.Next() {
var connection WeKnoraConnection
if err := rows.Scan(&connection.Environment, &connection.Revision, &connection.Endpoint,
&connection.KeyCiphertext, &connection.KeyTail, &connection.Verification,
&connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt); err != nil {
return nil, errors.New("load weknora connections")
}
connections = append(connections, connection)
}
if rows.Err() != nil {
return nil, errors.New("load weknora connections")
}
return connections, nil
}
// LoadWeKnoraConnection reads one environment. The boolean is false when the
// environment was never configured.
func (s *Store) LoadWeKnoraConnection(ctx context.Context, environment string) (WeKnoraConnection, bool, error) {
var connection WeKnoraConnection
err := s.db.QueryRow(ctx, `
SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at
FROM weknora_environment_connections WHERE environment=$1`, environment).
Scan(&connection.Environment, &connection.Revision, &connection.Endpoint,
&connection.KeyCiphertext, &connection.KeyTail, &connection.Verification,
&connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return WeKnoraConnection{}, false, nil
}
if err != nil {
return WeKnoraConnection{}, false, errors.New("load weknora connection")
}
return connection, true, nil
}
// SaveWeKnoraConnection writes one revision and its history row in a single
// transaction. The advisory lock is per environment so two concurrent saves
// cannot both pick the same revision.
func (s *Store) SaveWeKnoraConnection(ctx context.Context, connection WeKnoraConnection, now time.Time) error {
if now.IsZero() {
return errors.New("weknora connection save requires a timestamp")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return fmt.Errorf("begin weknora connection save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('weknora_connection:'||$1))`, connection.Environment); err != nil {
return fmt.Errorf("lock weknora connection: %w", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_connections(environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
ON CONFLICT(environment) DO UPDATE SET
revision=EXCLUDED.revision,
endpoint=EXCLUDED.endpoint,
key_ciphertext=EXCLUDED.key_ciphertext,
key_tail=EXCLUDED.key_tail,
verification=EXCLUDED.verification,
library_count=EXCLUDED.library_count,
checked_at=EXCLUDED.checked_at,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`,
connection.Environment, connection.Revision, connection.Endpoint, connection.KeyCiphertext,
connection.KeyTail, connection.Verification, connection.LibraryCount, connection.CheckedAt,
connection.UpdatedBy, now); err != nil {
return errors.New("save weknora connection")
}
if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_connection_history(environment,revision,endpoint,key_configured,verification,actor,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(environment,revision) DO NOTHING`,
connection.Environment, connection.Revision, connection.Endpoint, len(connection.KeyCiphertext) > 0,
connection.Verification, connection.UpdatedBy, now); err != nil {
return errors.New("record weknora connection history")
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit weknora connection save: %w", err)
}
return nil
}
// SaveWeKnoraConnectionTest stores the outcome of the real listing a save will
// later point at. Only the key fingerprint is kept — never the key.
func (s *Store) SaveWeKnoraConnectionTest(ctx context.Context, result WeKnoraConnectionTest, now time.Time) error {
if now.IsZero() {
return errors.New("weknora connection test requires a timestamp")
}
if _, err := s.db.Exec(ctx, `
INSERT INTO weknora_environment_connection_tests(environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at)
VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(environment) DO UPDATE SET
endpoint=EXCLUDED.endpoint,
key_fingerprint=EXCLUDED.key_fingerprint,
outcome=EXCLUDED.outcome,
library_count=EXCLUDED.library_count,
message=EXCLUDED.message,
checked_at=EXCLUDED.checked_at`,
result.Environment, result.Endpoint, result.KeyFingerprint, result.Outcome,
result.LibraryCount, result.Message, now); err != nil {
return errors.New("save weknora connection test")
}
return nil
}
// LoadWeKnoraConnectionTest reads the last test for one environment.
func (s *Store) LoadWeKnoraConnectionTest(ctx context.Context, environment string) (WeKnoraConnectionTest, bool, error) {
var result WeKnoraConnectionTest
err := s.db.QueryRow(ctx, `
SELECT environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at
FROM weknora_environment_connection_tests WHERE environment=$1`, environment).
Scan(&result.Environment, &result.Endpoint, &result.KeyFingerprint, &result.Outcome,
&result.LibraryCount, &result.Message, &result.CheckedAt)
if errors.Is(err, pgx.ErrNoRows) {
return WeKnoraConnectionTest{}, false, nil
}
if err != nil {
return WeKnoraConnectionTest{}, false, errors.New("load weknora connection test")
}
return result, true, nil
}
// UpdateWeKnoraConnectionVerification refreshes the card state without touching
// the saved endpoint or ciphertext.
func (s *Store) UpdateWeKnoraConnectionVerification(ctx context.Context, environment, verification string, libraryCount int, checkedAt time.Time, now time.Time) error {
if _, err := s.db.Exec(ctx, `
UPDATE weknora_environment_connections
SET verification=$2, library_count=$3, checked_at=$4, updated_at=$5
WHERE environment=$1`, environment, verification, libraryCount, checkedAt, now); err != nil {
return errors.New("update weknora connection verification")
}
return nil
}
// ProductionExecutionCounts reports, for executions that are still in flight,
// how many items already have a frozen production target and how many do not yet.
// A production binding change never rewrites the frozen ones: an execution that
// already started keeps the knowledge base it was authorized against. Lifetime
// counts are deliberately excluded — completed executions are history, not
// something a binding change could still affect.
func (s *Store) ProductionExecutionCounts(ctx context.Context) (int, int, error) {
var frozen, retargetable int
if err := s.db.QueryRow(ctx, `
SELECT
COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''),
COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '')
FROM release_item_executions item
JOIN release_executions execution ON execution.id = item.release_execution_id
WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable); err != nil {
return 0, 0, errors.New("load production execution counts")
}
return frozen, retargetable, nil
}
@@ -0,0 +1,118 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// 连接(地址 + 写-only 密钥)是新的持久状态:一环境一行、修订递增、历史只记
// 「有没有配过密钥」。测试必须证明 000083 真能 up/down,而不是只证明 SQL 解析通过。
func TestWeKnoraConnectionsMigrationUpDownAndStore(t *testing.T) {
databaseURL := isolatedIntegrationDatabaseURL(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 = ApplyMigrations(ctx, pool); err != nil {
t.Fatalf("apply migrations: %v", err)
}
var applied bool
if err = pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = 83)").Scan(&applied); err != nil || !applied {
t.Fatalf("migration 83 not recorded: %v %v", applied, err)
}
store := NewStore(pool)
now := time.Date(2026, time.November, 22, 7, 0, 0, 0, time.UTC)
checked := now.Add(-time.Minute)
connection := WeKnoraConnection{
Environment: "production",
Revision: 2,
Endpoint: "http://172.29.151.11:18093",
KeyCiphertext: []byte{1, 2, 3, 4},
KeyTail: "9f2c",
Verification: "ok",
LibraryCount: 4,
CheckedAt: &checked,
UpdatedBy: "admin",
}
if err := store.SaveWeKnoraConnection(ctx, connection, now); err != nil {
t.Fatalf("save connection: %v", err)
}
loaded, exists, err := store.LoadWeKnoraConnection(ctx, "production")
if err != nil || !exists {
t.Fatalf("load connection: %v %v", exists, err)
}
if loaded.Endpoint != connection.Endpoint || loaded.Revision != 2 || loaded.KeyTail != "9f2c" || string(loaded.KeyCiphertext) != string(connection.KeyCiphertext) {
t.Fatalf("loaded = %+v", loaded)
}
var configured bool
var actor string
if err := pool.QueryRow(ctx, `SELECT key_configured,actor FROM weknora_environment_connection_history WHERE environment='production' AND revision=2`).Scan(&configured, &actor); err != nil {
t.Fatalf("history row: %v", err)
}
if !configured || actor != "admin" {
t.Fatalf("history = %v %q", configured, actor)
}
// 历史里不能出现尾号或密文:只有布尔。
var historyColumns int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='weknora_environment_connection_history' AND column_name IN ('key_tail','key_ciphertext')`).Scan(&historyColumns); err != nil {
t.Fatal(err)
}
if historyColumns != 0 {
t.Fatalf("history table exposes %d secret columns", historyColumns)
}
// 测试证据:同一环境只保留最后一次,且只存密钥指纹。
fingerprint := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
if err := store.SaveWeKnoraConnectionTest(ctx, WeKnoraConnectionTest{
Environment: "production", Endpoint: connection.Endpoint, KeyFingerprint: fingerprint,
Outcome: "ok", LibraryCount: 4, Message: "接口可达",
}, now); err != nil {
t.Fatalf("save test evidence: %v", err)
}
proof, found, err := store.LoadWeKnoraConnectionTest(ctx, "production")
if err != nil || !found || proof.KeyFingerprint != fingerprint || proof.Outcome != "ok" {
t.Fatalf("load test evidence = %+v %v %v", proof, found, err)
}
// 冻结/未冻结计数按 target_knowledge_base_id 判定,不能用 IS NULL。
frozen, retargetable, err := store.ProductionExecutionCounts(ctx)
if err != nil {
t.Fatalf("production execution counts: %v", err)
}
if frozen != 0 || retargetable != 0 {
t.Fatalf("empty execution counts = %d/%d", frozen, retargetable)
}
// down 必须只删这三张新表,不碰既有绑定表。
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatalf("rollback 83: %v", err)
}
for _, table := range []string{"weknora_environment_connections", "weknora_environment_connection_history", "weknora_environment_connection_tests"} {
var present bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=current_schema() AND table_name=$1)`, table).Scan(&present); err != nil {
t.Fatal(err)
}
if present {
t.Fatalf("%s survived the down migration", table)
}
}
for _, table := range []string{"routing_kb_bindings", "production_kb_bindings"} {
var present bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=current_schema() AND table_name=$1)`, table).Scan(&present); err != nil {
t.Fatal(err)
}
if !present {
t.Fatalf("%s must not be dropped by migration 83 down", table)
}
}
}