package serviceverify import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "knowledge-governance/internal/governance" ) const testKey = "test-api-key-value" // fakeWeKnora answers the two reads the verifier makes, so the tests can pin // every verdict without a live WeKnora. type fakeWeKnora struct { bases []map[string]any detailErr int healthErr int detailHit int listHit int } func (fake *fakeWeKnora) serve() *httptest.Server { mux := http.NewServeMux() mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { if fake.healthErr != 0 { w.WriteHeader(fake.healthErr) return } w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{"status":"ok"}`)) }) mux.HandleFunc("/api/v1/knowledge-bases", func(w http.ResponseWriter, r *http.Request) { fake.listHit++ if r.Header.Get("X-API-Key") != testKey { w.WriteHeader(http.StatusUnauthorized) return } _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": fake.bases}) }) mux.HandleFunc("/api/v1/knowledge-bases/", func(w http.ResponseWriter, r *http.Request) { fake.detailHit++ if r.Header.Get("X-API-Key") != testKey { w.WriteHeader(http.StatusUnauthorized) return } if fake.detailErr != 0 { w.WriteHeader(fake.detailErr) _, _ = w.Write([]byte(`{"error":{"code":1003,"message":"knowledge base not found"}}`)) return } id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/") for _, base := range fake.bases { if base["id"] == id { _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": base}) return } } w.WriteHeader(http.StatusNotFound) _, _ = w.Write([]byte(`{"error":{"code":1003,"message":"knowledge base not found"}}`)) }) return httptest.NewServer(mux) } func writeKey(t *testing.T, value string) string { t.Helper() path := filepath.Join(t.TempDir(), "weknora_api_key") if err := os.WriteFile(path, []byte(value+"\n"), 0o600); err != nil { t.Fatalf("write key: %v", err) } return path } func newVerifier(t *testing.T, productionKeyFile string) *Verifier { t.Helper() return New(Config{ ProductionAPIKeyFile: productionKeyFile, TestAPIKeyFile: writeKey(t, testKey), Timeout: 3 * time.Second, Now: func() time.Time { return time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) }, }) } func base(id, name string, tenant uint64) map[string]any { return map[string]any{"id": id, "name": name, "tenant_id": tenant, "knowledge_count": 3} } func TestVerifyServiceTargetVerdicts(t *testing.T) { cases := []struct { name string bases []map[string]any detailErr int noKey bool target governance.ServiceTarget wantStatus string wantBlocked bool wantIn string }{ { name: "verifies an existing knowledge base and its tenant", bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}, target: governance.ServiceTarget{ProductionKnowledgeBaseID: "kb-prod-1", ProductionTenantID: "10000"}, wantStatus: governance.ServiceTargetVerified, wantIn: "生产知识库", }, { name: "refuses a knowledge base the endpoint does not have", bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}, detailErr: http.StatusNotFound, target: governance.ServiceTarget{ProductionKnowledgeBaseID: "kb-typo", ProductionTenantID: "10000"}, wantStatus: governance.ServiceTargetMissing, wantBlocked: true, wantIn: "kb-prod-1", }, { name: "refuses a tenant that does not own the knowledge base", bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}, target: governance.ServiceTarget{ProductionKnowledgeBaseID: "kb-prod-1", ProductionTenantID: "20000"}, wantStatus: governance.ServiceTargetTenantMismatch, wantBlocked: true, wantIn: "20000", }, { name: "warns instead of blocking when the key is rejected", bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}, detailErr: http.StatusUnauthorized, target: governance.ServiceTarget{ProductionKnowledgeBaseID: "kb-prod-1", ProductionTenantID: "10000"}, wantStatus: governance.ServiceTargetUnauthorized, wantIn: "未被阻断", }, { name: "warns instead of blocking when no production credential exists", bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}, noKey: true, target: governance.ServiceTarget{ProductionKnowledgeBaseID: "kb-prod-1", ProductionTenantID: "10000"}, wantStatus: governance.ServiceTargetCannotVerify, wantIn: "PRODUCTION_WEKNORA_API_KEY_FILE", }, { name: "verifies the tenant alone through the knowledge base list", bases: []map[string]any{base("kb-a", "甲库", 10000), base("kb-b", "乙库", 10000)}, target: governance.ServiceTarget{ProductionTenantID: "10000"}, wantStatus: governance.ServiceTargetVerified, }, { name: "refuses a tenant no knowledge base belongs to", bases: []map[string]any{base("kb-a", "甲库", 10000)}, target: governance.ServiceTarget{ProductionTenantID: "20000"}, wantStatus: governance.ServiceTargetMissing, wantBlocked: true, wantIn: "10000", }, } for _, testCase := range cases { t.Run(testCase.name, func(t *testing.T) { fake := &fakeWeKnora{bases: testCase.bases, detailErr: testCase.detailErr} server := fake.serve() defer server.Close() keyFile := "" if !testCase.noKey { keyFile = writeKey(t, testKey) } target := testCase.target if target.ProductionBaseURL == "" { target.ProductionBaseURL = server.URL } if target.TestBaseURL == "" { target.TestBaseURL = server.URL } verification := newVerifier(t, keyFile).VerifyServiceTarget(context.Background(), target) if verification.Status != testCase.wantStatus { t.Fatalf("status: want %q, got %q (%s)", testCase.wantStatus, verification.Status, verification.Message) } if verification.Blocked != testCase.wantBlocked { t.Fatalf("blocked: want %v, got %v (%s)", testCase.wantBlocked, verification.Blocked, verification.Message) } if testCase.wantIn != "" && !strings.Contains(verification.Message, testCase.wantIn) { t.Fatalf("message %q does not mention %q", verification.Message, testCase.wantIn) } if verification.CheckedAt.IsZero() { t.Fatal("expected a check timestamp") } if verification.TestEndpoint.Status != governance.ServiceEndpointReachable { t.Fatalf("test endpoint: want reachable, got %q (%s)", verification.TestEndpoint.Status, verification.TestEndpoint.Message) } }) } } // A save that stages no ID has nothing to verify: nothing blocks, and the // endpoints are reported as unconfigured instead of being invented. func TestVerifyServiceTargetWithoutIDs(t *testing.T) { verification := newVerifier(t, "").VerifyServiceTarget(context.Background(), governance.ServiceTarget{}) if verification.Status != governance.ServiceTargetNotConfigured || verification.Blocked { t.Fatalf("want not_configured without blocking, got %q blocked=%v", verification.Status, verification.Blocked) } if verification.TestEndpoint.Status != governance.ServiceEndpointNotConfigured || verification.ProductionEndpoint.Status != governance.ServiceEndpointNotConfigured { t.Fatalf("want unconfigured endpoints, got %q/%q", verification.TestEndpoint.Status, verification.ProductionEndpoint.Status) } } // Endpoint flakiness must never cost an operator their save: an outage is a // warning, not a refusal. func TestVerifyServiceTargetTreatsUnreachableEndpointAsWarning(t *testing.T) { server := (&fakeWeKnora{bases: []map[string]any{base("kb-prod-1", "生产知识库", 10000)}}).serve() unreachable := server.URL server.Close() target := governance.ServiceTarget{ProductionBaseURL: unreachable, ProductionKnowledgeBaseID: "kb-prod-1", ProductionTenantID: "10000"} verification := newVerifier(t, writeKey(t, testKey)).VerifyServiceTarget(context.Background(), target) if verification.Blocked { t.Fatalf("an unreachable endpoint must not block the save (%s)", verification.Message) } if verification.Status != governance.ServiceTargetUnreachable { t.Fatalf("want unreachable, got %q (%s)", verification.Status, verification.Message) } if verification.ProductionEndpoint.Status != governance.ServiceEndpointUnavailable { t.Fatalf("want an unavailable production endpoint, got %q", verification.ProductionEndpoint.Status) } } // Without a production credential the endpoint is still probed, so the console // can show real reachability next to the honest "未核验". func TestVerifyServiceTargetProbesEndpointWithoutCredential(t *testing.T) { server := (&fakeWeKnora{}).serve() defer server.Close() target := governance.ServiceTarget{ProductionBaseURL: server.URL, ProductionKnowledgeBaseID: "kb-prod-1"} verification := newVerifier(t, "").VerifyServiceTarget(context.Background(), target) if verification.Status != governance.ServiceTargetCannotVerify || verification.Blocked { t.Fatalf("want cannot_verify without blocking, got %q blocked=%v", verification.Status, verification.Blocked) } if verification.ProductionEndpoint.Status != governance.ServiceEndpointReachable { t.Fatalf("want a reachable production endpoint, got %q (%s)", verification.ProductionEndpoint.Status, verification.ProductionEndpoint.Message) } } // An endpoint that answers with 5xx is reported as unavailable, never as // configured-but-fine. func TestVerifyServiceTargetReportsUnhealthyEndpoint(t *testing.T) { server := (&fakeWeKnora{healthErr: http.StatusBadGateway}).serve() defer server.Close() target := governance.ServiceTarget{ProductionBaseURL: server.URL, ProductionKnowledgeBaseID: "kb-x"} verification := newVerifier(t, "").VerifyServiceTarget(context.Background(), target) if verification.ProductionEndpoint.Status != governance.ServiceEndpointUnavailable { t.Fatalf("want an unavailable production endpoint, got %q (%s)", verification.ProductionEndpoint.Status, verification.ProductionEndpoint.Message) } if verification.Blocked { t.Fatal("an unhealthy endpoint must not block the save") } }