Files
knowledge-governance/internal/weknoraconn/service.go
T
狐友 GXXP & LEN aac8538372
build / build (push) Successful in 1m48s
fix(settings): 绑定留档名称并按旧目标重指向待入库
- 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID
- 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库
- 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key
- 生产换绑返回重指向/退休数量,页面提示与测试侧一致

验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
2026-11-23 12:47:22 +08:00

470 lines
16 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package weknoraconn owns the two WeKnora connections the console configures:
// endpoint + write-only API key per environment, with a real listing as the only
// proof a configuration is usable.
//
// It deliberately stores no knowledge-base binding. Which base receives 对内 /
// 对外 content stays in routing_kb_bindings / production_kb_bindings, because one
// meaning may only have one home.
package weknoraconn
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"strconv"
"strings"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/sealedsecret"
)
const (
EnvironmentTest = "test"
EnvironmentProduction = "production"
KeyActionKeep = "keep"
KeyActionReplace = "replace"
KeyActionClear = "clear"
// Outcome vocabulary shared by the API, the stored evidence and the page.
OutcomeOK = "ok"
OutcomeUnreachable = "unreachable"
OutcomeKeyInvalid = "key_invalid"
OutcomeKeyForbidden = "key_forbidden"
// VerificationNotConfigured means there is nothing to verify yet.
VerificationNotConfigured = "not_configured"
// proofTTL bounds how long a successful 测试连接 vouches for a candidate.
proofTTL = 15 * time.Minute
)
var (
ErrInvalid = errors.New("weknora connection request is invalid")
ErrNotFound = errors.New("unknown weknora environment")
ErrStaleRevision = errors.New("weknora connection revision is stale")
ErrNotTested = errors.New("weknora connection must be tested before saving")
ErrStorageUnavailable = errors.New("weknora connection secret storage is unavailable")
)
// Store is the persistence the service needs. The postgres store implements it.
type Store interface {
LoadWeKnoraConnection(ctx context.Context, environment string) (postgresstore.WeKnoraConnection, bool, error)
LoadWeKnoraConnections(ctx context.Context) ([]postgresstore.WeKnoraConnection, error)
SaveWeKnoraConnection(ctx context.Context, connection postgresstore.WeKnoraConnection, now time.Time) error
SaveWeKnoraConnectionTest(ctx context.Context, result postgresstore.WeKnoraConnectionTest, now time.Time) error
LoadWeKnoraConnectionTest(ctx context.Context, environment string) (postgresstore.WeKnoraConnectionTest, bool, error)
UpdateWeKnoraConnectionVerification(ctx context.Context, environment, verification string, libraryCount int, checkedAt time.Time, now time.Time) error
}
// KnowledgeBaseLister is the narrow client the service needs; tests inject it.
type KnowledgeBaseLister interface {
ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error)
}
type Config struct {
// MasterKeyFile is the 0600 32-byte master key. Empty or unreadable means
// the page can read state but cannot store a key — reported, never faked.
MasterKeyFile string
// AllowPrivateHTTP follows WEKNORA_ALLOW_PRIVATE_HTTP: same-LAN plain http
// is usable, public http is not.
AllowPrivateHTTP bool
Timeout time.Duration
Now func() time.Time
// NewLister is overridable in tests. Production leaves it nil.
NewLister func(endpoint, apiKey string) (KnowledgeBaseLister, error)
}
type Service struct {
store Store
config Config
}
func New(store Store, config Config) *Service {
if config.Timeout <= 0 {
config.Timeout = 10 * time.Second
}
if config.Now == nil {
config.Now = time.Now
}
return &Service{store: store, config: config}
}
// View is the page projection. It never carries the key or the ciphertext.
type View struct {
Environment string `json:"environment"`
Endpoint string `json:"endpoint"`
KeyConfigured bool `json:"key_configured"`
KeyTail string `json:"key_tail"`
Verification string `json:"verification"`
LibraryCount int `json:"library_count"`
CheckedAt *time.Time `json:"checked_at"`
UpdatedBy string `json:"updated_by"`
Revision int64 `json:"revision"`
StorageReady bool `json:"storage_ready"`
}
// TestInput is one 测试连接 request. An empty endpoint means "the saved one"; an
// empty key_action means keep.
type TestInput struct {
Endpoint string `json:"endpoint"`
APIKey string `json:"api_key"`
KeyAction string `json:"key_action"`
}
type TestResult struct {
Environment string `json:"environment"`
Endpoint string `json:"endpoint"`
Outcome string `json:"outcome"`
LibraryCount int `json:"library_count"`
Message string `json:"message"`
CheckedAt time.Time `json:"checked_at"`
}
type SaveInput struct {
Endpoint string `json:"endpoint"`
APIKey string `json:"api_key"`
KeyAction string `json:"key_action"`
BaseRevision int64 `json:"base_revision"`
}
func ValidEnvironment(value string) bool {
return value == EnvironmentTest || value == EnvironmentProduction
}
// View reads both environments, or one when environment is non-empty. A missing
// row is projected as 未配置 so the page has a stable shape.
func (service *Service) View(ctx context.Context, environment string) ([]View, error) {
stored, err := service.store.LoadWeKnoraConnections(ctx)
if err != nil {
return nil, err
}
byEnvironment := make(map[string]postgresstore.WeKnoraConnection, len(stored))
for _, connection := range stored {
byEnvironment[connection.Environment] = connection
}
environments := []string{EnvironmentTest, EnvironmentProduction}
if environment != "" {
if !ValidEnvironment(environment) {
return nil, ErrNotFound
}
environments = []string{environment}
}
_, masterKeyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
views := make([]View, 0, len(environments))
for _, name := range environments {
connection := byEnvironment[name]
verification := connection.Verification
if verification == "" {
verification = VerificationNotConfigured
}
views = append(views, View{
Environment: name,
Endpoint: connection.Endpoint,
KeyConfigured: len(connection.KeyCiphertext) > 0,
KeyTail: connection.KeyTail,
Verification: verification,
LibraryCount: connection.LibraryCount,
CheckedAt: connection.CheckedAt,
UpdatedBy: connection.UpdatedBy,
Revision: connection.Revision,
StorageReady: masterKeyErr == nil,
})
}
return views, nil
}
// Test performs the real GET /api/v1/knowledge-bases against the candidate
// endpoint and key, and records the outcome as the evidence a later save needs.
func (service *Service) Test(ctx context.Context, environment string, input TestInput) (TestResult, error) {
if !ValidEnvironment(environment) {
return TestResult{}, ErrNotFound
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return TestResult{}, err
}
endpoint := strings.TrimSpace(input.Endpoint)
if endpoint == "" && exists {
endpoint = saved.Endpoint
}
if endpoint == "" {
return TestResult{}, ErrInvalid
}
action := normalizeKeyAction(input.KeyAction)
apiKey, err := service.candidateKey(saved, exists, action, input.APIKey)
if err != nil {
return TestResult{}, err
}
now := service.config.Now().UTC()
result := TestResult{Environment: environment, Endpoint: endpoint, CheckedAt: now}
if !weknora.HTTPAllowed(endpoint, weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}) {
result.Outcome = OutcomeUnreachable
result.Message = "地址不可达:只接受 https,或已放行的私网/回环 http 地址"
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
lister, err := service.newLister(endpoint, apiKey)
if err != nil {
result.Outcome = OutcomeUnreachable
result.Message = "地址不可达:" + err.Error()
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
probeCtx, cancel := context.WithTimeout(ctx, service.config.Timeout)
defer cancel()
bases, listErr := lister.ListKnowledgeBases(probeCtx)
if listErr != nil {
result.Outcome, result.Message = classifyListError(listErr)
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
result.Outcome = OutcomeOK
result.LibraryCount = len(bases)
result.Message = "接口可达 · 已读到 " + strconv.Itoa(len(bases)) + " 个知识库"
if recordErr := service.recordTest(ctx, result, apiKey); recordErr != nil {
// The listing worked but the proof did not land: say so now, because the
// save gate will refuse this configuration a moment later.
result.Message += "(测试证据未能落库,保存会被拒绝,请重试)"
}
// The card may only claim 「可达」 for the configuration it actually probed.
if exists && action != KeyActionReplace && endpoint == saved.Endpoint {
_ = service.store.UpdateWeKnoraConnectionVerification(ctx, environment, result.Outcome, result.LibraryCount, result.CheckedAt, now)
}
return result, nil
}
// Save stores a tested configuration. A new key or a new endpoint must have a
// successful test behind it; keeping a tested configuration is not blocked by a
// jittery endpoint.
func (service *Service) Save(ctx context.Context, environment string, input SaveInput, actor string) (View, error) {
if !ValidEnvironment(environment) {
return View{}, ErrNotFound
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return View{}, err
}
endpoint := strings.TrimSpace(input.Endpoint)
if endpoint == "" {
return View{}, ErrInvalid
}
action := normalizeKeyAction(input.KeyAction)
if exists && input.BaseRevision != saved.Revision {
return View{}, ErrStaleRevision
}
if exists && endpoint != saved.Endpoint && action != KeyActionReplace {
return View{}, ErrInvalid
}
apiKey, err := service.candidateKey(saved, exists, action, input.APIKey)
if err != nil {
return View{}, err
}
now := service.config.Now().UTC()
revision := int64(1)
if exists {
revision = saved.Revision + 1
}
verification := VerificationNotConfigured
libraryCount := 0
var checkedAt *time.Time
if apiKey != "" {
if !weknora.HTTPAllowed(endpoint, weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}) {
return View{}, ErrInvalid
}
if !exists || action == KeyActionReplace || endpoint != saved.Endpoint {
proof, found, proofErr := service.store.LoadWeKnoraConnectionTest(ctx, environment)
if proofErr != nil {
return View{}, proofErr
}
if !found || proof.Outcome != OutcomeOK || proof.Endpoint != endpoint ||
proof.KeyFingerprint != fingerprint(apiKey) || now.Sub(proof.CheckedAt) > proofTTL {
return View{}, ErrNotTested
}
libraryCount = proof.LibraryCount
checkedAt = &proof.CheckedAt
} else {
libraryCount = saved.LibraryCount
checkedAt = saved.CheckedAt
}
verification = OutcomeOK
}
sealed := []byte{}
if apiKey != "" {
masterKey, keyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if keyErr != nil {
return View{}, ErrStorageUnavailable
}
sealed, err = sealedsecret.Seal(masterKey, apiKey, sealedsecret.AAD("weknora-connection", environment, revision))
if err != nil {
return View{}, ErrStorageUnavailable
}
}
connection := postgresstore.WeKnoraConnection{
Environment: environment,
Revision: revision,
Endpoint: endpoint,
KeyCiphertext: sealed,
KeyTail: keyTail(apiKey),
Verification: verification,
LibraryCount: libraryCount,
CheckedAt: checkedAt,
UpdatedBy: actor,
}
if err := service.store.SaveWeKnoraConnection(ctx, connection, now); err != nil {
return View{}, err
}
views, err := service.View(ctx, environment)
if err != nil {
return View{}, err
}
return views[0], nil
}
// Resolve returns the endpoint and key the platform should use for one
// environment. It is the single source other features read instead of guessing
// from environment variables.
func (service *Service) Resolve(ctx context.Context, environment string) (string, string, bool) {
if !ValidEnvironment(environment) {
return "", "", false
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil || !exists || saved.Endpoint == "" || len(saved.KeyCiphertext) == 0 {
return "", "", false
}
masterKey, keyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if keyErr != nil {
return "", "", false
}
apiKey, openErr := sealedsecret.Open(masterKey, saved.KeyCiphertext, sealedsecret.AAD("weknora-connection", environment, saved.Revision))
if openErr != nil {
return "", "", false
}
return saved.Endpoint, apiKey, true
}
// Configured reports whether an operator has saved a connection row for this
// environment. It distinguishes "never configured, use bootstrap files" from
// "configured but the key was cleared", which must fail closed instead of
// silently falling back to an old file key.
func (service *Service) Configured(ctx context.Context, environment string) (bool, error) {
if !ValidEnvironment(environment) {
return false, ErrNotFound
}
_, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return false, err
}
return exists, nil
}
// HTTPPolicy exposes the endpoint policy the client uses, so a caller that
// builds its own client stays in agreement with the service.
func (service *Service) HTTPPolicy() weknora.HTTPPolicy {
return weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}
}
func (service *Service) candidateKey(saved postgresstore.WeKnoraConnection, exists bool, action, inputKey string) (string, error) {
switch action {
case KeyActionClear:
return "", nil
case KeyActionReplace:
trimmed := strings.TrimSpace(inputKey)
if trimmed == "" {
return "", ErrInvalid
}
return trimmed, nil
default:
if !exists || len(saved.KeyCiphertext) == 0 {
return "", ErrInvalid
}
masterKey, err := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if err != nil {
return "", ErrStorageUnavailable
}
apiKey, err := sealedsecret.Open(masterKey, saved.KeyCiphertext, sealedsecret.AAD("weknora-connection", saved.Environment, saved.Revision))
if err != nil {
return "", ErrStorageUnavailable
}
return apiKey, nil
}
}
func (service *Service) newLister(endpoint, apiKey string) (KnowledgeBaseLister, error) {
if service.config.NewLister != nil {
return service.config.NewLister(endpoint, apiKey)
}
return weknora.NewClient(weknora.ClientConfig{
BaseURL: endpoint,
APIKey: apiKey,
Timeout: service.config.Timeout,
AllowPrivateHTTP: service.config.AllowPrivateHTTP,
})
}
func (service *Service) recordTest(ctx context.Context, result TestResult, apiKey string) error {
return service.store.SaveWeKnoraConnectionTest(ctx, postgresstore.WeKnoraConnectionTest{
Environment: result.Environment,
Endpoint: result.Endpoint,
KeyFingerprint: fingerprint(apiKey),
Outcome: result.Outcome,
LibraryCount: result.LibraryCount,
Message: result.Message,
}, result.CheckedAt)
}
// classifyListError maps one failed listing onto the four answers the page
// promises, so 「密钥无效」 and 「密钥无权限」 never collapse into one message.
func classifyListError(err error) (string, string) {
var httpErr *weknora.HTTPError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode {
case 401:
return OutcomeKeyInvalid, "密钥无效:该实例拒绝了这把 API Key(401)"
case 403:
return OutcomeKeyForbidden, "密钥无权限读取知识库列表(403)"
}
}
switch {
case errors.Is(err, context.DeadlineExceeded):
return OutcomeUnreachable, "地址不可达:请求超时"
default:
var netErr interface{ Timeout() bool }
if errors.As(err, &netErr) && netErr.Timeout() {
return OutcomeUnreachable, "地址不可达:请求超时"
}
return OutcomeUnreachable, "地址不可达:连接失败"
}
}
func normalizeKeyAction(action string) string {
switch strings.TrimSpace(action) {
case KeyActionReplace:
return KeyActionReplace
case KeyActionClear:
return KeyActionClear
default:
return KeyActionKeep
}
}
func fingerprint(apiKey string) string {
sum := sha256.Sum256([]byte(apiKey))
return hex.EncodeToString(sum[:])
}
// keyTail is the only part of a key the page may show: the last four characters.
func keyTail(apiKey string) string {
if apiKey == "" {
return ""
}
runes := []rune(apiKey)
if len(runes) <= 4 {
return string(runes)
}
return string(runes[len(runes)-4:])
}