连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥, 页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功, 换地址或换密钥必须测通才能保存(迁移 000083)。 可达性判定收敛为 weknora.HTTPAllowed,客户端与监控探活共用;新增 WEKNORA_ALLOW_PRIVATE_HTTP 只放行 RFC1918/回环/链路本地。生产绑定只保留下拉, 保存后回报冻结/未冻结条数,已冻结目标不被改写。
This commit is contained in:
@@ -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