feat(settings): 服务配置四项化并保存时真校验

- 生产/测试 WeKnora 地址、租户 ID、知识库 ID 由静态 env 收敛为版本化 UI 设置,保留修订号与操作人审计
- 新增 serviceverify:保存前真调目标端点探测,端点无效才拒绝;网络抖动或无凭据仅告警
- 迁移 000042(生产 WeKnora 端点)/000043(服务目标);补齐设置候选与校验契约用例
This commit is contained in:
姚章浩
2026-09-30 10:53:25 +08:00
parent e53b98f37d
commit 1db21fb899
28 changed files with 1887 additions and 65 deletions
+156 -14
View File
@@ -67,6 +67,7 @@ type Store interface {
GetReleaseExecution(ctx context.Context, executionID string) (governance.ReleaseExecutionDetail, error)
ListReleasePlan(ctx context.Context) (governance.ReleasePlan, error)
GetActiveUISettings(ctx context.Context) (governance.UISettings, error)
GetUISettingsRevision(ctx context.Context, revisionID string) (governance.UISettings, error)
CreateUISettingsCandidate(ctx context.Context, request governance.CreateUISettingsCandidateRequest) (governance.UISettings, error)
CreateUISettingsCandidateWithOperation(ctx context.Context, request governance.CreateUISettingsCandidateRequest, operationID string) (governance.UISettings, bool, error)
ActivateUISettings(ctx context.Context, revisionID string, now time.Time) (governance.UISettings, error)
@@ -104,6 +105,7 @@ type Config struct {
ExternalRoutingKnowledgeBaseID string
RoutingBindings RoutingBindingStore
KnowledgeBases KnowledgeBaseLister
ServiceTargetVerifier ServiceTargetVerifier
Now func() time.Time
RequireWeKnoraReady bool
ProductionReleaseRequestsEnabled bool
@@ -1183,11 +1185,60 @@ func reviewPublication(w http.ResponseWriter, r *http.Request, config Config) {
}
type createUISettingsCandidateRequest struct {
DocumentRefreshSeconds int `json:"document_refresh_seconds"`
ResourceRefreshSeconds int `json:"resource_refresh_seconds"`
StalledAfterSeconds int `json:"stalled_after_seconds"`
FinalizingAfterSeconds int `json:"finalizing_after_seconds"`
IngestionConcurrency int `json:"ingestion_concurrency"`
DocumentRefreshSeconds int `json:"document_refresh_seconds"`
ResourceRefreshSeconds int `json:"resource_refresh_seconds"`
StalledAfterSeconds int `json:"stalled_after_seconds"`
FinalizingAfterSeconds int `json:"finalizing_after_seconds"`
IngestionConcurrency int `json:"ingestion_concurrency"`
TestWeKnoraBaseURL string `json:"test_weknora_base_url"`
ProductionWeKnoraBaseURL string `json:"production_weknora_base_url"`
ProductionTenantID string `json:"production_tenant_id"`
ProductionKnowledgeBaseID string `json:"production_knowledge_base_id"`
}
// adminAuthorized reports whether the caller may change operator-level
// configuration (endpoints, production IDs). With auth enabled the RBAC middleware
// has already put a session identity in the context; without auth (development
// socket only) there is no identity to check, matching productionAuthorizer's
// fallback rather than inventing a second rule.
func adminAuthorized(r *http.Request) bool {
identity, ok := sessionFrom(r.Context())
if !ok {
return true
}
return identity.Role == roleAdmin
}
// operatorServiceFields are the operator-level entries of 「服务配置」: the test
// and production endpoints, the production tenant and the production knowledge
// base. Engineers may still tune refresh windows; only an admin may repoint the
// console's environments or rewrite its production IDs.
type operatorServiceFields struct {
TestWeKnoraBaseURL string
ProductionWeKnoraBaseURL string
ProductionTenantID string
ProductionKnowledgeBaseID string
}
func operatorServiceFieldsOf(settings governance.UISettings) operatorServiceFields {
return operatorServiceFields{
TestWeKnoraBaseURL: settings.TestWeKnoraBaseURL,
ProductionWeKnoraBaseURL: settings.ProductionWeKnoraBaseURL,
ProductionTenantID: settings.ProductionTenantID,
ProductionKnowledgeBaseID: settings.ProductionKnowledgeBaseID,
}
}
// operatorChangeNeedsAdmin keeps the operator-level service configuration
// admin-only on both ends of the versioned settings flow: authoring a candidate,
// and activating a revision whose values differ from the active ones (otherwise
// an engineer could activate an admin-authored change).
func operatorChangeNeedsAdmin(w http.ResponseWriter, r *http.Request, current, incoming operatorServiceFields) bool {
if current == incoming || adminAuthorized(r) {
return false
}
writeJSON(w, http.StatusForbidden, map[string]string{"error": "service configuration changes require an admin"})
return true
}
func getActiveUISettings(w http.ResponseWriter, r *http.Request, store Store) {
@@ -1199,6 +1250,44 @@ func getActiveUISettings(w http.ResponseWriter, r *http.Request, store Store) {
writeJSON(w, http.StatusOK, map[string]any{"data": settings})
}
// ServiceTargetVerifier performs a real read against the configured endpoints so
// that 「服务配置」cannot store an ID nobody ever checked. It decides no policy:
// it answers, and the caller refuses only a definitive negative answer.
type ServiceTargetVerifier interface {
VerifyServiceTarget(ctx context.Context, target governance.ServiceTarget) governance.ServiceTargetVerification
}
// verifyServiceTarget runs the configured verifier over the staged service
// fields. When the endpoint answered "not there" it writes the 400 itself and
// reports rejected=true, so the caller stops before touching the store.
func verifyServiceTarget(w http.ResponseWriter, r *http.Request, config Config, fields operatorServiceFields) (governance.ServiceTargetVerification, bool) {
if config.ServiceTargetVerifier == nil {
return governance.ServiceTargetVerification{}, false
}
verification := config.ServiceTargetVerifier.VerifyServiceTarget(r.Context(), governance.ServiceTarget{
TestBaseURL: fields.TestWeKnoraBaseURL,
ProductionBaseURL: fields.ProductionWeKnoraBaseURL,
ProductionTenantID: fields.ProductionTenantID,
ProductionKnowledgeBaseID: fields.ProductionKnowledgeBaseID,
})
if verification.Blocked {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": verification.Message, "verification": verification})
return verification, true
}
return verification, false
}
// uiSettingsWriteResponse keeps the write response shape stable across the paths
// that do and do not run a real verification (Status is empty when no verifier
// is configured).
func uiSettingsWriteResponse(settings governance.UISettings, operation string, verification governance.ServiceTargetVerification) map[string]any {
payload := map[string]any{"data": settings, "operation": operation}
if verification.Status != "" {
payload["verification"] = verification
}
return payload
}
func createUISettingsCandidate(w http.ResponseWriter, r *http.Request, config Config) {
if r.Header.Get("X-Governance-Action") != "ui-settings" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "UI settings write intent is required"})
@@ -1213,14 +1302,42 @@ func createUISettingsCandidate(w http.ResponseWriter, r *http.Request, config Co
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid UI settings candidate"})
return
}
// The endpoints and the production IDs are operator-level config: engineers
// may tune refresh windows, only an admin may repoint the console at a
// different environment or rewrite its production IDs.
incoming := operatorServiceFields{
TestWeKnoraBaseURL: strings.TrimSpace(request.TestWeKnoraBaseURL),
ProductionWeKnoraBaseURL: strings.TrimSpace(request.ProductionWeKnoraBaseURL),
ProductionTenantID: strings.TrimSpace(request.ProductionTenantID),
ProductionKnowledgeBaseID: strings.TrimSpace(request.ProductionKnowledgeBaseID),
}
current := operatorServiceFields{}
if active, err := config.Store.GetActiveUISettings(r.Context()); err == nil {
current = operatorServiceFieldsOf(active)
}
if operatorChangeNeedsAdmin(w, r, current, incoming) {
return
}
// The four service fields are only worth storing if the endpoint really has
// them, so ask it now: a definitive "not there" refuses the save, a flaky or
// unconfigured endpoint only warns (an outage must not stop an operator from
// fixing the address).
verification, rejected := verifyServiceTarget(w, r, config, incoming)
if rejected {
return
}
settings, replayed, err := config.Store.CreateUISettingsCandidateWithOperation(r.Context(), governance.CreateUISettingsCandidateRequest{
DocumentRefreshSeconds: request.DocumentRefreshSeconds,
ResourceRefreshSeconds: request.ResourceRefreshSeconds,
StalledAfterSeconds: request.StalledAfterSeconds,
FinalizingAfterSeconds: request.FinalizingAfterSeconds,
IngestionConcurrency: request.IngestionConcurrency,
UpdatedBy: actorFor(r),
Now: config.Now(),
DocumentRefreshSeconds: request.DocumentRefreshSeconds,
ResourceRefreshSeconds: request.ResourceRefreshSeconds,
StalledAfterSeconds: request.StalledAfterSeconds,
FinalizingAfterSeconds: request.FinalizingAfterSeconds,
IngestionConcurrency: request.IngestionConcurrency,
TestWeKnoraBaseURL: incoming.TestWeKnoraBaseURL,
ProductionWeKnoraBaseURL: incoming.ProductionWeKnoraBaseURL,
ProductionTenantID: incoming.ProductionTenantID,
ProductionKnowledgeBaseID: incoming.ProductionKnowledgeBaseID,
UpdatedBy: actorFor(r),
Now: config.Now(),
}, operationID)
if errors.Is(err, postgresstore.ErrOperationRequestConflict) {
writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"})
@@ -1238,7 +1355,7 @@ func createUISettingsCandidate(w http.ResponseWriter, r *http.Request, config Co
if replayed {
operation = "replayed"
}
writeJSON(w, http.StatusCreated, map[string]any{"data": settings, "operation": operation})
writeJSON(w, http.StatusCreated, uiSettingsWriteResponse(settings, operation, verification))
}
func activateUISettings(w http.ResponseWriter, r *http.Request, config Config) {
@@ -1255,6 +1372,31 @@ func activateUISettings(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid UI settings activation"})
return
}
// Activation applies the revision: if it would flip the endpoints or the
// production IDs, the caller must be an admin even when they did not author it.
revision, err := config.Store.GetUISettingsRevision(r.Context(), r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid UI settings activation"})
return
}
current := operatorServiceFields{}
if active, err := config.Store.GetActiveUISettings(r.Context()); err == nil {
current = operatorServiceFieldsOf(active)
}
staged := operatorServiceFieldsOf(revision)
if operatorChangeNeedsAdmin(w, r, current, staged) {
return
}
// Re-verify right before the values go live: a candidate can sit for days and
// its knowledge base can be deleted in between. An unchanged activation (a
// replay of an applied revision) skips the check so a retry stays idempotent.
verification := governance.ServiceTargetVerification{}
if staged != current {
var rejected bool
if verification, rejected = verifyServiceTarget(w, r, config, staged); rejected {
return
}
}
settings, replayed, err := config.Store.ActivateUISettingsWithOperation(r.Context(), r.PathValue("id"), config.Now(), operationID)
if errors.Is(err, postgresstore.ErrOperationRequestConflict) {
writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"})
@@ -1272,7 +1414,7 @@ func activateUISettings(w http.ResponseWriter, r *http.Request, config Config) {
if replayed {
operation = "replayed"
}
writeJSON(w, http.StatusOK, map[string]any{"data": settings, "operation": operation})
writeJSON(w, http.StatusOK, uiSettingsWriteResponse(settings, operation, verification))
}
type createReleaseBatchRequest struct {
+7
View File
@@ -1589,10 +1589,12 @@ type fakeJobStore struct {
activeUISettingsResult governance.UISettings
candidateUISettingsResult governance.UISettings
activatedUISettingsResult governance.UISettings
revisionUISettingsResult governance.UISettings
createUISettingsRequest governance.CreateUISettingsCandidateRequest
createUISettingsOperationID string
createUISettingsErr error
activateUISettingsID string
activationRevisionID string
activateUISettingsOperationID string
activateUISettingsErr error
publicationResult governance.TestPublicationPage
@@ -1831,6 +1833,11 @@ func (s *fakeJobStore) GetActiveUISettings(context.Context) (governance.UISettin
return s.activeUISettingsResult, nil
}
func (s *fakeJobStore) GetUISettingsRevision(_ context.Context, revisionID string) (governance.UISettings, error) {
s.activationRevisionID = revisionID
return s.revisionUISettingsResult, nil
}
func (s *fakeJobStore) CreateUISettingsCandidate(_ context.Context, request governance.CreateUISettingsCandidateRequest) (governance.UISettings, error) {
s.createUISettingsRequest = request
return s.candidateUISettingsResult, nil
@@ -0,0 +1,281 @@
package httpapi
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
const serviceCandidateBody = `{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"test_weknora_base_url":"https://weknora.test.example","production_weknora_base_url":"https://weknora.prod.example","production_tenant_id":"10000","production_knowledge_base_id":"kb-prod-1"}`
const refreshOnlyCandidateBody = `{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2}`
func withOperatorRole(request *http.Request, role string) *http.Request {
identity := sessionIdentity{UserID: "user-1", Username: "operator-1", DisplayName: "Operator", Role: role}
return request.WithContext(context.WithValue(request.Context(), sessionKey{}, identity))
}
func postUISettings(t *testing.T, handler http.Handler, path, body, key, role string) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(body))
request.Header.Set("X-Governance-Action", "ui-settings")
request.Header.Set("Idempotency-Key", key)
if role != "" {
request = withOperatorRole(request, role)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
return response
}
// The four service fields (test endpoint, production endpoint, production tenant,
// production knowledge base) are the settings a knowledge engineer may not touch:
// authoring them must fail closed, per field, and only an admin's candidate may
// carry them into the store. Refresh-only candidates keep working for engineers.
func TestServiceConfigurationCandidateRequiresAdmin(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{
ID: "uis-candidate", State: "validated", TestWeKnoraBaseURL: "https://weknora.test.example",
ProductionWeKnoraBaseURL: "https://weknora.prod.example", ProductionTenantID: "10000", ProductionKnowledgeBaseID: "kb-prod-1", CreatedAt: now,
}}
handler, err := NewHandler(Config{Store: store, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
engineer := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-engineer", roleEngineer)
if engineer.Code != http.StatusForbidden || !strings.Contains(engineer.Body.String(), "service configuration changes require an admin") {
t.Fatalf("engineer service candidate status=%d body=%s", engineer.Code, engineer.Body.String())
}
if store.createUISettingsRequest.TestWeKnoraBaseURL != "" || store.createUISettingsRequest.ProductionWeKnoraBaseURL != "" || store.createUISettingsRequest.ProductionTenantID != "" || store.createUISettingsRequest.ProductionKnowledgeBaseID != "" {
t.Fatalf("engineer candidate reached the store: %#v", store.createUISettingsRequest)
}
// Every single field is gated on its own — an engineer cannot slip one in.
for name, body := range map[string]string{
"test endpoint": `{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"test_weknora_base_url":"https://weknora.test.example"}`,
"tenant id": `{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"production_tenant_id":"10000"}`,
"knowledge base": `{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"production_knowledge_base_id":"kb-prod-1"}`,
} {
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", body, "op-service-engineer-"+name, roleEngineer)
if response.Code != http.StatusForbidden {
t.Fatalf("engineer %s-only candidate status=%d body=%s", name, response.Code, response.Body.String())
}
}
admin := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-admin", roleAdmin)
if admin.Code != http.StatusCreated || store.createUISettingsRequest.ProductionWeKnoraBaseURL != "https://weknora.prod.example" || store.createUISettingsRequest.TestWeKnoraBaseURL != "https://weknora.test.example" || store.createUISettingsRequest.ProductionTenantID != "10000" || store.createUISettingsRequest.ProductionKnowledgeBaseID != "kb-prod-1" {
t.Fatalf("admin service candidate status=%d request=%#v body=%s", admin.Code, store.createUISettingsRequest, admin.Body.String())
}
// A refresh-only candidate carries no service field, so nothing changed and the
// engineer keeps their existing write path.
refreshStore := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-refresh", State: "validated", CreatedAt: now}}
refreshHandler, err := NewHandler(Config{Store: refreshStore, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
refresh := postUISettings(t, refreshHandler, "/api/v1/ui-settings/candidates", refreshOnlyCandidateBody, "op-service-engineer-refresh", roleEngineer)
if refresh.Code != http.StatusCreated || refreshStore.createUISettingsRequest.ProductionTenantID != "" {
t.Fatalf("engineer refresh-only candidate status=%d request=%#v body=%s", refresh.Code, refreshStore.createUISettingsRequest, refresh.Body.String())
}
}
// Activation is the second half of the same privilege: a revision that would flip
// any of the four service fields may only be activated by an admin, while
// refresh-only revisions keep working for engineers.
func TestServiceConfigurationActivationRequiresAdmin(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
for name, revision := range map[string]governance.UISettings{
"test endpoint": {ID: "uis-test-endpoint", State: "validated", TestWeKnoraBaseURL: "https://weknora.test.example"},
"tenant id": {ID: "uis-tenant", State: "validated", ProductionTenantID: "10000"},
"knowledge base": {ID: "uis-kb", State: "validated", ProductionKnowledgeBaseID: "kb-prod-1"},
"production peer endpoint": {ID: "uis-endpoint", State: "validated", ProductionWeKnoraBaseURL: "https://weknora.prod.example"},
} {
flipping := &fakeJobStore{activeUISettingsResult: governance.UISettings{ID: "settings-default", State: "active"}, revisionUISettingsResult: revision}
handler, err := NewHandler(Config{Store: flipping, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
engineer := postUISettings(t, handler, "/api/v1/ui-settings/"+revision.ID+"/activate", `{}`, "op-service-activate-eng-"+name, roleEngineer)
if engineer.Code != http.StatusForbidden || flipping.activateUISettingsID != "" {
t.Fatalf("engineer %s activation status=%d id=%q body=%s", name, engineer.Code, flipping.activateUISettingsID, engineer.Body.String())
}
admin := postUISettings(t, handler, "/api/v1/ui-settings/"+revision.ID+"/activate", `{}`, "op-service-activate-admin-"+name, roleAdmin)
if admin.Code != http.StatusOK || flipping.activateUISettingsID != revision.ID {
t.Fatalf("admin %s activation status=%d id=%q body=%s", name, admin.Code, flipping.activateUISettingsID, admin.Body.String())
}
}
refreshOnly := &fakeJobStore{
activeUISettingsResult: governance.UISettings{ID: "settings-default", State: "active", TestWeKnoraBaseURL: "https://weknora.test.example", ProductionWeKnoraBaseURL: "https://weknora.prod.example", ProductionTenantID: "10000", ProductionKnowledgeBaseID: "kb-prod-1"},
revisionUISettingsResult: governance.UISettings{ID: "uis-refresh", State: "validated", TestWeKnoraBaseURL: "https://weknora.test.example", ProductionWeKnoraBaseURL: "https://weknora.prod.example", ProductionTenantID: "10000", ProductionKnowledgeBaseID: "kb-prod-1"},
}
refreshHandler, err := NewHandler(Config{Store: refreshOnly, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
unchanged := postUISettings(t, refreshHandler, "/api/v1/ui-settings/uis-refresh/activate", `{}`, "op-refresh-activate-eng", roleEngineer)
if unchanged.Code != http.StatusOK || refreshOnly.activateUISettingsID != "uis-refresh" {
t.Fatalf("engineer refresh-only activation status=%d id=%q body=%s", unchanged.Code, refreshOnly.activateUISettingsID, unchanged.Body.String())
}
}
// Without auth (development socket) there is no identity to rank, so the existing
// dev behaviour must not become a 403 regression.
func TestServiceConfigurationStaysOpenOnAuthDisabledDevSocket(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-candidate", State: "validated", ProductionWeKnoraBaseURL: "https://weknora.prod.example", CreatedAt: now}}
handler, err := NewHandler(Config{Store: store, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-dev", "")
if response.Code != http.StatusCreated || store.createUISettingsRequest.ProductionKnowledgeBaseID != "kb-prod-1" {
t.Fatalf("auth-disabled candidate status=%d request=%#v body=%s", response.Code, store.createUISettingsRequest, response.Body.String())
}
}
// stubServiceTargetVerifier records what the save path asked and answers with a
// canned verdict, so the handler's policy — refuse a definitive no, tolerate an
// outage — is tested without a live endpoint.
type stubServiceTargetVerifier struct {
targets []governance.ServiceTarget
verification governance.ServiceTargetVerification
}
func (stub *stubServiceTargetVerifier) VerifyServiceTarget(_ context.Context, target governance.ServiceTarget) governance.ServiceTargetVerification {
stub.targets = append(stub.targets, target)
return stub.verification
}
// 保存必须用「生产地址 + 知识库 ID」真查一次:查到了才写入,并把知识库名回显给界面。
func TestServiceConfigurationSaveVerifiesProductionTarget(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
verifier := &stubServiceTargetVerifier{verification: governance.ServiceTargetVerification{
Status: governance.ServiceTargetVerified, Message: "已核验:生产地址上存在知识库「生产知识库」,租户 10000 一致",
KnowledgeBaseName: "生产知识库", ObservedTenantID: "10000", CheckedAt: now,
}}
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-candidate", State: "validated", CreatedAt: now}}
handler, err := NewHandler(Config{Store: store, ServiceTargetVerifier: verifier, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-verified", roleAdmin)
if response.Code != http.StatusCreated || !strings.Contains(response.Body.String(), `"status":"verified"`) || !strings.Contains(response.Body.String(), "生产知识库") {
t.Fatalf("verified save status=%d body=%s", response.Code, response.Body.String())
}
if len(verifier.targets) != 1 {
t.Fatalf("verifier calls = %d", len(verifier.targets))
}
want := governance.ServiceTarget{
TestBaseURL: "https://weknora.test.example", ProductionBaseURL: "https://weknora.prod.example",
ProductionTenantID: "10000", ProductionKnowledgeBaseID: "kb-prod-1",
}
if verifier.targets[0] != want {
t.Fatalf("verified target = %#v want %#v", verifier.targets[0], want)
}
if store.createUISettingsOperationID == "" {
t.Fatal("a verified save must still reach the store")
}
}
// 端点明确回答"没有这个知识库"时不允许落库:ID 不能靠格式校验混过去。
func TestServiceConfigurationSaveRefusesKnowledgeBaseTheEndpointDoesNotHave(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
verifier := &stubServiceTargetVerifier{verification: governance.ServiceTargetVerification{
Status: governance.ServiceTargetMissing, Blocked: true, Message: "未通过:生产地址上找不到知识库 ID「kb-prod-1」",
}}
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-candidate", State: "validated", CreatedAt: now}}
handler, err := NewHandler(Config{Store: store, ServiceTargetVerifier: verifier, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-refused", roleAdmin)
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "找不到知识库") {
t.Fatalf("refused save status=%d body=%s", response.Code, response.Body.String())
}
if !strings.Contains(response.Body.String(), `"blocked":true`) {
t.Fatalf("refusal must carry the verification detail: %s", response.Body.String())
}
if store.createUISettingsOperationID != "" {
t.Fatal("a refused save must not reach the store")
}
}
// 端点抖动(超时/网络/未配置凭据)只警告不拦:运维不能因为端点故障就改不了地址。
func TestServiceConfigurationSaveKeepsFlakyEndpointNonBlocking(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
verifier := &stubServiceTargetVerifier{verification: governance.ServiceTargetVerification{
Status: governance.ServiceTargetUnreachable, Message: "未核验:生产端点暂时不可用(超时),保存未被阻断",
}}
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-candidate", State: "validated", CreatedAt: now}}
handler, err := NewHandler(Config{Store: store, ServiceTargetVerifier: verifier, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-flaky", roleAdmin)
if response.Code != http.StatusCreated || !strings.Contains(response.Body.String(), `"status":"unreachable"`) {
t.Fatalf("flaky save status=%d body=%s", response.Code, response.Body.String())
}
if store.createUISettingsOperationID == "" {
t.Fatal("an outage must not stop the save")
}
}
// 激活前再查一次:候选可以躺几天,知识库可能已经被删;字段与线上一致的回放不重复核验。
func TestServiceConfigurationActivationReverifiesStagedTarget(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
verifier := &stubServiceTargetVerifier{verification: governance.ServiceTargetVerification{
Status: governance.ServiceTargetMissing, Blocked: true, Message: "未通过:生产地址上找不到知识库 ID「kb-prod-1」",
}}
store := &fakeJobStore{
activeUISettingsResult: governance.UISettings{ID: "settings-default", State: "active"},
revisionUISettingsResult: governance.UISettings{ID: "uis-kb", State: "validated", ProductionKnowledgeBaseID: "kb-prod-1"},
activatedUISettingsResult: governance.UISettings{ID: "uis-kb", State: "active", ProductionKnowledgeBaseID: "kb-prod-1"},
}
handler, err := NewHandler(Config{Store: store, ServiceTargetVerifier: verifier, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/uis-kb/activate", `{}`, "op-activate-reverify", roleAdmin)
if response.Code != http.StatusBadRequest || store.activateUISettingsOperationID != "" {
t.Fatalf("re-verified activation status=%d id=%q body=%s", response.Code, store.activateUISettingsOperationID, response.Body.String())
}
if len(verifier.targets) != 1 || verifier.targets[0].ProductionKnowledgeBaseID != "kb-prod-1" {
t.Fatalf("activation verification targets = %#v", verifier.targets)
}
// A replay (identical fields already live) must stay idempotent: no endpoint
// call, so an outage cannot turn a retry into a failure.
replayVerifier := &stubServiceTargetVerifier{verification: governance.ServiceTargetVerification{Status: governance.ServiceTargetMissing, Blocked: true, Message: "boom"}}
replayStore := &fakeJobStore{
activeUISettingsResult: governance.UISettings{ID: "settings-default", State: "active", ProductionKnowledgeBaseID: "kb-prod-1"},
revisionUISettingsResult: governance.UISettings{ID: "uis-kb", State: "validated", ProductionKnowledgeBaseID: "kb-prod-1"},
activatedUISettingsResult: governance.UISettings{ID: "uis-kb", State: "active", ProductionKnowledgeBaseID: "kb-prod-1"},
}
replayHandler, err := NewHandler(Config{Store: replayStore, ServiceTargetVerifier: replayVerifier, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
replayed := postUISettings(t, replayHandler, "/api/v1/ui-settings/uis-kb/activate", `{}`, "op-activate-replay", roleAdmin)
if replayed.Code != http.StatusOK || len(replayVerifier.targets) != 0 {
t.Fatalf("unchanged activation must not re-verify: status=%d calls=%d body=%s", replayed.Code, len(replayVerifier.targets), replayed.Body.String())
}
}
// 没有配置核验器(开发 socket)时响应形状不变,不出现空的 verification 字段。
func TestServiceConfigurationSaveWithoutVerifierOmitsVerification(t *testing.T) {
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
store := &fakeJobStore{candidateUISettingsResult: governance.UISettings{ID: "uis-candidate", State: "validated", CreatedAt: now}}
handler, err := NewHandler(Config{Store: store, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := postUISettings(t, handler, "/api/v1/ui-settings/candidates", serviceCandidateBody, "op-service-no-verifier", roleAdmin)
if response.Code != http.StatusCreated || strings.Contains(response.Body.String(), "verification") {
t.Fatalf("unverified save status=%d body=%s", response.Code, response.Body.String())
}
}
@@ -37,7 +37,7 @@ func TestUISettingsWriteReadBackIntegration(t *testing.T) {
}
create := httptest.NewRecorder()
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400}`))
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"test_weknora_base_url":"https://weknora.test.example:8443/weknora","production_weknora_base_url":"https://weknora.prod.example:8443/weknora","production_tenant_id":"10000","production_knowledge_base_id":"kb-prod-1"}`))
createRequest.Header.Set("X-Governance-Action", "ui-settings")
createRequest.Header.Set("Idempotency-Key", "op-e2e-uis-create")
handler.ServeHTTP(create, createRequest)
@@ -50,6 +50,9 @@ func TestUISettingsWriteReadBackIntegration(t *testing.T) {
if err := json.NewDecoder(create.Body).Decode(&candidate); err != nil || candidate.Data.State != "validated" {
t.Fatalf("candidate=%#v error=%v", candidate, err)
}
if candidate.Data.ProductionWeKnoraBaseURL != "https://weknora.prod.example:8443/weknora" || candidate.Data.TestWeKnoraBaseURL != "https://weknora.test.example:8443/weknora" || candidate.Data.ProductionTenantID != "10000" || candidate.Data.ProductionKnowledgeBaseID != "kb-prod-1" {
t.Fatalf("service fields lost in the web write path: %#v", candidate.Data)
}
activate := httptest.NewRecorder()
activateRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/"+candidate.Data.ID+"/activate", bytes.NewBufferString(`{}`))
@@ -71,6 +74,13 @@ func TestUISettingsWriteReadBackIntegration(t *testing.T) {
if err := json.NewDecoder(get.Body).Decode(&active); err != nil || active.Data.ID != candidate.Data.ID || active.Data.State != "active" || active.Data.DocumentRefreshSeconds != 30 {
t.Fatalf("active=%#v error=%v", active, err)
}
if active.Data.ProductionWeKnoraBaseURL != "https://weknora.prod.example:8443/weknora" || active.Data.TestWeKnoraBaseURL != "https://weknora.test.example:8443/weknora" || active.Data.ProductionTenantID != "10000" || active.Data.ProductionKnowledgeBaseID != "kb-prod-1" {
t.Fatalf("active service fields not served back to the console: %#v", active.Data)
}
var persistedEndpoint, persistedTestEndpoint, persistedTenant, persistedKnowledgeBase string
if err := pool.QueryRow(ctx, `SELECT production_weknora_base_url,test_weknora_base_url,production_tenant_id,production_knowledge_base_id FROM ui_setting_revisions WHERE state='active'`).Scan(&persistedEndpoint, &persistedTestEndpoint, &persistedTenant, &persistedKnowledgeBase); err != nil || persistedEndpoint != "https://weknora.prod.example:8443/weknora" || persistedTestEndpoint != "https://weknora.test.example:8443/weknora" || persistedTenant != "10000" || persistedKnowledgeBase != "kb-prod-1" {
t.Fatalf("persisted service fields=%q/%q/%q/%q error=%v", persistedEndpoint, persistedTestEndpoint, persistedTenant, persistedKnowledgeBase, err)
}
var activeCount, retiredCount int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FILTER(WHERE state='active'),COUNT(*) FILTER(WHERE state='retired') FROM ui_setting_revisions`).Scan(&activeCount, &retiredCount); err != nil || activeCount != 1 || retiredCount != 1 {
t.Fatalf("active=%d retired=%d error=%v", activeCount, retiredCount, err)
@@ -0,0 +1,123 @@
package httpapi
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/serviceverify"
)
// 真端点 + 真库的回环:证明「保存服务配置」不是格式校验,而是拿生产地址真查了
// WeKnora(列库接口)——存在才落库,不存在必须被拒且一行都不写。
// 默认跳过,只有显式给环境变量时才跑(命中真实生产端点):
//
// TEST_DATABASE_URL=<一次性库>
// SERVICEVERIFY_LIVE_BASE_URL=https://weknora-test.dobot.cn
// SERVICEVERIFY_LIVE_API_KEY_FILE=/path/to/key
// SERVICEVERIFY_LIVE_KNOWLEDGE_BASE_ID=<真实知识库 ID>
// SERVICEVERIFY_LIVE_TENANT_ID=<该库真实租户 ID>
func TestUISettingsWriteReadBackWithLiveVerification(t *testing.T) {
databaseURL := os.Getenv("TEST_DATABASE_URL")
baseURL := os.Getenv("SERVICEVERIFY_LIVE_BASE_URL")
keyFile := os.Getenv("SERVICEVERIFY_LIVE_API_KEY_FILE")
knowledgeBaseID := os.Getenv("SERVICEVERIFY_LIVE_KNOWLEDGE_BASE_ID")
tenantID := os.Getenv("SERVICEVERIFY_LIVE_TENANT_ID")
if databaseURL == "" || baseURL == "" || keyFile == "" || knowledgeBaseID == "" || tenantID == "" {
t.Skip("live verification environment is not configured")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, databaseURL)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
var before int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM ui_setting_revisions`).Scan(&before); err != nil {
t.Fatal(err)
}
now := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
handler, err := NewHandler(Config{
Store: postgresstore.NewStore(pool),
Now: func() time.Time { return now },
ServiceTargetVerifier: serviceverify.New(serviceverify.Config{
ProductionAPIKeyFile: keyFile,
Timeout: 10 * time.Second,
}),
})
if err != nil {
t.Fatal(err)
}
// 1) 真实存在的知识库 + 真实租户:必须落库,并把知识库名回显给界面。
body := fmt.Sprintf(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"production_weknora_base_url":%q,"production_tenant_id":%q,"production_knowledge_base_id":%q}`, baseURL, tenantID, knowledgeBaseID)
create := httptest.NewRecorder()
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(body))
createRequest.Header.Set("X-Governance-Action", "ui-settings")
createRequest.Header.Set("Idempotency-Key", "op-live-verify-ok")
handler.ServeHTTP(create, createRequest)
if create.Code != http.StatusCreated {
t.Fatalf("verified save status=%d body=%s", create.Code, create.Body.String())
}
responseBody := create.Body.String()
if !strings.Contains(responseBody, `"status":"verified"`) || !strings.Contains(responseBody, `"blocked":false`) {
t.Fatalf("verified save must report a real verification: %s", responseBody)
}
var afterCreate int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM ui_setting_revisions`).Scan(&afterCreate); err != nil {
t.Fatal(err)
}
if afterCreate != before+1 {
t.Fatalf("verified save revisions=%d want %d", afterCreate, before+1)
}
// 2) 真实端点回答"没有这个知识库":必须 400,且一行都不写。
missingKB := "kb-live-missing-9f2c1"
missingBody := fmt.Sprintf(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"production_weknora_base_url":%q,"production_tenant_id":%q,"production_knowledge_base_id":%q}`, baseURL, tenantID, missingKB)
refused := httptest.NewRecorder()
refusedRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(missingBody))
refusedRequest.Header.Set("X-Governance-Action", "ui-settings")
refusedRequest.Header.Set("Idempotency-Key", "op-live-verify-missing")
handler.ServeHTTP(refused, refusedRequest)
if refused.Code != http.StatusBadRequest || !strings.Contains(refused.Body.String(), `"status":"missing"`) {
t.Fatalf("refused save status=%d body=%s", refused.Code, refused.Body.String())
}
var afterRefusal int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM ui_setting_revisions`).Scan(&afterRefusal); err != nil {
t.Fatal(err)
}
if afterRefusal != afterCreate {
t.Fatalf("a refused save must not write: revisions=%d want %d", afterRefusal, afterCreate)
}
// 3) 知识库真存在但租户不符:也必须拒("ID 存在"不等于"ID 是你的")。
mismatchBody := fmt.Sprintf(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"ingestion_concurrency":2,"production_weknora_base_url":%q,"production_tenant_id":%q,"production_knowledge_base_id":%q}`, baseURL, "20000", knowledgeBaseID)
mismatch := httptest.NewRecorder()
mismatchRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(mismatchBody))
mismatchRequest.Header.Set("X-Governance-Action", "ui-settings")
mismatchRequest.Header.Set("Idempotency-Key", "op-live-verify-mismatch")
handler.ServeHTTP(mismatch, mismatchRequest)
if mismatch.Code != http.StatusBadRequest || !strings.Contains(mismatch.Body.String(), `"status":"tenant_mismatch"`) {
t.Fatalf("tenant mismatch save status=%d body=%s", mismatch.Code, mismatch.Body.String())
}
var afterMismatch int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM ui_setting_revisions`).Scan(&afterMismatch); err != nil {
t.Fatal(err)
}
if afterMismatch != afterCreate {
t.Fatalf("a tenant mismatch must not write: revisions=%d want %d", afterMismatch, afterCreate)
}
t.Logf("live verification ok: kb=%s tenant=%s", knowledgeBaseID, tenantID)
}