1f5bf72aec
网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。 克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个 目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项, 执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以 release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。 测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前 连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。 「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署 默认 ID,避免换绑实例后带过去旧对象的默认库。 验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户 的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。
419 lines
12 KiB
Go
419 lines
12 KiB
Go
// Package kbbinding 是「知识库绑定」的唯一服务端入口:按环境保存连接
|
|
// (地址 + 加密后的 API Key)和对内/对外知识库绑定,并提供候选人列库、
|
|
// 选库归属校验与消费者解析。旧的部署文件凭据/默认绑定在没有任何新行时
|
|
// 继续生效,所以升级不需要回填数据。
|
|
package kbbinding
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"knowledge-governance/internal/platform/weknora"
|
|
"knowledge-governance/internal/secretbox"
|
|
)
|
|
|
|
const (
|
|
EnvTest = "test"
|
|
EnvProduction = "production"
|
|
)
|
|
|
|
func Environments() []string { return []string{EnvTest, EnvProduction} }
|
|
|
|
func ValidEnvironment(value string) bool {
|
|
return value == EnvTest || value == EnvProduction
|
|
}
|
|
|
|
func EnvironmentLabel(value string) string {
|
|
if value == EnvProduction {
|
|
return "生产 090"
|
|
}
|
|
return "测试 090"
|
|
}
|
|
|
|
var (
|
|
ErrInvalid = errors.New("invalid knowledge base binding")
|
|
ErrConflict = errors.New("knowledge base binding revision conflict")
|
|
ErrKeyForwarding = errors.New("old key must not follow a new address")
|
|
ErrNotConfigured = errors.New("weknora connection is not configured")
|
|
ErrStorage = errors.New("secure binding storage is not ready")
|
|
ErrRejected = errors.New("weknora rejected the candidate connection")
|
|
ErrUnreachable = errors.New("weknora candidate connection is unreachable")
|
|
)
|
|
|
|
// View is the public projection. It never carries a key, ciphertext or any
|
|
// value derived from the key beyond "configured or not".
|
|
type View struct {
|
|
Environment string `json:"environment"`
|
|
Revision int64 `json:"revision"`
|
|
BaseURL string `json:"base_url"`
|
|
KeyConfigured bool `json:"key_configured"`
|
|
KeySource string `json:"key_source"`
|
|
InternalKBID string `json:"internal_kb_id"`
|
|
InternalKBName string `json:"internal_kb_name"`
|
|
ExternalKBID string `json:"external_kb_id"`
|
|
ExternalKBName string `json:"external_kb_name"`
|
|
Verification string `json:"verification"`
|
|
CheckedAt *time.Time `json:"checked_at"`
|
|
UpdatedBy string `json:"updated_by"`
|
|
UpdatedAt *time.Time `json:"updated_at"`
|
|
// Source says where this effective configuration comes from: a row saved on
|
|
// this page, or the pre-existing deployment file/default binding.
|
|
Source string `json:"source"`
|
|
StorageReady bool `json:"storage_ready"`
|
|
// Replanned / RetiredDuplicates only report what a save just did to 待入库
|
|
// rows that had never been uploaded; a plain read reports zeros.
|
|
Replanned int `json:"replanned"`
|
|
RetiredDuplicates int `json:"retired_duplicates"`
|
|
}
|
|
|
|
type Option struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
KnowledgeCount int64 `json:"knowledge_count"`
|
|
}
|
|
|
|
type Catalog struct {
|
|
Status string `json:"status"`
|
|
Message string `json:"message"`
|
|
Page int `json:"page"`
|
|
PageSize int `json:"page_size"`
|
|
Total int64 `json:"total"`
|
|
Options []Option `json:"options"`
|
|
}
|
|
|
|
type CatalogInput struct {
|
|
BaseRevision int64 `json:"base_revision"`
|
|
BaseURL string `json:"base_url"`
|
|
KeyAction string `json:"key_action"`
|
|
APIKey string `json:"api_key"`
|
|
Page int `json:"page"`
|
|
PageSize int `json:"page_size"`
|
|
}
|
|
|
|
type SaveInput struct {
|
|
BaseRevision int64 `json:"base_revision"`
|
|
BaseURL string `json:"base_url"`
|
|
KeyAction string `json:"key_action"`
|
|
APIKey string `json:"api_key"`
|
|
InternalKBID string `json:"internal_kb_id"`
|
|
ExternalKBID string `json:"external_kb_id"`
|
|
}
|
|
|
|
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
|
// reach the effective instance. It never leaves the server.
|
|
type Target struct {
|
|
BaseURL string
|
|
APIKey string
|
|
Revision int64
|
|
Source string
|
|
}
|
|
|
|
type Options struct {
|
|
MasterKeyFile string
|
|
Timeout time.Duration
|
|
// AllowDockerHTTP mirrors the per-environment client policy (a single-label
|
|
// docker host may be reached over plain HTTP in the internal network).
|
|
AllowDockerHTTP map[string]bool
|
|
// LegacyBaseURL resolves the pre-existing endpoint (web setting first, then
|
|
// the deployment env value). It is only consulted when no row exists.
|
|
LegacyBaseURL func(context.Context, string) string
|
|
// LegacyKey reads the deployment credential file. It is only consulted when
|
|
// no row exists, or when a keep action targets exactly that legacy address.
|
|
LegacyKey func(string) (string, error)
|
|
// LegacyBinding resolves the pre-existing internal/external binding ids.
|
|
LegacyBinding func(context.Context, string) (string, string, error)
|
|
Now func() time.Time
|
|
}
|
|
|
|
type DB interface {
|
|
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
|
Begin(ctx context.Context) (pgx.Tx, error)
|
|
}
|
|
|
|
type Store struct {
|
|
db DB
|
|
options Options
|
|
}
|
|
|
|
func New(db DB, options Options) *Store {
|
|
if options.Timeout <= 0 {
|
|
options.Timeout = 10 * time.Second
|
|
}
|
|
if options.Now == nil {
|
|
options.Now = time.Now
|
|
}
|
|
return &Store{db: db, options: options}
|
|
}
|
|
|
|
type stored struct {
|
|
Environment string
|
|
Revision int64
|
|
BaseURL string
|
|
KeyCiphertext []byte
|
|
InternalKBID string
|
|
ExternalKBID string
|
|
InternalKBName string
|
|
ExternalKBName string
|
|
Verification string
|
|
CheckedAt *time.Time
|
|
UpdatedBy string
|
|
UpdatedAt *time.Time
|
|
}
|
|
|
|
const bindingColumns = `environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at`
|
|
|
|
func scanStored(row pgx.Row) (stored, bool, error) {
|
|
var value stored
|
|
err := row.Scan(&value.Environment, &value.Revision, &value.BaseURL, &value.KeyCiphertext,
|
|
&value.InternalKBID, &value.ExternalKBID, &value.InternalKBName, &value.ExternalKBName,
|
|
&value.Verification, &value.CheckedAt, &value.UpdatedBy, &value.UpdatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return stored{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return stored{}, false, err
|
|
}
|
|
return value, true, nil
|
|
}
|
|
|
|
func (s *Store) load(ctx context.Context, env string) (stored, bool, error) {
|
|
if !ValidEnvironment(env) {
|
|
return stored{}, false, ErrInvalid
|
|
}
|
|
return scanStored(s.db.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1`, env))
|
|
}
|
|
|
|
func (s *Store) StorageReady() bool {
|
|
return s.loadBox() != nil
|
|
}
|
|
|
|
func (s *Store) loadBox() *secretbox.Box {
|
|
box, err := secretbox.Load(s.options.MasterKeyFile)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return box
|
|
}
|
|
|
|
func (s *Store) legacyBaseURL(ctx context.Context, env string) string {
|
|
if s.options.LegacyBaseURL == nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(s.options.LegacyBaseURL(ctx, env))
|
|
}
|
|
|
|
func (s *Store) legacyKey(env string) (string, error) {
|
|
if s.options.LegacyKey == nil {
|
|
return "", nil
|
|
}
|
|
value, err := s.options.LegacyKey(env)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return strings.TrimSpace(value), nil
|
|
}
|
|
|
|
// List returns both environments' effective views for the page header and the
|
|
// environment switch. Names are best-effort: an unreachable instance yields
|
|
// short ids instead of hiding the binding.
|
|
func (s *Store) List(ctx context.Context) ([]View, error) {
|
|
views := make([]View, 0, 2)
|
|
for _, env := range Environments() {
|
|
view, err := s.Get(ctx, env)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
views = append(views, view)
|
|
}
|
|
return views, nil
|
|
}
|
|
|
|
func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
|
saved, found, err := s.load(ctx, env)
|
|
if err != nil {
|
|
return View{}, err
|
|
}
|
|
view := View{Environment: env, StorageReady: s.StorageReady(), Source: "legacy"}
|
|
if found {
|
|
view.Revision = saved.Revision
|
|
view.BaseURL = saved.BaseURL
|
|
view.KeyConfigured = len(saved.KeyCiphertext) > 0
|
|
view.KeySource = keySource(view.KeyConfigured)
|
|
view.InternalKBID = saved.InternalKBID
|
|
view.InternalKBName = saved.InternalKBName
|
|
view.ExternalKBID = saved.ExternalKBID
|
|
view.ExternalKBName = saved.ExternalKBName
|
|
view.Verification = saved.Verification
|
|
view.CheckedAt = saved.CheckedAt
|
|
view.UpdatedBy = saved.UpdatedBy
|
|
view.UpdatedAt = saved.UpdatedAt
|
|
view.Source = "web"
|
|
return view, nil
|
|
}
|
|
// Legacy fallback: exactly what the consumers use before any page save.
|
|
view.BaseURL = s.legacyBaseURL(ctx, env)
|
|
if key, keyErr := s.legacyKey(env); keyErr == nil && key != "" {
|
|
view.KeyConfigured = true
|
|
view.KeySource = "file"
|
|
}
|
|
if s.options.LegacyBinding != nil {
|
|
internal, external, bindErr := s.options.LegacyBinding(ctx, env)
|
|
if bindErr != nil {
|
|
return View{}, bindErr
|
|
}
|
|
view.InternalKBID = internal
|
|
view.ExternalKBID = external
|
|
}
|
|
view.Verification = "legacy"
|
|
s.fillNames(ctx, &view)
|
|
return view, nil
|
|
}
|
|
|
|
func keySource(configured bool) string {
|
|
if configured {
|
|
return "sealed"
|
|
}
|
|
return "none"
|
|
}
|
|
|
|
// fillNames reads names from the effective instance for the legacy view. A
|
|
// failure leaves names empty; ids still identify the binding.
|
|
func (s *Store) fillNames(ctx context.Context, view *View) {
|
|
if view.BaseURL == "" || (view.InternalKBID == "" && view.ExternalKBID == "") {
|
|
return
|
|
}
|
|
// 只是把 ID 换成名字:不能让一次不可达的旧实例拖住整个页面读取。
|
|
namesCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
defer cancel()
|
|
key, err := s.legacyKey(view.Environment)
|
|
if err != nil || key == "" {
|
|
return
|
|
}
|
|
client, err := s.client(view.BaseURL, key, view.Environment)
|
|
if err != nil {
|
|
return
|
|
}
|
|
names := map[string]string{}
|
|
page := 1
|
|
for page <= 20 {
|
|
result, err := client.ListKnowledgeBasesPage(namesCtx, page, 100)
|
|
if err != nil {
|
|
break
|
|
}
|
|
for _, base := range result.Items {
|
|
names[base.ID] = base.Name
|
|
}
|
|
if result.Total <= int64(page*100) || len(result.Items) < 100 {
|
|
break
|
|
}
|
|
page++
|
|
}
|
|
view.InternalKBName = names[view.InternalKBID]
|
|
view.ExternalKBName = names[view.ExternalKBID]
|
|
}
|
|
|
|
// Resolve returns the effective connection consumers must use. A saved row is
|
|
// authoritative: if its key cannot be opened we fail closed instead of falling
|
|
// back to the file credential (that would send the old key to a new address).
|
|
func (s *Store) Resolve(ctx context.Context, env string) (Target, error) {
|
|
saved, found, err := s.load(ctx, env)
|
|
if err != nil {
|
|
return Target{}, err
|
|
}
|
|
if found {
|
|
if saved.BaseURL == "" {
|
|
return Target{}, ErrNotConfigured
|
|
}
|
|
if len(saved.KeyCiphertext) == 0 {
|
|
return Target{}, ErrNotConfigured
|
|
}
|
|
box := s.loadBox()
|
|
if box == nil {
|
|
return Target{}, ErrStorage
|
|
}
|
|
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
|
if err != nil {
|
|
return Target{}, ErrStorage
|
|
}
|
|
return Target{BaseURL: saved.BaseURL, APIKey: string(raw), Revision: saved.Revision, Source: "web"}, nil
|
|
}
|
|
baseURL := s.legacyBaseURL(ctx, env)
|
|
key, err := s.legacyKey(env)
|
|
if err != nil {
|
|
return Target{}, err
|
|
}
|
|
if baseURL == "" || key == "" {
|
|
return Target{}, ErrNotConfigured
|
|
}
|
|
return Target{BaseURL: baseURL, APIKey: key, Source: "legacy"}, nil
|
|
}
|
|
|
|
// ResolveBaseURL is for health probes that only need the endpoint (no key).
|
|
func (s *Store) ResolveBaseURL(ctx context.Context, env string) string {
|
|
if saved, found, err := s.load(ctx, env); err == nil && found && saved.BaseURL != "" {
|
|
return saved.BaseURL
|
|
}
|
|
return s.legacyBaseURL(ctx, env)
|
|
}
|
|
|
|
func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey string, saved stored, found bool) (string, error) {
|
|
switch action {
|
|
case "keep":
|
|
if apiKey != "" {
|
|
return "", ErrInvalid
|
|
}
|
|
if found {
|
|
if saved.BaseURL != baseURL {
|
|
return "", ErrKeyForwarding
|
|
}
|
|
if len(saved.KeyCiphertext) == 0 {
|
|
return "", ErrNotConfigured
|
|
}
|
|
box := s.loadBox()
|
|
if box == nil {
|
|
return "", ErrStorage
|
|
}
|
|
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
|
if err != nil {
|
|
return "", ErrStorage
|
|
}
|
|
return string(raw), nil
|
|
}
|
|
// First save on an upgraded deployment: keeping the deployment file key
|
|
// is allowed only for exactly that legacy address.
|
|
if s.legacyBaseURL(ctx, env) != baseURL {
|
|
return "", ErrKeyForwarding
|
|
}
|
|
return s.legacyKey(env)
|
|
case "replace":
|
|
if !validAPIKey(apiKey) {
|
|
return "", ErrInvalid
|
|
}
|
|
return apiKey, nil
|
|
default:
|
|
return "", ErrInvalid
|
|
}
|
|
}
|
|
|
|
func validAPIKey(value string) bool {
|
|
return value != "" && len(value) <= 4096 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\r\n\x00")
|
|
}
|
|
|
|
func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) {
|
|
return weknora.NewClient(weknora.ClientConfig{
|
|
BaseURL: baseURL,
|
|
APIKey: apiKey,
|
|
Timeout: s.options.Timeout,
|
|
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
|
|
})
|
|
}
|
|
|
|
func keyAAD(env string, revision int64) string {
|
|
return "weknora-binding:" + env + ":" + strconv.FormatInt(revision, 10)
|
|
}
|