Files
knowledge-governance/internal/weknoraconn/service.go
T
狐友 GXXP & Miku ad02e8bb9c
build / build (push) Successful in 1m43s
feat(settings): 页面录入测试/生产 WeKnora 连接与密钥并收敛可达性判定
连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥,
页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功,
换地址或换密钥必须测通才能保存(迁移 000083)。

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

455 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
}
// 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:])
}