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:
@@ -138,6 +138,12 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Recording an endpoint or an API key changes which instance the whole
|
||||
// platform talks to, and the key is a credential: read is viewer, every
|
||||
// write (including 测试连接, which spends the key) is admin.
|
||||
if strings.HasPrefix(path, "/api/v1/weknora-connections") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Choosing the production base a release writes into is a production
|
||||
// authority change, exactly like the annotation binding above.
|
||||
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
|
||||
|
||||
@@ -411,8 +411,16 @@ func TestClassifyRoleMatrix(t *testing.T) {
|
||||
http.MethodPost + " /api/v1/users": roleAdmin,
|
||||
http.MethodPost + " /api/v1/source-connections/c-1/settings/revisions": roleAdmin,
|
||||
// Choosing a release's production base is a production authority change.
|
||||
http.MethodPut + " /api/v1/production-kb-bindings": roleAdmin,
|
||||
http.MethodGet + " /api/v1/production-kb-bindings": roleViewer,
|
||||
http.MethodPut + " /api/v1/production-kb-bindings": roleAdmin,
|
||||
http.MethodGet + " /api/v1/production-kb-bindings": roleViewer,
|
||||
// An endpoint or an API key decides which instance the platform talks
|
||||
// to; 测试连接 also spends the credential, so every write is admin.
|
||||
http.MethodGet + " /api/v1/weknora-connections": roleViewer,
|
||||
http.MethodPost + " /api/v1/weknora-connections/test/test": roleAdmin,
|
||||
http.MethodPut + " /api/v1/weknora-connections/production": roleAdmin,
|
||||
// The test-side annotation binding is the same authority as production.
|
||||
http.MethodGet + " /api/v1/routing-bindings": roleViewer,
|
||||
http.MethodPut + " /api/v1/routing-bindings": roleAdmin,
|
||||
http.MethodPost + " /api/v1/review-candidates/tp-1/decision": roleEngineer,
|
||||
http.MethodPost + " /api/v1/release-batches/rb-1/seal": roleEngineer,
|
||||
http.MethodPost + " /api/v1/test-publications/start": roleEngineer,
|
||||
|
||||
@@ -16,6 +16,10 @@ import (
|
||||
type ProductionBindingStore interface {
|
||||
LoadProductionKBBindings(context.Context) (string, string, string, error)
|
||||
SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error
|
||||
// ProductionExecutionCounts reports frozen vs still re-targetable release
|
||||
// items. A binding change never rewrites a target that was already frozen
|
||||
// when an execution started; the count is how the page says so.
|
||||
ProductionExecutionCounts(ctx context.Context) (frozen int, retargetable int, err error)
|
||||
}
|
||||
|
||||
// ProductionKnowledgeBaseLister enumerates the knowledge bases of the production
|
||||
@@ -33,11 +37,26 @@ type productionBindingView struct {
|
||||
ProductionBaseURL string `json:"production_base_url"`
|
||||
ProductionConnected bool `json:"production_connected"`
|
||||
ProductionMessage string `json:"production_message"`
|
||||
// Frozen / Retargetable describe what a binding change can still affect.
|
||||
Frozen int `json:"frozen"`
|
||||
Retargetable int `json:"retargetable"`
|
||||
}
|
||||
|
||||
// WeKnoraConnectionResolver reads the admin-managed connection for one
|
||||
// environment. When it answers, that endpoint is the only truth.
|
||||
type WeKnoraConnectionResolver interface {
|
||||
Resolve(ctx context.Context, environment string) (endpoint string, apiKey string, ok bool)
|
||||
}
|
||||
|
||||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||||
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
|
||||
// connection card first, the operator-managed 「服务配置 · 生产地址」 second, the
|
||||
// deployment default last.
|
||||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||||
if config.WeKnoraConnectionResolver != nil {
|
||||
if endpoint, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, "production"); ok {
|
||||
return endpoint
|
||||
}
|
||||
}
|
||||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||||
return resolved
|
||||
@@ -55,7 +74,7 @@ func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.Kn
|
||||
}
|
||||
baseURL := config.productionTargetBaseURL(ctx)
|
||||
if baseURL == "" {
|
||||
return nil, "未配置生产地址(系统设置 → 服务配置)"
|
||||
return nil, "未配置生产地址(系统设置 → 生产知识库绑定 → 连接卡)"
|
||||
}
|
||||
bases, err := config.ProductionKnowledgeBases.ListProductionKnowledgeBases(ctx, baseURL)
|
||||
if err != nil {
|
||||
@@ -74,11 +93,16 @@ func (config Config) productionBindingPayload(ctx context.Context) (productionBi
|
||||
for _, base := range bases {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
frozen, retargetable := 0, 0
|
||||
if frozenItems, retargetableItems, countsErr := config.ProductionBindings.ProductionExecutionCounts(ctx); countsErr == nil {
|
||||
frozen, retargetable = frozenItems, retargetableItems
|
||||
}
|
||||
return productionBindingView{
|
||||
InternalKBID: storedInternal, ExternalKBID: storedExternal,
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
|
||||
ProductionConnected: message == "", ProductionMessage: message,
|
||||
Frozen: frozen, Retargetable: retargetable,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ type productionBindingStoreFake struct {
|
||||
internal, external, saver string
|
||||
savedInternal, savedExternal string
|
||||
saveCallCount int
|
||||
frozen, retargetable int
|
||||
}
|
||||
|
||||
func (fake *productionBindingStoreFake) LoadProductionKBBindings(context.Context) (string, string, string, error) {
|
||||
@@ -32,6 +33,10 @@ func (fake *productionBindingStoreFake) SaveProductionKBBindings(_ context.Conte
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fake *productionBindingStoreFake) ProductionExecutionCounts(context.Context) (int, int, error) {
|
||||
return fake.frozen, fake.retargetable, nil
|
||||
}
|
||||
|
||||
type productionListerFake struct {
|
||||
bases []weknora.KnowledgeBase
|
||||
err error
|
||||
|
||||
@@ -31,12 +31,15 @@ type routingBindingView struct {
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
InternalEnvFallback bool `json:"internal_env_fallback"`
|
||||
ExternalEnvFallback bool `json:"external_env_fallback"`
|
||||
InternalBoundByUI bool `json:"internal_bound_by_ui"`
|
||||
ExternalBoundByUI bool `json:"external_bound_by_ui"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
WeKnoraConnected bool `json:"weknora_connected"`
|
||||
// 取消绑定时必须说清「回退到了哪个库」,否则「留空」等于没说。
|
||||
InternalFallbackKBID string `json:"internal_fallback_kb_id"`
|
||||
ExternalFallbackKBID string `json:"external_fallback_kb_id"`
|
||||
InternalBoundByUI bool `json:"internal_bound_by_ui"`
|
||||
ExternalBoundByUI bool `json:"external_bound_by_ui"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
WeKnoraConnected bool `json:"weknora_connected"`
|
||||
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items
|
||||
// that had not been uploaded yet. A plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
@@ -98,9 +101,10 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
|
||||
return routingBindingView{
|
||||
InternalKBID: internal, ExternalKBID: external,
|
||||
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalFallbackKBID: config.InternalRoutingKnowledgeBaseID, ExternalFallbackKBID: config.ExternalRoutingKnowledgeBaseID,
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
|
||||
}, nil
|
||||
|
||||
@@ -177,14 +177,24 @@ type Config struct {
|
||||
// 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。
|
||||
LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error)
|
||||
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
BackupRuns *BackupRunTracker
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
ProductionWeKnoraBaseURL string
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
BackupRuns *BackupRunTracker
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
ProductionWeKnoraBaseURL string
|
||||
// WeKnoraConnections 是「连接(地址 + 写-only 密钥)」服务;未接线时三条路由
|
||||
// 返回 503,页面显示「未接线」而不是假装已配置。
|
||||
WeKnoraConnections WeKnoraConnections
|
||||
// WeKnoraAllowPrivateHTTP 允许同网段 http(生产 18093 反代);与客户端、监控
|
||||
// 探活共用同一个判定。WeKnoraTrustTLSProxy 允许在可信 TLS 反代后录入密钥。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
WeKnoraTrustTLSProxy bool
|
||||
// WeKnoraConnectionResolver 读页面保存的连接(地址 + 密钥);页面上显示的
|
||||
// 生产地址必须来自这里,否则会出现「连接卡写 18093、绑定页还在用旧地址」。
|
||||
WeKnoraConnectionResolver WeKnoraConnectionResolver
|
||||
ServiceTargetVerifier ServiceTargetVerifier
|
||||
Now func() time.Time
|
||||
RequireWeKnoraReady bool
|
||||
@@ -421,6 +431,15 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleSaveProductionBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/weknora-connections", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleWeKnoraConnections(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/weknora-connections/{environment}/test", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleWeKnoraConnectionTest(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/weknora-connections/{environment}", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleSaveWeKnoraConnection(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-catalog/route", func(w http.ResponseWriter, r *http.Request) {
|
||||
routeCatalogFiles(w, r, config)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/weknoraconn"
|
||||
)
|
||||
|
||||
// WeKnoraConnections is the connection service the routes below call. It is
|
||||
// deliberately narrow: the page may read state, run one real test, and save a
|
||||
// tested configuration — nothing here triggers a sync, a release or a reparse.
|
||||
type WeKnoraConnections interface {
|
||||
View(ctx context.Context, environment string) ([]weknoraconn.View, error)
|
||||
Test(ctx context.Context, environment string, input weknoraconn.TestInput) (weknoraconn.TestResult, error)
|
||||
Save(ctx context.Context, environment string, input weknoraconn.SaveInput, actor string) (weknoraconn.View, error)
|
||||
}
|
||||
|
||||
func weKnoraConnectionError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, weknoraconn.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "未知的 WeKnora 环境(只支持 test / production)"})
|
||||
case errors.Is(err, weknoraconn.ErrStaleRevision):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "连接配置已被他人修改,请重新读取后再保存"})
|
||||
case errors.Is(err, weknoraconn.ErrNotTested):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"code": "weknora_connection_not_tested",
|
||||
"error": "请先点「测试连接」并成功,才能保存这一侧的配置",
|
||||
})
|
||||
case errors.Is(err, weknoraconn.ErrStorageUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "密钥存储不可用:主密钥文件缺失或权限不是 0600,本次未保存任何密钥",
|
||||
})
|
||||
case errors.Is(err, weknoraconn.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "连接配置不合法:地址必填,且更换地址必须重新录入密钥"})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "WeKnora 连接配置处理失败"})
|
||||
}
|
||||
}
|
||||
|
||||
// weKnoraSecretTransportWithPrivateHTTP decides whether a plaintext key may be
|
||||
// accepted on this request. It reuses the QA-AI rule (TLS, loopback, trusted
|
||||
// TLS proxy + same origin) and adds the one case this deployment needs: the
|
||||
// operator console itself is reached over plain http on a private address, so a
|
||||
// same-origin fetch from that console is the only accepted non-TLS shape.
|
||||
func weKnoraSecretTransportWithPrivateHTTP(config Config, r *http.Request) bool {
|
||||
if qaAISecretTransport(r, config) {
|
||||
return true
|
||||
}
|
||||
if config.WeKnoraTrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" &&
|
||||
r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
if err == nil && origin.Scheme == "https" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if !config.WeKnoraAllowPrivateHTTP {
|
||||
return false
|
||||
}
|
||||
if r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return false
|
||||
}
|
||||
if !strings.EqualFold(parsed.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
return strings.EqualFold(host, "localhost")
|
||||
}
|
||||
|
||||
func (config Config) handleWeKnoraConnections(w http.ResponseWriter, r *http.Request) {
|
||||
if config.WeKnoraConnections == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
views, err := config.WeKnoraConnections.View(r.Context(), r.PathValue("environment"))
|
||||
if err != nil {
|
||||
weKnoraConnectionError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": views})
|
||||
}
|
||||
|
||||
func (config Config) handleWeKnoraConnectionTest(w http.ResponseWriter, r *http.Request) {
|
||||
if config.WeKnoraConnections == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
var input weknoraconn.TestInput
|
||||
if err := decodeStrictJSON(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.APIKey) != "" && !weKnoraSecretTransportWithPrivateHTTP(config, r) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"code": "weknora_secret_secure_transport_required",
|
||||
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
|
||||
})
|
||||
return
|
||||
}
|
||||
result, err := config.WeKnoraConnections.Test(r.Context(), r.PathValue("environment"), input)
|
||||
if err != nil {
|
||||
weKnoraConnectionError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
}
|
||||
|
||||
func (config Config) handleSaveWeKnoraConnection(w http.ResponseWriter, r *http.Request) {
|
||||
if config.WeKnoraConnections == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if _, ok := requireOperationID(w, r); !ok {
|
||||
return
|
||||
}
|
||||
var input weknoraconn.SaveInput
|
||||
if err := decodeStrictJSON(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
|
||||
return
|
||||
}
|
||||
if input.KeyAction != weknoraconn.KeyActionClear && strings.TrimSpace(input.APIKey) != "" &&
|
||||
!weKnoraSecretTransportWithPrivateHTTP(config, r) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"code": "weknora_secret_secure_transport_required",
|
||||
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
|
||||
})
|
||||
return
|
||||
}
|
||||
view, err := config.WeKnoraConnections.Save(r.Context(), r.PathValue("environment"), input, actorFor(r))
|
||||
if err != nil {
|
||||
weKnoraConnectionError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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
|
||||
Reference in New Issue
Block a user