Files
knowledge-governance/internal/httpapi/weknora_connections_test.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

175 lines
7.5 KiB
Go

package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/weknoraconn"
)
type weknoraConnectionsFake struct {
views []weknoraconn.View
testResult weknoraconn.TestResult
testErr error
savedResult weknoraconn.View
saveErr error
lastTest weknoraconn.TestInput
lastSave weknoraconn.SaveInput
lastActor string
}
func (fake *weknoraConnectionsFake) View(_ context.Context, environment string) ([]weknoraconn.View, error) {
if environment == "" {
return fake.views, nil
}
if !weknoraconn.ValidEnvironment(environment) {
return nil, weknoraconn.ErrNotFound
}
for _, view := range fake.views {
if view.Environment == environment {
return []weknoraconn.View{view}, nil
}
}
return []weknoraconn.View{{Environment: environment, Verification: weknoraconn.VerificationNotConfigured}}, nil
}
func (fake *weknoraConnectionsFake) Test(_ context.Context, environment string, input weknoraconn.TestInput) (weknoraconn.TestResult, error) {
if !weknoraconn.ValidEnvironment(environment) {
return weknoraconn.TestResult{}, weknoraconn.ErrNotFound
}
fake.lastTest = input
return fake.testResult, fake.testErr
}
func (fake *weknoraConnectionsFake) Save(_ context.Context, environment string, input weknoraconn.SaveInput, actor string) (weknoraconn.View, error) {
if !weknoraconn.ValidEnvironment(environment) {
return weknoraconn.View{}, weknoraconn.ErrNotFound
}
fake.lastSave, fake.lastActor = input, actor
return fake.savedResult, fake.saveErr
}
func weknoraConnectionsHandler(t *testing.T, fake *weknoraConnectionsFake, allowPrivate bool) http.Handler {
t.Helper()
handler, err := NewHandler(Config{
Store: &fakeJobStore{},
WeKnoraConnections: fake,
WeKnoraAllowPrivateHTTP: allowPrivate,
Now: func() time.Time { return time.Date(2026, time.November, 22, 7, 0, 0, 0, time.UTC) },
})
if err != nil {
t.Fatalf("NewHandler: %v", err)
}
return handler
}
func TestWeKnoraConnectionRoutesProjectStateWithoutSecrets(t *testing.T) {
fake := &weknoraConnectionsFake{views: []weknoraconn.View{
{Environment: "test", Endpoint: "http://127.0.0.1:8092", KeyConfigured: true, KeyTail: "9f2c", Verification: weknoraconn.OutcomeOK, LibraryCount: 3, Revision: 2, StorageReady: true},
{Environment: "production", Verification: weknoraconn.VerificationNotConfigured, StorageReady: true},
}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/weknora-connections", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d %s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("cache-control = %q", rec.Header().Get("Cache-Control"))
}
body := rec.Body.String()
if !strings.Contains(body, `"key_tail":"9f2c"`) || strings.Contains(body, "key_ciphertext") || strings.Contains(body, "api_key") {
t.Fatalf("body leaks or loses key projection: %s", body)
}
}
func TestWeKnoraConnectionTestKeepsFourAnswers(t *testing.T) {
for _, outcome := range []string{weknoraconn.OutcomeOK, weknoraconn.OutcomeUnreachable, weknoraconn.OutcomeKeyInvalid, weknoraconn.OutcomeKeyForbidden} {
fake := &weknoraConnectionsFake{testResult: weknoraconn.TestResult{
Environment: "production", Endpoint: "http://172.29.151.11:18093", Outcome: outcome, Message: outcome,
}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/production/test", strings.NewReader(`{"endpoint":"http://172.29.151.11:18093","key_action":"keep"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"outcome":"`+outcome+`"`) {
t.Fatalf("%s: status = %d body = %s", outcome, rec.Code, rec.Body.String())
}
}
}
func TestWeKnoraConnectionTestRejectsPlainKeyFromAPublicOrigin(t *testing.T) {
fake := &weknoraConnectionsFake{}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/test/test", strings.NewReader(`{"endpoint":"http://127.0.0.1:8092","api_key":"sk-live","key_action":"replace"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "weknora_secret_secure_transport_required") {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
if fake.lastTest.APIKey != "" {
t.Fatal("a rejected key must never reach the service")
}
}
func TestWeKnoraConnectionTestAcceptsSameOriginPrivateConsole(t *testing.T) {
fake := &weknoraConnectionsFake{testResult: weknoraconn.TestResult{Environment: "test", Outcome: weknoraconn.OutcomeOK}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/test/test", strings.NewReader(`{"endpoint":"http://127.0.0.1:8092","api_key":"sk-live","key_action":"replace"}`))
request.Host = "172.29.151.10:8088"
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Origin", "http://172.29.151.10:8088")
request.Header.Set("Sec-Fetch-Site", "same-origin")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
if fake.lastTest.APIKey != "sk-live" {
t.Fatalf("service saw key %q", fake.lastTest.APIKey)
}
}
func TestSaveWeKnoraConnectionRequiresIdempotencyKeyAndMapsNotTested(t *testing.T) {
fake := &weknoraConnectionsFake{saveErr: weknoraconn.ErrNotTested}
handler := weknoraConnectionsHandler(t, fake, false)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPut, "/api/v1/weknora-connections/production", strings.NewReader(`{"endpoint":"https://prod.example","key_action":"keep","base_revision":1}`)))
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "Idempotency-Key") {
t.Fatalf("missing idempotency key: %d %s", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/api/v1/weknora-connections/production", strings.NewReader(`{"endpoint":"https://prod.example","key_action":"keep","base_revision":1}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "op-1")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "weknora_connection_not_tested") {
t.Fatalf("not tested mapping: %d %s", rec.Code, rec.Body.String())
}
}
func TestWeKnoraConnectionUnknownEnvironmentIs404(t *testing.T) {
fake := &weknoraConnectionsFake{}
handler := weknoraConnectionsHandler(t, fake, false)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/weknora-connections?environment=staging", nil))
// The list route reads the path value, not the query: unknown environments
// only matter on the per-environment routes.
rec = httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/staging/test", strings.NewReader(`{"endpoint":"https://x.example","key_action":"keep"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
}
var _ = json.Marshal