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:
@@ -0,0 +1,454 @@
|
||||
// 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:])
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package weknoraconn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
type fakeStore struct {
|
||||
connections map[string]postgres.WeKnoraConnection
|
||||
tests map[string]postgres.WeKnoraConnectionTest
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{
|
||||
connections: map[string]postgres.WeKnoraConnection{},
|
||||
tests: map[string]postgres.WeKnoraConnectionTest{},
|
||||
}
|
||||
}
|
||||
|
||||
func (store *fakeStore) LoadWeKnoraConnection(_ context.Context, environment string) (postgres.WeKnoraConnection, bool, error) {
|
||||
connection, ok := store.connections[environment]
|
||||
return connection, ok, nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) LoadWeKnoraConnections(context.Context) ([]postgres.WeKnoraConnection, error) {
|
||||
result := make([]postgres.WeKnoraConnection, 0, len(store.connections))
|
||||
for _, connection := range store.connections {
|
||||
result = append(result, connection)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) SaveWeKnoraConnection(_ context.Context, connection postgres.WeKnoraConnection, _ time.Time) error {
|
||||
store.connections[connection.Environment] = connection
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) SaveWeKnoraConnectionTest(_ context.Context, result postgres.WeKnoraConnectionTest, now time.Time) error {
|
||||
result.CheckedAt = now
|
||||
store.tests[result.Environment] = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) LoadWeKnoraConnectionTest(_ context.Context, environment string) (postgres.WeKnoraConnectionTest, bool, error) {
|
||||
result, ok := store.tests[environment]
|
||||
return result, ok, nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) UpdateWeKnoraConnectionVerification(_ context.Context, environment, verification string, libraryCount int, checkedAt time.Time, _ time.Time) error {
|
||||
connection, ok := store.connections[environment]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
connection.Verification = verification
|
||||
connection.LibraryCount = libraryCount
|
||||
connection.CheckedAt = &checkedAt
|
||||
store.connections[environment] = connection
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeLister struct {
|
||||
bases []weknora.KnowledgeBase
|
||||
err error
|
||||
}
|
||||
|
||||
func (lister fakeLister) ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
return lister.bases, lister.err
|
||||
}
|
||||
|
||||
func newService(t *testing.T, store Store, lister fakeLister) *Service {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "master.key")
|
||||
if err := os.WriteFile(path, []byte("0123456789abcdef0123456789abcdef"), 0o600); err != nil {
|
||||
t.Fatalf("write master key: %v", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatalf("chmod master key: %v", err)
|
||||
}
|
||||
now := time.Date(2026, 11, 22, 7, 0, 0, 0, time.UTC)
|
||||
return New(store, Config{
|
||||
MasterKeyFile: path,
|
||||
AllowPrivateHTTP: true,
|
||||
Timeout: time.Second,
|
||||
Now: func() time.Time { return now },
|
||||
NewLister: func(endpoint, apiKey string) (KnowledgeBaseLister, error) {
|
||||
if endpoint == "" || apiKey == "" {
|
||||
return nil, errors.New("missing endpoint or key")
|
||||
}
|
||||
return lister, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestTestClassifiesTheFourAnswers(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
wantOutcome string
|
||||
wantMessage string
|
||||
}{
|
||||
{"unauthorized", &weknora.HTTPError{StatusCode: 401}, OutcomeKeyInvalid, "密钥无效"},
|
||||
{"forbidden", &weknora.HTTPError{StatusCode: 403}, OutcomeKeyForbidden, "密钥无权限"},
|
||||
{"timeout", context.DeadlineExceeded, OutcomeUnreachable, "地址不可达"},
|
||||
{"refused", errors.New("dial tcp: connection refused"), OutcomeUnreachable, "地址不可达"},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
service := newService(t, newFakeStore(), fakeLister{err: testCase.err})
|
||||
result, err := service.Test(context.Background(), EnvironmentTest, TestInput{
|
||||
Endpoint: "http://127.0.0.1:8092", APIKey: "sk-test-1234", KeyAction: KeyActionReplace,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: Test() error = %v", testCase.name, err)
|
||||
}
|
||||
if result.Outcome != testCase.wantOutcome {
|
||||
t.Fatalf("%s: outcome = %q, want %q", testCase.name, result.Outcome, testCase.wantOutcome)
|
||||
}
|
||||
if !contains(result.Message, testCase.wantMessage) {
|
||||
t.Fatalf("%s: message = %q, want it to mention %q", testCase.name, result.Message, testCase.wantMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestSuccessReportsLibraryCount(t *testing.T) {
|
||||
service := newService(t, newFakeStore(), fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}, {ID: "b"}, {ID: "c"}}})
|
||||
result, err := service.Test(context.Background(), EnvironmentProduction, TestInput{
|
||||
Endpoint: "http://172.29.151.11:18093", APIKey: "prod-key-9999", KeyAction: KeyActionReplace,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Test() error = %v", err)
|
||||
}
|
||||
if result.Outcome != OutcomeOK || result.LibraryCount != 3 {
|
||||
t.Fatalf("result = %+v", result)
|
||||
}
|
||||
if !contains(result.Message, "3 个知识库") {
|
||||
t.Fatalf("message = %q", result.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveRequiresTestProofAndProjectsTailOnly(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}, {ID: "b"}}})
|
||||
ctx := context.Background()
|
||||
save := SaveInput{Endpoint: "http://127.0.0.1:8092", APIKey: "sk-live-abcd", KeyAction: KeyActionReplace}
|
||||
if _, err := service.Save(ctx, EnvironmentTest, save, "admin"); !errors.Is(err, ErrNotTested) {
|
||||
t.Fatalf("Save() without a test = %v, want ErrNotTested", err)
|
||||
}
|
||||
if _, err := service.Test(ctx, EnvironmentTest, TestInput{Endpoint: save.Endpoint, APIKey: save.APIKey, KeyAction: KeyActionReplace}); err != nil {
|
||||
t.Fatalf("Test() error = %v", err)
|
||||
}
|
||||
view, err := service.Save(ctx, EnvironmentTest, save, "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
if !view.KeyConfigured || view.KeyTail != "abcd" || view.Verification != OutcomeOK || view.LibraryCount != 2 {
|
||||
t.Fatalf("view = %+v", view)
|
||||
}
|
||||
if view.Revision != 1 {
|
||||
t.Fatalf("revision = %d", view.Revision)
|
||||
}
|
||||
endpoint, apiKey, ok := service.Resolve(ctx, EnvironmentTest)
|
||||
if !ok || endpoint != save.Endpoint || apiKey != save.APIKey {
|
||||
t.Fatalf("Resolve() = %q %q %v", endpoint, apiKey, ok)
|
||||
}
|
||||
// The proof is bound to the key: another key must not reuse it.
|
||||
other := SaveInput{Endpoint: save.Endpoint, APIKey: "sk-live-zzzz", KeyAction: KeyActionReplace, BaseRevision: 1}
|
||||
if _, err := service.Save(ctx, EnvironmentTest, other, "admin"); !errors.Is(err, ErrNotTested) {
|
||||
t.Fatalf("Save() with a different untested key = %v, want ErrNotTested", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveRejectsEndpointChangeWithoutReenteringKey(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}}})
|
||||
ctx := context.Background()
|
||||
first := SaveInput{Endpoint: "http://127.0.0.1:8092", APIKey: "sk-live-abcd", KeyAction: KeyActionReplace}
|
||||
if _, err := service.Test(ctx, EnvironmentTest, TestInput{Endpoint: first.Endpoint, APIKey: first.APIKey, KeyAction: KeyActionReplace}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Save(ctx, EnvironmentTest, first, "admin"); err != nil {
|
||||
t.Fatalf("first Save() error = %v", err)
|
||||
}
|
||||
if _, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:9092", KeyAction: KeyActionKeep, BaseRevision: 1}, "admin"); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("endpoint change with keep = %v, want ErrInvalid", err)
|
||||
}
|
||||
if _, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:8092", KeyAction: KeyActionKeep, BaseRevision: 7}, "admin"); !errors.Is(err, ErrStaleRevision) {
|
||||
t.Fatalf("stale revision = %v, want ErrStaleRevision", err)
|
||||
}
|
||||
// Keeping the tested configuration must not be blocked by proof age.
|
||||
view, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:8092", KeyAction: KeyActionKeep, BaseRevision: 1}, "admin")
|
||||
if err != nil || view.Verification != OutcomeOK || view.KeyTail != "abcd" {
|
||||
t.Fatalf("keep Save() = %+v, %v", view, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearKeyResetsVerification(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}}})
|
||||
ctx := context.Background()
|
||||
if _, err := service.Test(ctx, EnvironmentProduction, TestInput{Endpoint: "https://prod.example", APIKey: "prod-key", KeyAction: KeyActionReplace}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Save(ctx, EnvironmentProduction, SaveInput{Endpoint: "https://prod.example", APIKey: "prod-key", KeyAction: KeyActionReplace}, "admin"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view, err := service.Save(ctx, EnvironmentProduction, SaveInput{Endpoint: "https://prod.example", KeyAction: KeyActionClear, BaseRevision: 1}, "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("clear Save() error = %v", err)
|
||||
}
|
||||
if view.KeyConfigured || view.KeyTail != "" || view.Verification != VerificationNotConfigured {
|
||||
t.Fatalf("cleared view = %+v", view)
|
||||
}
|
||||
if _, _, ok := service.Resolve(ctx, EnvironmentProduction); ok {
|
||||
t.Fatal("a cleared connection must not resolve")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicHTTPIsRefusedEvenWhenPrivateHTTPIsAllowed(t *testing.T) {
|
||||
service := newService(t, newFakeStore(), fakeLister{})
|
||||
result, err := service.Test(context.Background(), EnvironmentTest, TestInput{Endpoint: "http://weknora.example", APIKey: "k", KeyAction: KeyActionReplace})
|
||||
if err != nil {
|
||||
t.Fatalf("Test() error = %v", err)
|
||||
}
|
||||
if result.Outcome != OutcomeUnreachable {
|
||||
t.Fatalf("outcome = %q", result.Outcome)
|
||||
}
|
||||
if _, err := service.Save(context.Background(), EnvironmentTest, SaveInput{Endpoint: "http://weknora.example", APIKey: "k", KeyAction: KeyActionReplace}, "admin"); err == nil {
|
||||
t.Fatal("saving a public http endpoint must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func contains(value, needle string) bool {
|
||||
return len(needle) == 0 || (len(value) >= len(needle) && indexOf(value, needle) >= 0)
|
||||
}
|
||||
|
||||
func indexOf(value, needle string) int {
|
||||
for i := 0; i+len(needle) <= len(value); i++ {
|
||||
if value[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
Reference in New Issue
Block a user