feat(settings): 服务配置四项化并保存时真校验
- 生产/测试 WeKnora 地址、租户 ID、知识库 ID 由静态 env 收敛为版本化 UI 设置,保留修订号与操作人审计 - 新增 serviceverify:保存前真调目标端点探测,端点无效才拒绝;网络抖动或无凭据仅告警 - 迁移 000042(生产 WeKnora 端点)/000043(服务目标);补齐设置候选与校验契约用例
This commit is contained in:
+37
-7
@@ -18,6 +18,7 @@ import (
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -75,17 +76,46 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
// Production WeKnora is probed for liveness only: the console must show the
|
||||
// real state of that endpoint, while credentials and the publish target stay
|
||||
// in the release runtime config (RELEASE_CONFIG_FILE).
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 服务配置」,管理员保存的值是
|
||||
// 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在
|
||||
// release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。
|
||||
actionStore := postgresstore.NewStore(pool)
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.ProductionWeKnoraBaseURL
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
Store: postgresstore.NewStore(pool),
|
||||
Monitor: monitorProvider,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
KnowledgeBases: knowledgeBaseLister,
|
||||
Store: postgresstore.NewStore(pool),
|
||||
Monitor: monitorProvider,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
KnowledgeBases: knowledgeBaseLister,
|
||||
ServiceTargetVerifier: serviceverify.New(serviceverify.Config{
|
||||
TestAPIKeyFile: config.TestWeKnoraAPIKeyFile,
|
||||
ProductionAPIKeyFile: config.ProductionWeKnoraAPIKeyFile,
|
||||
TestBaseURLFallback: config.TestWeKnoraBaseURL,
|
||||
ProductionBaseURLFallback: config.ProductionWeKnoraBaseURL,
|
||||
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
}),
|
||||
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
|
||||
ProductionBackupRestoreVerified: config.ProductionBackupRestoreVerified,
|
||||
ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef,
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -23,6 +25,12 @@ type Config struct {
|
||||
ProductionBackupRestoreVerified bool
|
||||
ProductionReleaseAuthorizerRef string
|
||||
ProductionReleaseAuthTokenFile string
|
||||
// Production WeKnora endpoint: the release target itself stays declared in
|
||||
// the release runtime config (RELEASE_CONFIG_FILE); these settings only let
|
||||
// the API probe that endpoint so the console can show its real state.
|
||||
ProductionWeKnoraBaseURL string
|
||||
ProductionWeKnoraAPIKeyFile string
|
||||
ProductionWeKnoraAllowDockerHTTP bool
|
||||
PPScanEnabled bool
|
||||
PPScanAllowedRoot string
|
||||
PPScanLedgerPath string
|
||||
@@ -59,6 +67,8 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
ReleaseConfigFile: strings.TrimSpace(getenv("RELEASE_CONFIG_FILE")),
|
||||
ProductionReleaseAuthorizerRef: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTHORIZER_REF")),
|
||||
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
|
||||
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
|
||||
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
|
||||
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
|
||||
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
|
||||
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
|
||||
@@ -119,6 +129,25 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, fmt.Errorf("PRODUCTION_BACKUP_RESTORE_VERIFIED: %w", err)
|
||||
}
|
||||
}
|
||||
if raw := getenv("PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP"); raw != "" {
|
||||
config.ProductionWeKnoraAllowDockerHTTP, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP: %w", err)
|
||||
}
|
||||
}
|
||||
if config.ProductionWeKnoraBaseURL != "" {
|
||||
if err := validateHTTPBaseURL(config.ProductionWeKnoraBaseURL); err != nil {
|
||||
return Config{}, fmt.Errorf("PRODUCTION_WEKNORA_BASE_URL: %w", err)
|
||||
}
|
||||
}
|
||||
if config.ProductionWeKnoraAPIKeyFile != "" {
|
||||
if config.ProductionWeKnoraBaseURL == "" {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE requires PRODUCTION_WEKNORA_BASE_URL")
|
||||
}
|
||||
if !filepath.IsAbs(config.ProductionWeKnoraAPIKeyFile) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
@@ -215,6 +244,17 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// validateHTTPBaseURL accepts only a bare http(s) origin: no credentials, query
|
||||
// or fragment, so a probe address can never smuggle in secrets. The rule itself
|
||||
// lives with the domain type because the web-configured endpoint must obey the
|
||||
// exact same shape.
|
||||
func validateHTTPBaseURL(value string) error {
|
||||
if !governance.ValidHTTPOrigin(value) {
|
||||
return errors.New("must be an http(s) origin without credentials, query or fragment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func valueOrDefault(value, fallback string) string {
|
||||
if value == "" {
|
||||
return fallback
|
||||
|
||||
@@ -241,3 +241,52 @@ func TestLoadRequiresBothCatalogRoutingKnowledgeBases(t *testing.T) {
|
||||
t.Fatal("one-sided routing target must fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProductionWeKnoraEndpointIsConfigurableAndFailsClosed freezes the
|
||||
// production WeKnora configuration contract: the address is operator-supplied
|
||||
// (never hardcoded), validation rejects anything that could smuggle secrets, and
|
||||
// an unset address is an explicit "not configured" state instead of a guess.
|
||||
func TestProductionWeKnoraEndpointIsConfigurableAndFailsClosed(t *testing.T) {
|
||||
load := func(extra map[string]string) (Config, error) {
|
||||
values := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
for key, value := range extra {
|
||||
values[key] = value
|
||||
}
|
||||
return Load(func(key string) string { return values[key] })
|
||||
}
|
||||
config, err := load(map[string]string{
|
||||
"PRODUCTION_WEKNORA_BASE_URL": "https://weknora.prod.example/",
|
||||
"PRODUCTION_WEKNORA_API_KEY_FILE": "/run/secrets/production_weknora_api_key",
|
||||
"PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP": "true",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid production endpoint rejected: %v", err)
|
||||
}
|
||||
if config.ProductionWeKnoraBaseURL != "https://weknora.prod.example/" || !config.ProductionWeKnoraAllowDockerHTTP {
|
||||
t.Fatalf("production endpoint = %#v", config)
|
||||
}
|
||||
if config.ProductionWeKnoraAPIKeyFile != "/run/secrets/production_weknora_api_key" {
|
||||
t.Fatalf("production key file = %q", config.ProductionWeKnoraAPIKeyFile)
|
||||
}
|
||||
for _, invalid := range []map[string]string{
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "ftp://weknora.example"},
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "weknora.example"},
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "https://user:pass@weknora.example"},
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "https://weknora.example/?token=secret"},
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "https://weknora.example/#frag"},
|
||||
{"PRODUCTION_WEKNORA_API_KEY_FILE": "/run/secrets/production_weknora_api_key"},
|
||||
{"PRODUCTION_WEKNORA_BASE_URL": "https://weknora.example", "PRODUCTION_WEKNORA_API_KEY_FILE": "relative/key"},
|
||||
{"PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP": "yes"},
|
||||
} {
|
||||
if _, err := load(invalid); err == nil {
|
||||
t.Fatalf("invalid production endpoint accepted: %#v", invalid)
|
||||
}
|
||||
}
|
||||
unset, err := load(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if unset.ProductionWeKnoraBaseURL != "" || unset.ProductionWeKnoraAPIKeyFile != "" || unset.ProductionWeKnoraAllowDockerHTTP {
|
||||
t.Fatalf("production endpoint must default to unconfigured: %#v", unset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ValidHTTPOrigin reports whether value is a bare http(s) origin: scheme, host
|
||||
// and an optional path, with no credentials, query string or fragment. It is
|
||||
// the single rule for every operator-supplied endpoint — the env-configured
|
||||
// probe address and the web-configured one — so an endpoint can never smuggle
|
||||
// a secret (https://user:pass@host, ?token=...) or an injection payload.
|
||||
func ValidHTTPOrigin(value string) bool {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed == "" || trimmed != value || len(trimmed) > 300 {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(trimmed)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||
return false
|
||||
}
|
||||
return parsed.User == nil && parsed.RawQuery == "" && parsed.Fragment == ""
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package governance
|
||||
|
||||
import "time"
|
||||
|
||||
// ServiceTarget is the operator-level 「服务配置」 target: the console endpoints
|
||||
// plus the production knowledge base and its tenant. It exists so the save path
|
||||
// can ask the real endpoint whether the typed values exist, instead of storing
|
||||
// two numbers nobody ever consumed.
|
||||
type ServiceTarget struct {
|
||||
TestBaseURL string
|
||||
ProductionBaseURL string
|
||||
ProductionTenantID string
|
||||
ProductionKnowledgeBaseID string
|
||||
}
|
||||
|
||||
// Statuses of a whole service-target verification.
|
||||
const (
|
||||
// ServiceTargetVerified: the endpoint answered and every configured value is
|
||||
// really there.
|
||||
ServiceTargetVerified = "verified"
|
||||
// ServiceTargetMissing: the endpoint answered and the knowledge base (or a
|
||||
// knowledge base of that tenant) is NOT there. Blocking.
|
||||
ServiceTargetMissing = "missing"
|
||||
// ServiceTargetTenantMismatch: the knowledge base exists but belongs to a
|
||||
// different tenant than the configured production ID. Blocking.
|
||||
ServiceTargetTenantMismatch = "tenant_mismatch"
|
||||
// ServiceTargetUnauthorized: the endpoint answered 401/403 — a credential
|
||||
// problem, not proof about the values. Advisory.
|
||||
ServiceTargetUnauthorized = "unauthorized"
|
||||
// ServiceTargetUnreachable: network, timeout or server error. Advisory.
|
||||
ServiceTargetUnreachable = "unreachable"
|
||||
// ServiceTargetCannotVerify: nothing to ask with (no endpoint, no key file,
|
||||
// unusable address). Advisory.
|
||||
ServiceTargetCannotVerify = "cannot_verify"
|
||||
// ServiceTargetNotConfigured: both IDs are empty, so there is nothing to
|
||||
// verify and nothing was.
|
||||
ServiceTargetNotConfigured = "not_configured"
|
||||
)
|
||||
|
||||
// Statuses of a single endpoint probe.
|
||||
const (
|
||||
ServiceEndpointReachable = "reachable"
|
||||
ServiceEndpointUnauthorized = "unauthorized"
|
||||
ServiceEndpointUnavailable = "unavailable"
|
||||
ServiceEndpointNotConfigured = "not_configured"
|
||||
)
|
||||
|
||||
// ServiceEndpointStatus is one endpoint's live reachability, as measured during
|
||||
// the save. Both endpoints are probed on every save so the console never claims
|
||||
// 「已配置」without a read behind it.
|
||||
type ServiceEndpointStatus struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ServiceTargetVerification is the honest outcome of the real read behind a
|
||||
// 「服务配置」save. Blocked is true only for a definitive negative answer — the
|
||||
// endpoint answered and the knowledge base / tenant is provably absent. A flaky,
|
||||
// unauthorized or unconfigured endpoint only warns: an outage must never stop an
|
||||
// operator from fixing the configuration.
|
||||
type ServiceTargetVerification struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Blocked bool `json:"blocked"`
|
||||
KnowledgeBaseName string `json:"knowledge_base_name,omitempty"`
|
||||
ObservedTenantID string `json:"observed_tenant_id,omitempty"`
|
||||
TestEndpoint ServiceEndpointStatus `json:"test_endpoint"`
|
||||
ProductionEndpoint ServiceEndpointStatus `json:"production_endpoint"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
@@ -1,33 +1,42 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UISettings struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
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"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ActivatedAt *time.Time `json:"activated_at"`
|
||||
RetiredAt *time.Time `json:"retired_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
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"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ActivatedAt *time.Time `json:"activated_at"`
|
||||
RetiredAt *time.Time `json:"retired_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
}
|
||||
|
||||
type CreateUISettingsCandidateRequest struct {
|
||||
DocumentRefreshSeconds int
|
||||
ResourceRefreshSeconds int
|
||||
StalledAfterSeconds int
|
||||
FinalizingAfterSeconds int
|
||||
IngestionConcurrency int
|
||||
UpdatedBy string
|
||||
Now time.Time
|
||||
DocumentRefreshSeconds int
|
||||
ResourceRefreshSeconds int
|
||||
StalledAfterSeconds int
|
||||
FinalizingAfterSeconds int
|
||||
IngestionConcurrency int
|
||||
TestWeKnoraBaseURL string
|
||||
ProductionWeKnoraBaseURL string
|
||||
ProductionTenantID string
|
||||
ProductionKnowledgeBaseID string
|
||||
UpdatedBy string
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
func (request CreateUISettingsCandidateRequest) Valid() bool {
|
||||
@@ -36,9 +45,68 @@ func (request CreateUISettingsCandidateRequest) Valid() bool {
|
||||
oneOfInt(request.StalledAfterSeconds, 1800, 3600) &&
|
||||
oneOfInt(request.FinalizingAfterSeconds, 7200, 14400) &&
|
||||
request.IngestionConcurrency >= 1 && request.IngestionConcurrency <= 16 &&
|
||||
ValidTestWeKnoraBaseURL(request.TestWeKnoraBaseURL) &&
|
||||
ValidProductionWeKnoraBaseURL(request.ProductionWeKnoraBaseURL) &&
|
||||
ValidProductionTenantID(request.ProductionTenantID) &&
|
||||
ValidKnowledgeBaseID(request.ProductionKnowledgeBaseID) &&
|
||||
validSettingsActor(request.UpdatedBy) && !request.Now.IsZero()
|
||||
}
|
||||
|
||||
// ValidProductionWeKnoraBaseURL accepts the operator-configured production
|
||||
// WeKnora endpoint for the console: empty means "not configured" (clearing the
|
||||
// field is legal and honest), anything else must be a bare http(s) origin.
|
||||
// Credentials stay file references — never part of this value.
|
||||
func ValidProductionWeKnoraBaseURL(value string) bool {
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
return ValidHTTPOrigin(value)
|
||||
}
|
||||
|
||||
// ValidTestWeKnoraBaseURL is the same rule as the production endpoint: the
|
||||
// test environment is also operator-provided, empty means "not configured".
|
||||
func ValidTestWeKnoraBaseURL(value string) bool {
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
return ValidHTTPOrigin(value)
|
||||
}
|
||||
|
||||
// ValidProductionTenantID accepts the WeKnora tenant of the production
|
||||
// environment (the release contract's tenant_id). It is a decimal identifier,
|
||||
// so anything with a sign, separator or letter is a typing mistake. Empty means
|
||||
// "not configured".
|
||||
func ValidProductionTenantID(value string) bool {
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
if len(value) > 20 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if char < '0' || char > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
parsed, err := strconv.ParseUint(value, 10, 64)
|
||||
return err == nil && parsed > 0
|
||||
}
|
||||
|
||||
// ValidKnowledgeBaseID accepts the target knowledge base identifier of the
|
||||
// production environment. It is an opaque id (letters, digits, '.', '_', '-',
|
||||
// ':'), never a path or URL fragment: whitespace, '/' , '?', '#' and '\\' are
|
||||
// rejected so a pasted URL cannot masquerade as an id. Empty means "not
|
||||
// configured".
|
||||
func ValidKnowledgeBaseID(value string) bool {
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
if len(value) > 128 {
|
||||
return false
|
||||
}
|
||||
return !strings.ContainsAny(value, "\x00\r\n /?#\\")
|
||||
}
|
||||
|
||||
func oneOfInt(value int, allowed ...int) bool {
|
||||
for _, candidate := range allowed {
|
||||
if value == candidate {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestValidProductionWeKnoraBaseURL(t *testing.T) {
|
||||
base := CreateUISettingsCandidateRequest{
|
||||
DocumentRefreshSeconds: 15, ResourceRefreshSeconds: 30,
|
||||
StalledAfterSeconds: 1800, FinalizingAfterSeconds: 7200,
|
||||
IngestionConcurrency: 2, UpdatedBy: "admin-1",
|
||||
Now: time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC),
|
||||
}
|
||||
if !base.Valid() {
|
||||
t.Fatal("an empty endpoint means \"not configured\" and must stay legal")
|
||||
}
|
||||
configured := base
|
||||
configured.ProductionWeKnoraBaseURL = "https://weknora.prod.example:8443/weknora"
|
||||
if !configured.Valid() {
|
||||
t.Fatalf("bare http(s) origin rejected: %q", configured.ProductionWeKnoraBaseURL)
|
||||
}
|
||||
for _, unsafe := range []string{
|
||||
"weknora.prod.example",
|
||||
"ftp://weknora.prod.example",
|
||||
"https://user:pass@weknora.prod.example",
|
||||
"https://weknora.prod.example/?token=abc",
|
||||
"https://weknora.prod.example/#frag",
|
||||
" https://weknora.prod.example",
|
||||
"https://weknora.prod.example\r\nX-Injected: 1",
|
||||
} {
|
||||
candidate := base
|
||||
candidate.ProductionWeKnoraBaseURL = unsafe
|
||||
if candidate.Valid() {
|
||||
t.Fatalf("unsafe endpoint accepted: %q", unsafe)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The other three service fields carry the same "empty means not configured"
|
||||
// rule and their own shape: an origin for the test endpoint, decimal digits for
|
||||
// the tenant, and a token without whitespace or URL pieces for the knowledge base.
|
||||
func TestValidServiceTargetFields(t *testing.T) {
|
||||
base := CreateUISettingsCandidateRequest{
|
||||
DocumentRefreshSeconds: 15, ResourceRefreshSeconds: 30,
|
||||
StalledAfterSeconds: 1800, FinalizingAfterSeconds: 7200,
|
||||
IngestionConcurrency: 2, UpdatedBy: "admin-1",
|
||||
Now: time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC),
|
||||
}
|
||||
configured := base
|
||||
configured.TestWeKnoraBaseURL = "https://weknora.test.example:8443/weknora"
|
||||
configured.ProductionTenantID = "10000"
|
||||
configured.ProductionKnowledgeBaseID = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
|
||||
if !configured.Valid() {
|
||||
t.Fatalf("valid service targets rejected: %#v", configured)
|
||||
}
|
||||
for _, unsafe := range []string{"weknora.test.example", "https://user:pass@weknora.test.example", "https://weknora.test.example?token=abc", "ftp://weknora.test.example"} {
|
||||
candidate := base
|
||||
candidate.TestWeKnoraBaseURL = unsafe
|
||||
if candidate.Valid() {
|
||||
t.Fatalf("unsafe test endpoint accepted: %q", unsafe)
|
||||
}
|
||||
}
|
||||
for _, unsafe := range []string{"abc", "10 000", "-1", "0", "10000.5", "10000000000000000000000", "10000\n20000"} {
|
||||
candidate := base
|
||||
candidate.ProductionTenantID = unsafe
|
||||
if candidate.Valid() {
|
||||
t.Fatalf("unsafe production tenant id accepted: %q", unsafe)
|
||||
}
|
||||
}
|
||||
for _, unsafe := range []string{"kb/abc", "kb abc", "kb-abc?x", "kb#frag", "https://weknora.prod.example/kb", `kb\abc`} {
|
||||
candidate := base
|
||||
candidate.ProductionKnowledgeBaseID = unsafe
|
||||
if candidate.Valid() {
|
||||
t.Fatalf("unsafe knowledge base id accepted: %q", unsafe)
|
||||
}
|
||||
}
|
||||
}
|
||||
+156
-14
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -172,16 +172,28 @@ func (provider *RealProvider) httpProbe(ctx context.Context, key, name, baseURL
|
||||
// weKnoraProbe checks the WeKnora API: liveness via /health, readiness via an
|
||||
// optional real read against a routing knowledge base.
|
||||
func (provider *RealProvider) weKnoraProbe(ctx context.Context, now time.Time) governance.ServiceHealth {
|
||||
if provider.weknoraBaseURL == "" {
|
||||
baseURL := provider.resolveTestWeKnoraBaseURL(ctx)
|
||||
if baseURL == "" {
|
||||
return provider.track(classify("weknora", "WeKnora API", false, true, ProbeOutcome{ObservedAt: now}))
|
||||
}
|
||||
outcome := provider.httpProbeOutcome(ctx, provider.weknoraBaseURL, now)
|
||||
outcome := provider.httpProbeOutcome(ctx, baseURL, now)
|
||||
if outcome.Reachability == nil && provider.weknoraReadiness != nil {
|
||||
outcome.WorkReadiness = provider.weknoraReadiness(ctx)
|
||||
}
|
||||
return provider.track(classify("weknora", "WeKnora API", true, true, outcome))
|
||||
}
|
||||
|
||||
// productionWeKnoraProbe reports the real state of the production WeKnora
|
||||
// endpoint (liveness via /health). It is advisory: publishing stays gated by the
|
||||
// production switch and keeps its target in the release runtime config.
|
||||
func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now time.Time) governance.ServiceHealth {
|
||||
baseURL := provider.resolveProductionWeKnoraBaseURL(ctx)
|
||||
if baseURL == "" {
|
||||
return provider.track(classify("weknora-production", "生产 WeKnora", false, true, ProbeOutcome{ObservedAt: now}))
|
||||
}
|
||||
return provider.track(classify("weknora-production", "生产 WeKnora", true, true, provider.httpProbeOutcome(ctx, baseURL, now)))
|
||||
}
|
||||
|
||||
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
|
||||
parsed, err := url.Parse(baseURL)
|
||||
outcome := ProbeOutcome{ObservedAt: now}
|
||||
@@ -284,6 +296,7 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
|
||||
health = append(health, provider.track(classify("queue", "任务队列", true, true, queueOutcome)))
|
||||
health = append(health, provider.workerProbe(ctx, now)...)
|
||||
health = append(health, provider.weKnoraProbe(ctx, now))
|
||||
health = append(health, provider.productionWeKnoraProbe(ctx, now))
|
||||
health = append(health, provider.httpProbe(ctx, "mineru", "MinerU", provider.minerUBaseURL, now))
|
||||
// Not-applicable dependencies stay explicit (embedding/llm managed by
|
||||
// WeKnora, redis/mq/oss not deployed).
|
||||
@@ -299,10 +312,14 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
|
||||
|
||||
// Readiness blocks only on services that ARE deployed and configured and
|
||||
// currently fail readiness; not_configured is surfaced as a warning elsewhere.
|
||||
// advisoryHealthKeys are reported to operators but never block the platform's
|
||||
// own readiness: a production endpoint outage must not stop the test pipeline.
|
||||
var advisoryHealthKeys = map[string]bool{"weknora-production": true}
|
||||
|
||||
func overallReadiness(health []governance.ServiceHealth) (bool, []string) {
|
||||
blocked := []string{}
|
||||
for _, item := range health {
|
||||
if !item.Applicable || !item.Configured {
|
||||
if !item.Applicable || !item.Configured || advisoryHealthKeys[item.Key] {
|
||||
continue
|
||||
}
|
||||
if item.Readiness != ReadReady {
|
||||
|
||||
@@ -5,9 +5,13 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
func testNow() time.Time { return time.Date(2026, 9, 12, 9, 0, 0, 0, time.UTC) }
|
||||
@@ -82,3 +86,58 @@ func TestSanitizeProbeErrorTruncatesLongMessages(t *testing.T) {
|
||||
t.Fatalf("len=%d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestProductionWeKnoraProbeReportsRealEndpointState freezes the production
|
||||
// WeKnora contract: the console shows the endpoint's real state, an unset
|
||||
// address is an explicit not-configured state, and no reason ever leaks the URL.
|
||||
func TestProductionWeKnoraProbeReportsRealEndpointState(t *testing.T) {
|
||||
// Unset address: explicit not_configured, never a fake "reachable".
|
||||
provider := &RealProvider{httpClient: &http.Client{Timeout: time.Second}, health: newHealthTracker()}
|
||||
health := provider.productionWeKnoraProbe(context.Background(), testNow())
|
||||
if health.Key != "weknora-production" || health.Name != "生产 WeKnora" || health.Configured {
|
||||
t.Fatalf("production rows must be identified: %+v", health)
|
||||
}
|
||||
if health.Liveness != LiveUnknown || health.Readiness != ReadNotConfigured {
|
||||
t.Fatalf("unconfigured production endpoint = %+v", health)
|
||||
}
|
||||
|
||||
// Reachable: /health is actually called on the configured address.
|
||||
probed := ""
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
probed = request.URL.Path
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
provider = &RealProvider{httpClient: server.Client(), productionWeKnoraBaseURL: server.URL, health: newHealthTracker()}
|
||||
health = provider.productionWeKnoraProbe(context.Background(), testNow())
|
||||
if probed != "/health" || health.Liveness != LiveUp || health.Readiness != ReadReady || !health.Configured {
|
||||
t.Fatalf("reachable production endpoint = %+v (probed %q)", health, probed)
|
||||
}
|
||||
|
||||
// Reachable but refusing new work: up/blocked with a sanitized reason.
|
||||
full := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(http.StatusTooManyRequests)
|
||||
}))
|
||||
defer full.Close()
|
||||
provider = &RealProvider{httpClient: full.Client(), productionWeKnoraBaseURL: full.URL, health: newHealthTracker()}
|
||||
health = provider.productionWeKnoraProbe(context.Background(), testNow())
|
||||
if health.Liveness != LiveUp || health.Readiness != ReadBlocked || health.Reason == "" || strings.Contains(health.Reason, full.URL) {
|
||||
t.Fatalf("capacity-blocked production endpoint = %+v", health)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOverallReadinessTreatsProductionEndpointAsAdvisory keeps the platform's
|
||||
// own readiness independent from the production endpoint's availability.
|
||||
func TestOverallReadinessTreatsProductionEndpointAsAdvisory(t *testing.T) {
|
||||
health := []governance.ServiceHealth{
|
||||
{Key: "postgres", Name: "PostgreSQL", Configured: true, Applicable: true, Liveness: LiveUp, Readiness: ReadReady},
|
||||
{Key: "weknora-production", Name: "生产 WeKnora", Configured: true, Applicable: true, Liveness: LiveDown, Readiness: ReadBlocked, Reason: "网络不可达"},
|
||||
}
|
||||
if ok, blocked := overallReadiness(health); !ok || len(blocked) != 0 {
|
||||
t.Fatalf("production endpoint must not block readiness: ok=%v blocked=%v", ok, blocked)
|
||||
}
|
||||
health[0].Readiness = ReadBlocked
|
||||
if ok, blocked := overallReadiness(health); ok || len(blocked) != 1 || blocked[0] != "postgres" {
|
||||
t.Fatalf("real dependency failure must still block: ok=%v blocked=%v", ok, blocked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,11 @@ func TestRealServicesHealthMatrix(t *testing.T) {
|
||||
if byKey["weknora/r"] != ReadNotConfigured || byKey["mineru/r"] != ReadNotConfigured {
|
||||
t.Fatalf("unconfigured deps must be explicit: %v %v", byKey["weknora/r"], byKey["mineru/r"])
|
||||
}
|
||||
// Production WeKnora is probed separately; with no address configured it is
|
||||
// an explicit not-configured state, never a fake "reachable".
|
||||
if byKey["weknora-production/r"] != ReadNotConfigured || byKey["weknora-production/l"] != LiveUnknown {
|
||||
t.Fatalf("unconfigured production endpoint = %v/%v", byKey["weknora-production/l"], byKey["weknora-production/r"])
|
||||
}
|
||||
for _, key := range []string{"redis", "oss", "embedding", "llm"} {
|
||||
if byKey[key+"/r"] != ReadNotApplicable || byKey[key+"/l"] != LiveUnknown {
|
||||
t.Fatalf("not-deployed %s = %v/%v", key, byKey[key+"/l"], byKey[key+"/r"])
|
||||
|
||||
+51
-10
@@ -30,6 +30,20 @@ type RealProviderConfig struct {
|
||||
HTTPClient *http.Client
|
||||
WeKnoraBaseURL string
|
||||
MinerUBaseURL string
|
||||
// TestWeKnoraResolver reads the test endpoint an admin saved in the web
|
||||
// settings, so 「服务配置」is the single place the console probes. The env
|
||||
// value above stays the bootstrap fallback for containers wired before the
|
||||
// UI existed.
|
||||
TestWeKnoraResolver func(ctx context.Context) string
|
||||
// ProductionWeKnoraBaseURL lets the console show the real state of the
|
||||
// production WeKnora endpoint. Publishing itself keeps reading its target
|
||||
// from the release runtime config, never from here.
|
||||
ProductionWeKnoraBaseURL string
|
||||
// ProductionWeKnoraResolver reads the endpoint an admin saved in the web
|
||||
// settings. That value is what the console probes — the web page is the
|
||||
// place operators configure it — and the env value above stays the
|
||||
// bootstrap fallback for containers that were wired before the UI existed.
|
||||
ProductionWeKnoraResolver func(ctx context.Context) string
|
||||
// WeKnoraReadiness optionally exercises a real read against a routing
|
||||
// knowledge base (nil = API key not configured; liveness-only).
|
||||
WeKnoraReadiness func(ctx context.Context) error
|
||||
@@ -39,14 +53,40 @@ type RealProviderConfig struct {
|
||||
}
|
||||
|
||||
type RealProvider struct {
|
||||
db Database
|
||||
now func() time.Time
|
||||
httpClient *http.Client
|
||||
weknoraBaseURL string
|
||||
minerUBaseURL string
|
||||
weknoraReadiness func(ctx context.Context) error
|
||||
workerStaleAfter time.Duration
|
||||
health *healthTracker
|
||||
db Database
|
||||
now func() time.Time
|
||||
httpClient *http.Client
|
||||
weknoraBaseURL string
|
||||
minerUBaseURL string
|
||||
testWeKnoraResolver func(ctx context.Context) string
|
||||
productionWeKnoraBaseURL string
|
||||
productionWeKnoraResolver func(ctx context.Context) string
|
||||
weknoraReadiness func(ctx context.Context) error
|
||||
workerStaleAfter time.Duration
|
||||
health *healthTracker
|
||||
}
|
||||
|
||||
// resolveTestWeKnoraBaseURL prefers the admin-saved web setting and falls back to
|
||||
// the env bootstrap value, so the page is the place to change the test endpoint.
|
||||
func (provider *RealProvider) resolveTestWeKnoraBaseURL(ctx context.Context) string {
|
||||
if provider.testWeKnoraResolver != nil {
|
||||
if value := strings.TrimSpace(provider.testWeKnoraResolver(ctx)); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return provider.weknoraBaseURL
|
||||
}
|
||||
|
||||
// resolveProductionWeKnoraBaseURL prefers the admin-saved web setting and falls
|
||||
// back to the env bootstrap value: the page wins, the container env only fills in
|
||||
// when nobody configured it in the UI.
|
||||
func (provider *RealProvider) resolveProductionWeKnoraBaseURL(ctx context.Context) string {
|
||||
if provider.productionWeKnoraResolver != nil {
|
||||
if value := strings.TrimSpace(provider.productionWeKnoraResolver(ctx)); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return provider.productionWeKnoraBaseURL
|
||||
}
|
||||
|
||||
func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
|
||||
@@ -63,7 +103,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
|
||||
if stale <= 0 {
|
||||
stale = time.Minute
|
||||
}
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
|
||||
}
|
||||
|
||||
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
|
||||
@@ -73,7 +113,8 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
overview.Services = append(overview.Services, provider.postgresHealth(ctx, now), provider.queueHealth(ctx, now))
|
||||
overview.Health = provider.Services(ctx)
|
||||
overview.Services = append(overview.Services,
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.weknoraBaseURL, now),
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now),
|
||||
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE ui_setting_revisions DROP COLUMN IF EXISTS production_weknora_base_url;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- The production WeKnora endpoint is operator configuration, so it belongs in
|
||||
-- the versioned web settings (admin-only, audited, atomic activation) instead of
|
||||
-- only in container env. Empty means "not configured": the console then says so
|
||||
-- honestly instead of inventing an address. Credentials are never stored here —
|
||||
-- they stay file references.
|
||||
ALTER TABLE ui_setting_revisions ADD COLUMN IF NOT EXISTS production_weknora_base_url TEXT NOT NULL DEFAULT '';
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE ui_setting_revisions DROP COLUMN IF EXISTS test_weknora_base_url;
|
||||
ALTER TABLE ui_setting_revisions DROP COLUMN IF EXISTS production_tenant_id;
|
||||
ALTER TABLE ui_setting_revisions DROP COLUMN IF EXISTS production_knowledge_base_id;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- 服务配置界面收敛为四项:生产地址、测试地址、生产 ID(租户)、知识库 ID。
|
||||
-- 与生产地址同一规格:空 = 未配置;只有管理员能改;走版本化修订 + 审计 + 原子切换。
|
||||
-- ID 只做格式校验并如实展示,凭据仍然是文件引用,绝不进这一行。
|
||||
ALTER TABLE ui_setting_revisions ADD COLUMN IF NOT EXISTS test_weknora_base_url TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE ui_setting_revisions ADD COLUMN IF NOT EXISTS production_tenant_id TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE ui_setting_revisions ADD COLUMN IF NOT EXISTS production_knowledge_base_id TEXT NOT NULL DEFAULT '';
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 41 {
|
||||
t.Fatalf("migration count = %d, want 41", len(migrations))
|
||||
if len(migrations) != 43 {
|
||||
t.Fatalf("migration count = %d, want 43", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
@@ -104,6 +104,10 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if migrations[34].Version != 35 || !strings.Contains(migrations[34].UpSQL, "CREATE TABLE IF NOT EXISTS filename_filter_rules") || !strings.Contains(migrations[34].UpSQL, "'filtered'") {
|
||||
t.Fatalf("migration 35 = %#v", migrations[34])
|
||||
}
|
||||
// 服务配置收敛为四项:两个地址 + 生产 ID(租户)+ 知识库 ID,全部走同一版本化修订。
|
||||
if migrations[42].Version != 43 || !strings.Contains(migrations[42].UpSQL, "test_weknora_base_url") || !strings.Contains(migrations[42].UpSQL, "production_tenant_id") || !strings.Contains(migrations[42].UpSQL, "production_knowledge_base_id") {
|
||||
t.Fatalf("migration 43 = %#v", migrations[42])
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessingConfirmationMigrationSeparatesPlanningFromUpload(t *testing.T) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
var ErrInvalidUISettings = errors.New("invalid UI settings")
|
||||
|
||||
const uiSettingsColumns = `id,state,document_refresh_seconds,resource_refresh_seconds,stalled_after_seconds,finalizing_after_seconds,ingestion_concurrency,updated_by,created_at,activated_at,retired_at,error_code`
|
||||
const uiSettingsColumns = `id,state,document_refresh_seconds,resource_refresh_seconds,stalled_after_seconds,finalizing_after_seconds,ingestion_concurrency,test_weknora_base_url,production_weknora_base_url,production_tenant_id,production_knowledge_base_id,updated_by,created_at,activated_at,retired_at,error_code`
|
||||
|
||||
const getActiveUISettingsSQL = `
|
||||
SELECT ` + uiSettingsColumns + `
|
||||
@@ -24,11 +24,19 @@ WHERE state = 'active'
|
||||
const createUISettingsCandidateSQL = `
|
||||
INSERT INTO ui_setting_revisions(
|
||||
id,state,document_refresh_seconds,resource_refresh_seconds,
|
||||
stalled_after_seconds,finalizing_after_seconds,ingestion_concurrency,updated_by,created_at
|
||||
) VALUES($1,'validated',$2,$3,$4,$5,$6,$7,$8)
|
||||
stalled_after_seconds,finalizing_after_seconds,ingestion_concurrency,
|
||||
test_weknora_base_url,production_weknora_base_url,production_tenant_id,
|
||||
production_knowledge_base_id,updated_by,created_at
|
||||
) VALUES($1,'validated',$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
|
||||
RETURNING ` + uiSettingsColumns + `
|
||||
`
|
||||
|
||||
const getUISettingsRevisionSQL = `
|
||||
SELECT ` + uiSettingsColumns + `
|
||||
FROM ui_setting_revisions
|
||||
WHERE id=$1
|
||||
`
|
||||
|
||||
const lockUISettingsRevisionSQL = `
|
||||
SELECT ` + uiSettingsColumns + `
|
||||
FROM ui_setting_revisions
|
||||
@@ -64,9 +72,21 @@ func (s *Store) CreateUISettingsCandidate(ctx context.Context, request governanc
|
||||
return scanUISettings(s.db.QueryRow(ctx, createUISettingsCandidateSQL,
|
||||
id, request.DocumentRefreshSeconds, request.ResourceRefreshSeconds,
|
||||
request.StalledAfterSeconds, request.FinalizingAfterSeconds, request.IngestionConcurrency,
|
||||
request.TestWeKnoraBaseURL, request.ProductionWeKnoraBaseURL,
|
||||
request.ProductionTenantID, request.ProductionKnowledgeBaseID,
|
||||
request.UpdatedBy, request.Now.UTC()))
|
||||
}
|
||||
|
||||
// GetUISettingsRevision reads one revision in any state. Activation uses it to
|
||||
// compare the incoming endpoint against the active one before letting an
|
||||
// engineer apply a change only an admin may author.
|
||||
func (s *Store) GetUISettingsRevision(ctx context.Context, revisionID string) (governance.UISettings, error) {
|
||||
if !validShortID(revisionID) {
|
||||
return governance.UISettings{}, ErrInvalidUISettings
|
||||
}
|
||||
return scanUISettings(s.db.QueryRow(ctx, getUISettingsRevisionSQL, revisionID))
|
||||
}
|
||||
|
||||
func (s *Store) ActivateUISettings(ctx context.Context, revisionID string, now time.Time) (governance.UISettings, error) {
|
||||
if !validShortID(revisionID) || now.IsZero() {
|
||||
return governance.UISettings{}, ErrInvalidUISettings
|
||||
@@ -125,7 +145,8 @@ func scanUISettings(row interface{ Scan(...any) error }) (governance.UISettings,
|
||||
var settings governance.UISettings
|
||||
if err := row.Scan(&settings.ID, &settings.State, &settings.DocumentRefreshSeconds,
|
||||
&settings.ResourceRefreshSeconds, &settings.StalledAfterSeconds, &settings.FinalizingAfterSeconds,
|
||||
&settings.IngestionConcurrency,
|
||||
&settings.IngestionConcurrency, &settings.TestWeKnoraBaseURL, &settings.ProductionWeKnoraBaseURL,
|
||||
&settings.ProductionTenantID, &settings.ProductionKnowledgeBaseID,
|
||||
&settings.UpdatedBy, &settings.CreatedAt, &settings.ActivatedAt, &settings.RetiredAt, &settings.ErrorCode); err != nil {
|
||||
return governance.UISettings{}, fmt.Errorf("scan UI settings: %w", err)
|
||||
}
|
||||
|
||||
@@ -12,17 +12,17 @@ import (
|
||||
|
||||
func TestUISettingsCandidateAndActiveProjectionAreVersioned(t *testing.T) {
|
||||
now := time.Date(2026, 9, 10, 6, 0, 0, 0, time.UTC)
|
||||
row := uiSettingsRow{id: "settings-safe", state: "validated", documentRefresh: 30, resourceRefresh: 60, stalledAfter: 3600, finalizingAfter: 14400, updatedBy: "engineer-1", createdAt: now}
|
||||
row := uiSettingsRow{id: "settings-safe", state: "validated", documentRefresh: 30, resourceRefresh: 60, stalledAfter: 3600, finalizingAfter: 14400, testBaseURL: "https://weknora.test.example", productionBaseURL: "https://weknora.prod.example", productionTenantID: "10000", productionKnowledgeBaseID: "kb-prod-1", updatedBy: "engineer-1", createdAt: now}
|
||||
db := &recordingDB{row: row}
|
||||
candidate, err := NewStore(db).CreateUISettingsCandidate(context.Background(), governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, UpdatedBy: "engineer-1", Now: now})
|
||||
candidate, err := NewStore(db).CreateUISettingsCandidate(context.Background(), governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, TestWeKnoraBaseURL: "https://weknora.test.example", ProductionWeKnoraBaseURL: "https://weknora.prod.example", ProductionTenantID: "10000", ProductionKnowledgeBaseID: "kb-prod-1", UpdatedBy: "engineer-1", Now: now})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if candidate.State != "validated" || candidate.DocumentRefreshSeconds != 30 || candidate.UpdatedBy != "engineer-1" {
|
||||
if candidate.State != "validated" || candidate.DocumentRefreshSeconds != 30 || candidate.UpdatedBy != "engineer-1" || candidate.TestWeKnoraBaseURL != "https://weknora.test.example" || candidate.ProductionWeKnoraBaseURL != "https://weknora.prod.example" || candidate.ProductionTenantID != "10000" || candidate.ProductionKnowledgeBaseID != "kb-prod-1" {
|
||||
t.Fatalf("candidate=%#v", candidate)
|
||||
}
|
||||
sql := strings.ToLower(db.queryRowSQL)
|
||||
for _, required := range []string{"insert into ui_setting_revisions", "'validated'", "returning"} {
|
||||
for _, required := range []string{"insert into ui_setting_revisions", "'validated'", "test_weknora_base_url", "production_weknora_base_url", "production_tenant_id", "production_knowledge_base_id", "returning"} {
|
||||
if !strings.Contains(sql, required) {
|
||||
t.Fatalf("candidate SQL missing %q", required)
|
||||
}
|
||||
@@ -48,12 +48,49 @@ func TestUISettingsRejectInvalidCandidate(t *testing.T) {
|
||||
if !errors.Is(err, ErrInvalidUISettings) {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
// The web-typed production endpoint is validated before it can reach the
|
||||
// database: only a bare http(s) origin is accepted, never a URL with
|
||||
// embedded credentials, a query string or a fragment.
|
||||
for _, endpoint := range []string{
|
||||
"weknora.prod.example",
|
||||
"https://user:pass@weknora.prod.example",
|
||||
"https://weknora.prod.example/?api_key=leaked",
|
||||
"https://weknora.prod.example/#fragment",
|
||||
" http://weknora.prod.example",
|
||||
} {
|
||||
request := governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, ProductionWeKnoraBaseURL: endpoint, UpdatedBy: "admin-1", Now: time.Now()}
|
||||
if _, err := NewStore(&recordingDB{}).CreateUISettingsCandidate(context.Background(), request); !errors.Is(err, ErrInvalidUISettings) {
|
||||
t.Fatalf("endpoint %q was accepted, error=%v", endpoint, err)
|
||||
}
|
||||
}
|
||||
// Same rule for the test endpoint, plus the two new ID fields: a tenant ID is
|
||||
// decimal digits, a knowledge base ID carries no whitespace and no URL pieces.
|
||||
for _, testEndpoint := range []string{"weknora.test.example", "https://user:pass@weknora.test.example", "https://weknora.test.example?token=abc", " https://weknora.test.example"} {
|
||||
request := governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, TestWeKnoraBaseURL: testEndpoint, UpdatedBy: "admin-1", Now: time.Now()}
|
||||
if _, err := NewStore(&recordingDB{}).CreateUISettingsCandidate(context.Background(), request); !errors.Is(err, ErrInvalidUISettings) {
|
||||
t.Fatalf("test endpoint %q was accepted, error=%v", testEndpoint, err)
|
||||
}
|
||||
}
|
||||
for _, tenantID := range []string{"abc", "10 000", "-1", "0", "10000.5", "10000000000000000000000"} {
|
||||
request := governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, ProductionTenantID: tenantID, UpdatedBy: "admin-1", Now: time.Now()}
|
||||
if _, err := NewStore(&recordingDB{}).CreateUISettingsCandidate(context.Background(), request); !errors.Is(err, ErrInvalidUISettings) {
|
||||
t.Fatalf("production tenant id %q was accepted, error=%v", tenantID, err)
|
||||
}
|
||||
}
|
||||
for _, kbID := range []string{"kb/abc", "kb abc", "kb-abc?x", "https://weknora.prod.example/kb", "kb#frag"} {
|
||||
request := governance.CreateUISettingsCandidateRequest{DocumentRefreshSeconds: 30, ResourceRefreshSeconds: 60, StalledAfterSeconds: 3600, FinalizingAfterSeconds: 14400, IngestionConcurrency: 2, ProductionKnowledgeBaseID: kbID, UpdatedBy: "admin-1", Now: time.Now()}
|
||||
if _, err := NewStore(&recordingDB{}).CreateUISettingsCandidate(context.Background(), request); !errors.Is(err, ErrInvalidUISettings) {
|
||||
t.Fatalf("production knowledge base id %q was accepted, error=%v", kbID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type uiSettingsRow struct {
|
||||
id, state, updatedBy, errorCode string
|
||||
documentRefresh, resourceRefresh, stalledAfter, finalizingAfter int
|
||||
ingestionConcurrency int
|
||||
testBaseURL, productionBaseURL string
|
||||
productionTenantID, productionKnowledgeBaseID string
|
||||
createdAt time.Time
|
||||
activatedAt, retiredAt *time.Time
|
||||
}
|
||||
@@ -62,6 +99,8 @@ func (row uiSettingsRow) Scan(dest ...any) error {
|
||||
*dest[0].(*string), *dest[1].(*string) = row.id, row.state
|
||||
*dest[2].(*int), *dest[3].(*int), *dest[4].(*int), *dest[5].(*int) = row.documentRefresh, row.resourceRefresh, row.stalledAfter, row.finalizingAfter
|
||||
*dest[6].(*int) = row.ingestionConcurrency
|
||||
*dest[7].(*string), *dest[8].(*time.Time), *dest[9].(**time.Time), *dest[10].(**time.Time), *dest[11].(*string) = row.updatedBy, row.createdAt, row.activatedAt, row.retiredAt, row.errorCode
|
||||
*dest[7].(*string), *dest[8].(*string) = row.testBaseURL, row.productionBaseURL
|
||||
*dest[9].(*string), *dest[10].(*string) = row.productionTenantID, row.productionKnowledgeBaseID
|
||||
*dest[11].(*string), *dest[12].(*time.Time), *dest[13].(**time.Time), *dest[14].(**time.Time), *dest[15].(*string) = row.updatedBy, row.createdAt, row.activatedAt, row.retiredAt, row.errorCode
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -234,6 +234,23 @@ func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBase reads a single knowledge base by id. A knowledge base that is
|
||||
// not there surfaces as *HTTPError with status 404, so a caller can tell
|
||||
// "definitely absent" from "could not ask".
|
||||
func (c *Client) GetKnowledgeBase(ctx context.Context, knowledgeBaseID string) (KnowledgeBase, error) {
|
||||
if !validPathSegment(knowledgeBaseID) {
|
||||
return KnowledgeBase{}, errors.New("invalid knowledge base ID")
|
||||
}
|
||||
var response knowledgeBaseResponse
|
||||
if err := c.doJSON(ctx, http.MethodGet, "/api/v1/knowledge-bases/"+knowledgeBaseID, nil, &response); err != nil {
|
||||
return KnowledgeBase{}, err
|
||||
}
|
||||
if !response.Success || response.Data.ID == "" {
|
||||
return KnowledgeBase{}, errors.New("WeKnora returned an unsuccessful knowledge base response")
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListChunks(ctx context.Context, knowledgeID string, page, pageSize int, chunkTypes []string) ([]Chunk, int64, error) {
|
||||
if !validPathSegment(knowledgeID) || !validPage(page, pageSize) {
|
||||
return nil, 0, errors.New("invalid chunk list request")
|
||||
|
||||
@@ -50,6 +50,78 @@ func TestClientGetKnowledgeUsesPinnedOriginAndAPIKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientReadsKnowledgeBaseInventoryAndDetail(t *testing.T) {
|
||||
const inventory = `{"success":true,"data":[{"id":"kb-1","name":"生产知识库","knowledge_count":4,"chunk_count":9,"tenant_id":10000}]}`
|
||||
const detail = `{"success":true,"data":{"id":"kb-1","name":"生产知识库","knowledge_count":4,"chunk_count":9,"tenant_id":10000}}`
|
||||
requests := make([]string, 0, 2)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("X-API-Key"); got != "test-api-key" {
|
||||
t.Fatalf("X-API-Key = %q", got)
|
||||
}
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/api/v1/knowledge-bases" {
|
||||
_, _ = w.Write([]byte(inventory))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(detail))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "test-api-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
bases, err := client.ListKnowledgeBases(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListKnowledgeBases() error = %v", err)
|
||||
}
|
||||
if len(bases) != 1 || bases[0].ID != "kb-1" || bases[0].Name != "生产知识库" || bases[0].TenantID != 10000 {
|
||||
t.Fatalf("bases = %#v", bases)
|
||||
}
|
||||
base, err := client.GetKnowledgeBase(context.Background(), "kb-1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledgeBase() error = %v", err)
|
||||
}
|
||||
if base.ID != "kb-1" || base.TenantID != 10000 || base.Name != "生产知识库" {
|
||||
t.Fatalf("base = %#v", base)
|
||||
}
|
||||
if got := strings.Join(requests, ","); got != "GET /api/v1/knowledge-bases,GET /api/v1/knowledge-bases/kb-1" {
|
||||
t.Fatalf("requests = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientReportsMissingKnowledgeBaseAsNotFound(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":1003,"message":"knowledge base not found"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "test-api-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
if _, err := client.GetKnowledgeBase(context.Background(), "kb-missing"); err == nil {
|
||||
t.Fatal("expected an error for a missing knowledge base")
|
||||
} else {
|
||||
var httpErr *HTTPError
|
||||
if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("error = %v, want HTTPError 404", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledgeBaseRejectsUnsafeID(t *testing.T) {
|
||||
client, err := NewClient(ClientConfig{BaseURL: "http://127.0.0.1:1", APIKey: "test-api-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
if _, err := client.GetKnowledgeBase(context.Background(), "kb-1/../../etc/passwd"); err == nil {
|
||||
t.Fatal("expected an error for an unsafe knowledge base ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientRequiresHTTPSExceptForLoopbackTests(t *testing.T) {
|
||||
for _, rawURL := range []string{
|
||||
"http://example.com",
|
||||
|
||||
@@ -69,6 +69,10 @@ type KnowledgeBase struct {
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
// TenantID is the owning tenant WeKnora reports for the knowledge base.
|
||||
// 「服务配置」uses it to prove the saved production ID really owns the saved
|
||||
// knowledge base instead of trusting two unrelated numbers.
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
}
|
||||
|
||||
type knowledgeBaseListResponse struct {
|
||||
@@ -76,6 +80,11 @@ type knowledgeBaseListResponse struct {
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
}
|
||||
|
||||
type knowledgeBaseResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data KnowledgeBase `json:"data"`
|
||||
}
|
||||
|
||||
type chunkListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []Chunk `json:"data"`
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
// Package serviceverify performs the real read behind 「服务配置」: the configured
|
||||
// production endpoint is asked whether the saved knowledge base id exists and
|
||||
// whether it really belongs to the saved production tenant. Two numbers stored in
|
||||
// the database with nobody consuming them are decoration; this is the consumer.
|
||||
//
|
||||
// Blocking policy: only a definitive negative answer (HTTP 404/400 on the
|
||||
// knowledge base, or a tenant that provably differs) rejects a save. Timeouts,
|
||||
// 5xx, 401/403, a missing key file or a missing endpoint are reported as
|
||||
// 「未核验」and let the save through — an operator must always be able to repair a
|
||||
// broken configuration.
|
||||
package serviceverify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 10 * time.Second
|
||||
maxListedCandidates = 5
|
||||
)
|
||||
|
||||
// Config wires the verifier to the same credential files the rest of the platform
|
||||
// uses. Credentials stay file references (never values) and are read per call, so
|
||||
// rotating a key file needs no restart.
|
||||
type Config struct {
|
||||
TestAPIKeyFile string
|
||||
ProductionAPIKeyFile string
|
||||
TestBaseURLFallback string
|
||||
ProductionBaseURLFallback string
|
||||
TestAllowDockerHTTP bool
|
||||
ProductionAllowDockerHTTP bool
|
||||
Timeout time.Duration
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Verifier asks endpoints what they really hold. It is safe for concurrent use.
|
||||
type Verifier struct {
|
||||
config Config
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func New(config Config) *Verifier {
|
||||
if config.Timeout <= 0 {
|
||||
config.Timeout = defaultTimeout
|
||||
}
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &Verifier{
|
||||
config: config,
|
||||
httpClient: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// VerifyServiceTarget probes both endpoints and, when it has a credential to ask
|
||||
// with, checks the production knowledge base and tenant for real.
|
||||
func (verifier *Verifier) VerifyServiceTarget(ctx context.Context, target governance.ServiceTarget) governance.ServiceTargetVerification {
|
||||
productionBaseURL := firstNonEmpty(target.ProductionBaseURL, verifier.config.ProductionBaseURLFallback)
|
||||
testBaseURL := firstNonEmpty(target.TestBaseURL, verifier.config.TestBaseURLFallback)
|
||||
productionKey := verifier.apiKey(verifier.config.ProductionAPIKeyFile)
|
||||
testKey := verifier.apiKey(verifier.config.TestAPIKeyFile)
|
||||
|
||||
verification := governance.ServiceTargetVerification{
|
||||
Status: governance.ServiceTargetNotConfigured,
|
||||
Message: "未配置:两项 ID 都留空,没有可核验的值",
|
||||
TestEndpoint: verifier.probeEndpoint(ctx, testBaseURL, testKey, "测试地址", verifier.config.TestAllowDockerHTTP),
|
||||
ProductionEndpoint: verifier.probeEndpoint(ctx, productionBaseURL, productionKey, "生产地址", verifier.config.ProductionAllowDockerHTTP),
|
||||
CheckedAt: verifier.config.Now().UTC(),
|
||||
}
|
||||
if target.ProductionKnowledgeBaseID == "" && target.ProductionTenantID == "" {
|
||||
return verification
|
||||
}
|
||||
if productionBaseURL == "" {
|
||||
verification.Status = governance.ServiceTargetCannotVerify
|
||||
verification.Message = "未核验:还没有生产地址可查,保存未被阻断"
|
||||
return verification
|
||||
}
|
||||
if productionKey == "" {
|
||||
verification.Status = governance.ServiceTargetCannotVerify
|
||||
verification.Message = "未核验:没有可用的生产 API Key 文件(PRODUCTION_WEKNORA_API_KEY_FILE),保存未被阻断"
|
||||
return verification
|
||||
}
|
||||
client, err := verifier.client(productionBaseURL, productionKey, verifier.config.ProductionAllowDockerHTTP)
|
||||
if err != nil {
|
||||
verification.Status = governance.ServiceTargetCannotVerify
|
||||
verification.Message = "未核验:生产地址不能作为 WeKnora 端点(" + err.Error() + "),保存未被阻断"
|
||||
return verification
|
||||
}
|
||||
if target.ProductionKnowledgeBaseID == "" {
|
||||
return verifier.verifyTenantOnly(ctx, client, target, verification)
|
||||
}
|
||||
return verifier.verifyKnowledgeBase(ctx, client, target, verification)
|
||||
}
|
||||
|
||||
// verifyKnowledgeBase is the strong check: the knowledge base must exist on the
|
||||
// configured production endpoint, and (when a production ID is filled) its tenant
|
||||
// must be that ID.
|
||||
func (verifier *Verifier) verifyKnowledgeBase(ctx context.Context, client *weknora.Client, target governance.ServiceTarget, verification governance.ServiceTargetVerification) governance.ServiceTargetVerification {
|
||||
base, err := client.GetKnowledgeBase(ctx, target.ProductionKnowledgeBaseID)
|
||||
switch {
|
||||
case err == nil:
|
||||
observed := strconv.FormatUint(base.TenantID, 10)
|
||||
name := base.Name
|
||||
if name == "" {
|
||||
name = base.ID
|
||||
}
|
||||
verification.KnowledgeBaseName = base.Name
|
||||
verification.ObservedTenantID = observed
|
||||
if target.ProductionTenantID != "" && target.ProductionTenantID != observed {
|
||||
verification.Status = governance.ServiceTargetTenantMismatch
|
||||
verification.Blocked = true
|
||||
verification.Message = fmt.Sprintf("未通过:知识库「%s」属于租户 %s,与你填的生产 ID %s 不一致", name, observed, target.ProductionTenantID)
|
||||
return verification
|
||||
}
|
||||
verification.Status = governance.ServiceTargetVerified
|
||||
if target.ProductionTenantID == "" {
|
||||
verification.Message = fmt.Sprintf("已核验:生产地址上存在知识库「%s」(租户 %s;未填生产 ID,没有比对租户)", name, observed)
|
||||
return verification
|
||||
}
|
||||
verification.Message = fmt.Sprintf("已核验:生产地址上存在知识库「%s」,租户 %s 一致", name, observed)
|
||||
return verification
|
||||
case isStatus(err, http.StatusNotFound, http.StatusBadRequest):
|
||||
verification.Status = governance.ServiceTargetMissing
|
||||
verification.Blocked = true
|
||||
verification.Message = fmt.Sprintf("未通过:生产地址上找不到知识库 ID「%s」%s", target.ProductionKnowledgeBaseID, verifier.candidateSuffix(ctx, client))
|
||||
return verification
|
||||
case isStatus(err, http.StatusUnauthorized, http.StatusForbidden):
|
||||
verification.Status = governance.ServiceTargetUnauthorized
|
||||
verification.Message = fmt.Sprintf("未核验:生产端点拒绝了这个 API Key(%s),保存未被阻断", describe(err))
|
||||
return verification
|
||||
default:
|
||||
verification.Status = governance.ServiceTargetUnreachable
|
||||
verification.Message = fmt.Sprintf("未核验:生产端点暂时不可用(%s),保存未被阻断", describe(err))
|
||||
return verification
|
||||
}
|
||||
}
|
||||
|
||||
// verifyTenantOnly runs when only the production ID is filled: the tenant must own
|
||||
// at least one knowledge base on the configured endpoint.
|
||||
func (verifier *Verifier) verifyTenantOnly(ctx context.Context, client *weknora.Client, target governance.ServiceTarget, verification governance.ServiceTargetVerification) governance.ServiceTargetVerification {
|
||||
tenant, err := strconv.ParseUint(target.ProductionTenantID, 10, 64)
|
||||
if err != nil || tenant == 0 {
|
||||
verification.Status = governance.ServiceTargetCannotVerify
|
||||
verification.Message = "未核验:生产 ID 不是十进制租户号,没有可查的值"
|
||||
return verification
|
||||
}
|
||||
bases, err := client.ListKnowledgeBases(ctx)
|
||||
switch {
|
||||
case err == nil:
|
||||
owned, tenants := 0, []string{}
|
||||
for _, base := range bases {
|
||||
observed := strconv.FormatUint(base.TenantID, 10)
|
||||
if base.TenantID == tenant {
|
||||
owned++
|
||||
}
|
||||
if !contains(tenants, observed) {
|
||||
tenants = append(tenants, observed)
|
||||
}
|
||||
}
|
||||
if owned > 0 {
|
||||
verification.Status = governance.ServiceTargetVerified
|
||||
verification.ObservedTenantID = strconv.FormatUint(tenant, 10)
|
||||
verification.Message = fmt.Sprintf("已核验:生产地址上有 %d 个知识库属于租户 %s", owned, target.ProductionTenantID)
|
||||
return verification
|
||||
}
|
||||
verification.Status = governance.ServiceTargetMissing
|
||||
verification.Blocked = true
|
||||
verification.Message = fmt.Sprintf("未通过:生产地址上没有属于租户 %s 的知识库(该地址现有租户:%s)", target.ProductionTenantID, strings.Join(tenants, "、"))
|
||||
return verification
|
||||
case isStatus(err, http.StatusUnauthorized, http.StatusForbidden):
|
||||
verification.Status = governance.ServiceTargetUnauthorized
|
||||
verification.Message = fmt.Sprintf("未核验:生产端点拒绝了这个 API Key(%s),保存未被阻断", describe(err))
|
||||
return verification
|
||||
default:
|
||||
verification.Status = governance.ServiceTargetUnreachable
|
||||
verification.Message = fmt.Sprintf("未核验:生产端点暂时不可用(%s),保存未被阻断", describe(err))
|
||||
return verification
|
||||
}
|
||||
}
|
||||
|
||||
// probeEndpoint reads the endpoint: a real knowledge-base list when a credential
|
||||
// is available, otherwise a plain /health liveness call. Advisory — the caller
|
||||
// only reports it.
|
||||
func (verifier *Verifier) probeEndpoint(ctx context.Context, baseURL, apiKey, label string, allowDockerHTTP bool) governance.ServiceEndpointStatus {
|
||||
if strings.TrimSpace(baseURL) == "" {
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointNotConfigured, Message: label + "未配置"}
|
||||
}
|
||||
if apiKey != "" {
|
||||
if client, err := verifier.client(baseURL, apiKey, allowDockerHTTP); err == nil {
|
||||
bases, listErr := client.ListKnowledgeBases(ctx)
|
||||
switch {
|
||||
case listErr == nil:
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointReachable, Message: fmt.Sprintf("%s可达(凭据有效,可列出 %d 个知识库)", label, len(bases))}
|
||||
case isStatus(listErr, http.StatusUnauthorized, http.StatusForbidden):
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointUnauthorized, Message: fmt.Sprintf("%s拒绝了这个 API Key(%s)", label, describe(listErr))}
|
||||
case !isStatus(listErr, http.StatusNotFound):
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointUnavailable, Message: fmt.Sprintf("%s不可用(%s)", label, describe(listErr))}
|
||||
}
|
||||
}
|
||||
}
|
||||
code, err := verifier.healthCode(ctx, baseURL)
|
||||
switch {
|
||||
case err != nil:
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointUnavailable, Message: fmt.Sprintf("%s不可达(%s)", label, describe(err))}
|
||||
case code == http.StatusUnauthorized || code == http.StatusForbidden:
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointUnauthorized, Message: fmt.Sprintf("%s活着,但未带凭据的探活被拒(HTTP %d)", label, code)}
|
||||
case code >= 200 && code < 300:
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointReachable, Message: fmt.Sprintf("%s /health 返回 HTTP %d", label, code)}
|
||||
default:
|
||||
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointUnavailable, Message: fmt.Sprintf("%s /health 返回 HTTP %d", label, code)}
|
||||
}
|
||||
}
|
||||
|
||||
func (verifier *Verifier) healthCode(ctx context.Context, baseURL string) (int, error) {
|
||||
parsed, err := url.Parse(baseURL)
|
||||
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return 0, errors.New("endpoint is not an http(s) origin")
|
||||
}
|
||||
parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/health"
|
||||
parsed.RawQuery, parsed.Fragment = "", ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response, err := verifier.httpClient.Do(request)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
||||
return response.StatusCode, nil
|
||||
}
|
||||
|
||||
// candidateSuffix names what the endpoint actually holds, so a rejected save is
|
||||
// fixable without a second trip to the WeKnora console.
|
||||
func (verifier *Verifier) candidateSuffix(ctx context.Context, client *weknora.Client) string {
|
||||
bases, err := client.ListKnowledgeBases(ctx)
|
||||
if err != nil || len(bases) == 0 {
|
||||
return ""
|
||||
}
|
||||
listed := make([]string, 0, maxListedCandidates)
|
||||
for index, base := range bases {
|
||||
if index == maxListedCandidates {
|
||||
break
|
||||
}
|
||||
name := base.Name
|
||||
if name == "" {
|
||||
name = "无名"
|
||||
}
|
||||
listed = append(listed, name+"("+base.ID+")")
|
||||
}
|
||||
if len(bases) > len(listed) {
|
||||
return fmt.Sprintf(";该地址现有 %d 个知识库,前 %d 个:%s", len(bases), len(listed), strings.Join(listed, "、"))
|
||||
}
|
||||
return fmt.Sprintf(";该地址现有 %d 个知识库:%s", len(bases), strings.Join(listed, "、"))
|
||||
}
|
||||
|
||||
func (verifier *Verifier) client(baseURL, apiKey string, allowDockerHTTP bool) (*weknora.Client, error) {
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: verifier.config.Timeout,
|
||||
AllowDockerHTTP: allowDockerHTTP,
|
||||
})
|
||||
}
|
||||
|
||||
// apiKey reads a credential file reference. An unset, unreadable or empty file is
|
||||
// not an error here: it means "no credential to ask with" and is reported as
|
||||
// 未核验 rather than failing the save.
|
||||
func (verifier *Verifier) apiKey(path string) string {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" || !strings.HasPrefix(path, "/") {
|
||||
return ""
|
||||
}
|
||||
key, err := weknora.ReadAPIKeyFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func isStatus(err error, statuses ...int) bool {
|
||||
var httpErr *weknora.HTTPError
|
||||
if !errors.As(err, &httpErr) {
|
||||
return false
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if httpErr.StatusCode == status {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// describe keeps a failed request readable without leaking internals: the class of
|
||||
// failure and the HTTP status, nothing else.
|
||||
func describe(err error) string {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return fmt.Sprintf("HTTP %d", httpErr.StatusCode)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return "超时"
|
||||
case errors.Is(err, context.Canceled):
|
||||
return "请求被取消"
|
||||
case weknora.IsRetryable(err):
|
||||
return "网络错误"
|
||||
default:
|
||||
return "请求失败"
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func contains(values []string, wanted string) bool {
|
||||
for _, value := range values {
|
||||
if value == wanted {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user