feat(binding): 连接四态验证、密钥尾号与私网 http 放行
build / build (push) Successful in 1m45s

在既有 kbbinding(迁移 000081)上补齐任务要求,不另建表、不另起路由:
- 测试连接区分 401/403(密钥无效 / 无权限)与不可达、成功四态;
- 视图回显密钥尾 4 位(服务端不存、不回读明文);
- key_action=clear 作为独立动作,清除后解析失败关闭、不回落文件旧 Key;
- 内外库留空 = 取消绑定,回报回退来源(测试侧部署默认库 / 生产侧同 ID 语义);
- 生产绑定回报在飞执行的冻结/仍可改指向条数,已冻结目标不被改写;
- 新增 WEKNORA_ALLOW_PRIVATE_HTTP:客户端/探活/连接页共用 HTTPAllowed,
  只放行 RFC1918/回环/链路本地 http,生产 18093 同网段反代因此可用。
This commit is contained in:
狐友 GXXP & Miku
2026-11-22 15:46:13 +08:00
committed by 姚章浩
parent cb026e8dd1
commit 7d91343e5f
21 changed files with 528 additions and 73 deletions
+2
View File
@@ -27,6 +27,8 @@ QA_AI_MASTER_KEY_FILE=
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS=
# Only opt in behind an already trusted TLS-terminating same-origin reverse proxy.
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## 开发快照 0.1.411(知识库连接:四态验证、尾号回显与私网 http)
### Added
- **测试连接区分四态**:`POST /api/v1/kb-bindings/{environment}/catalog` 现在把
401 与 403 分开返回「密钥无效」与「密钥无权限读取知识库列表」,与「地址不可达」
「成功(读到 N 个库)」互不混淆,页面对应四种提示。
- **密钥只回显尾 4 位**:绑定视图新增 `key_tail`,只用于展示;服务端不存尾号、
不存明文,主密钥不可用时该字段为空而不是猜。
- **清除密钥是独立动作**:`key_action=clear` 保留地址与内外库绑定,只把该侧凭据
清空(需二次确认),消费者解析随后失败关闭,不会回落到服务器文件里的旧 Key。
- **留空 = 取消绑定并回报回退**:视图新增 `internal_fallback` / `external_fallback`,
测试侧回退到部署默认库、生产侧回退到「同 ID 语义」,保存提示里写明退到哪。
- **生产绑定回报冻结计数**:`frozen` / `retargetable` 按在飞执行统计,已冻结的
`release_item_executions.target_knowledge_base_id` 不被改写。
### Changed
- 新增 `WEKNORA_ALLOW_PRIVATE_HTTP`:只放行 RFC1918/回环/链路本地 http,公网 http
仍拒绝。客户端、监控探活与连接页共用 `weknora.HTTPAllowed` 这一份判定,生产
`18093` 同网段反代因此可用,页面不再出现「卡片可达、列库失败」。
- 私网治理台(明文 http)录入密钥改用同源校验(Origin 与 Host 完全一致),
仍拒绝跨站与公网来源。
## 开发快照 0.1.410(存储页快照状态区分)
### Fixed
+13 -6
View File
@@ -128,6 +128,10 @@ func run(ctx context.Context, getenv func(string) string) error {
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
},
AllowPrivateHTTP: map[string]bool{
kbbinding.EnvTest: config.WeKnoraAllowPrivateHTTP,
kbbinding.EnvProduction: config.WeKnoraAllowPrivateHTTP,
},
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
settings, err := actionStore.GetActiveUISettings(resolveCtx)
if err != nil {
@@ -194,9 +198,10 @@ func run(ctx context.Context, getenv func(string) string) error {
return target, nil
}
readinessProber := readiness.Prober{
Resolve: readinessResolver,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
Resolve: readinessResolver,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
weknoraProbe := func(probeCtx context.Context) (string, error) {
result := readinessProber.Check(probeCtx)
@@ -207,10 +212,11 @@ func run(ctx context.Context, getenv func(string) string) error {
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return connection.BaseURL, connection.APIKey, err
},
timeout: config.TestWeKnoraHTTPTimeout,
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
timeout: config.TestWeKnoraHTTPTimeout,
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
if err != nil {
return err
}
@@ -292,6 +298,7 @@ func run(ctx context.Context, getenv func(string) string) error {
ProductionBindings: postgresstore.NewStore(pool),
ProductionKnowledgeBases: productionKnowledgeBases,
KBBindings: kbBindings,
WeKnoraAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL,
ServiceTargetVerifier: serviceTargetVerifier,
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
+10 -8
View File
@@ -52,9 +52,10 @@ func newWeKnoraReadinessResolver(
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
type weKnoraLister struct {
resolve func(context.Context) (baseURL, apiKey string, err error)
timeout time.Duration
allowDockerHTTP bool
resolve func(context.Context) (baseURL, apiKey string, err error)
timeout time.Duration
allowDockerHTTP bool
allowPrivateHTTP bool
}
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
@@ -76,7 +77,7 @@ func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.
if timeout <= 0 || timeout > 10*time.Second {
timeout = 10 * time.Second
}
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
if err != nil {
return nil, err
}
@@ -87,9 +88,10 @@ func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.
// (加密密钥),而不是另一条文件凭据。显式传入的地址必须与已保存连接一致,
// 防止把生产密钥发往另一个地址。
type productionKnowledgeBaseLister struct {
bindings *kbbinding.Store
timeout time.Duration
allowDockerHTTP bool
bindings *kbbinding.Store
timeout time.Duration
allowDockerHTTP bool
allowPrivateHTTP bool
}
func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
@@ -107,7 +109,7 @@ func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx co
if timeout <= 0 || timeout > 10*time.Second {
timeout = 10 * time.Second
}
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
if err != nil {
return nil, err
}
+3
View File
@@ -60,6 +60,9 @@ services:
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
# P10 readiness probe reads the routing KB with the same scoped key.
+12
View File
@@ -60,6 +60,18 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
**生产 090 的两段地址。** 生产机私网 IP 为 `172.29.151.11`,其 WeKnora API 对宿主回环发布 `127.0.0.1:18092`。测试治理机上已有 SSH 本地转发,治理 API 使用 host 网络,故页面的生产服务地址填写 **`http://127.0.0.1:18092`**。请求从治理 API 发出,经测试机的回环监听到生产机的回环 API。浏览器所在电脑的 `127.0.0.1:28189` 则用于打开治理页面。迁到 bridge 网络时要从新 API 容器重新验证上游可达性。
**直连反代(18093)与隧道(18092)二选一。** 若生产机已按前置要求提供
`172.29.151.11:18093`(只放行测试机),页面就填 `http://172.29.151.11:18093`,并在
部署侧设置 `WEKNORA_ALLOW_PRIVATE_HTTP=true` —— 它只放行 RFC1918/回环/链路本地
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
「同 ID 语义」,提示里会写明。
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
```bash
+9
View File
@@ -47,6 +47,9 @@ type Config struct {
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
TestWeKnoraAPIKeyFile string
// WeKnoraAllowPrivateHTTP 放行同网段 http(生产 18093 反代);只接受
// RFC1918/回环/链路本地,公网 http 仍拒绝。监控探活与列库共用同一判定。
WeKnoraAllowPrivateHTTP bool
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
WeKnoraBindingMasterKeyFile string
@@ -362,6 +365,12 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
}
}
if raw := getenv("WEKNORA_ALLOW_PRIVATE_HTTP"); raw != "" {
config.WeKnoraAllowPrivateHTTP, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("WEKNORA_ALLOW_PRIVATE_HTTP: %w", err)
}
}
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
}
+2 -2
View File
@@ -56,7 +56,7 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
return
}
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
@@ -87,7 +87,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
return
}
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
+26
View File
@@ -32,3 +32,29 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
}
return false
}
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
return true
}
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return false
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
}
+3
View File
@@ -142,6 +142,9 @@ type Config struct {
// internal/external bindings saved together. Nil keeps the page read-only
// and reports unavailable, never a fake success.
KBBindings KBBindingStore
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
WeKnoraAllowPrivateHTTP bool
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
// enumerates the production-side bases the operator can bind.
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
+108 -9
View File
@@ -48,11 +48,14 @@ var (
// View is the public projection. It never carries a key, ciphertext or any
// value derived from the key beyond "configured or not".
type View struct {
Environment string `json:"environment"`
Revision int64 `json:"revision"`
BaseURL string `json:"base_url"`
KeyConfigured bool `json:"key_configured"`
KeySource string `json:"key_source"`
Environment string `json:"environment"`
Revision int64 `json:"revision"`
BaseURL string `json:"base_url"`
KeyConfigured bool `json:"key_configured"`
KeySource string `json:"key_source"`
// KeyTail is the only part of the key the page may show. It is derived at
// read time and never stored, so a rotated master key cannot resurrect it.
KeyTail string `json:"key_tail"`
InternalKBID string `json:"internal_kb_id"`
InternalKBName string `json:"internal_kb_name"`
ExternalKBID string `json:"external_kb_id"`
@@ -69,6 +72,13 @@ type View struct {
// rows that had never been uploaded; a plain read reports zeros.
Replanned int `json:"replanned"`
RetiredDuplicates int `json:"retired_duplicates"`
// 留空绑定 = 取消绑定,页面必须说清回退到了哪里:测试侧回退到部署默认库,
// 生产侧回退到「同 ID 语义」。空串表示该方向仍有显式绑定。
InternalFallback string `json:"internal_fallback"`
ExternalFallback string `json:"external_fallback"`
// 生产侧冻结计数:执行已开始的发布项目标已钉死,保存绑定不会改写它们。
Frozen int `json:"frozen"`
Retargetable int `json:"retargetable"`
}
type Option struct {
@@ -119,6 +129,9 @@ type Options struct {
// AllowDockerHTTP mirrors the per-environment client policy (a single-label
// docker host may be reached over plain HTTP in the internal network).
AllowDockerHTTP map[string]bool
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses
// (production 18093 reverse proxy). Public http stays refused.
AllowPrivateHTTP map[string]bool
// LegacyBaseURL resolves the pre-existing endpoint (web setting first, then
// the deployment env value). It is only consulted when no row exists.
LegacyBaseURL func(context.Context, string) string
@@ -253,6 +266,13 @@ func (s *Store) Get(ctx context.Context, env string) (View, error) {
view.UpdatedBy = saved.UpdatedBy
view.UpdatedAt = saved.UpdatedAt
view.Source = "web"
if s.options.MasterKeyFile != "" {
if tail, ok := s.keyTail(saved, env); ok {
view.KeyTail = tail
}
}
s.fillFallbacks(ctx, env, &view)
s.fillExecutionCounts(ctx, env, &view)
return view, nil
}
// Legacy fallback: exactly what the consumers use before any page save.
@@ -270,10 +290,81 @@ func (s *Store) Get(ctx context.Context, env string) (View, error) {
view.ExternalKBID = external
}
view.Verification = "legacy"
s.fillFallbacks(ctx, env, &view)
s.fillExecutionCounts(ctx, env, &view)
s.fillNames(ctx, &view)
return view, nil
}
// keyTail decrypts only to keep the last four characters. It never returns the
// key and never writes the tail anywhere.
func (s *Store) keyTail(saved stored, env string) (string, bool) {
box := s.loadBox()
if box == nil || len(saved.KeyCiphertext) == 0 {
return "", false
}
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
if err != nil {
return "", false
}
runes := []rune(string(raw))
if len(runes) <= 4 {
return string(runes), true
}
return string(runes[len(runes)-4:]), true
}
// fillFallbacks explains where an unbound direction routes to. Without this the
// page could only say 「留空」without saying what 「空」means.
func (s *Store) fillFallbacks(ctx context.Context, env string, view *View) {
if view.InternalKBID != "" && view.ExternalKBID != "" {
return
}
if env == EnvProduction {
if view.InternalKBID == "" {
view.InternalFallback = "same-id"
}
if view.ExternalKBID == "" {
view.ExternalFallback = "same-id"
}
return
}
if s.options.LegacyBinding == nil {
return
}
internal, external, err := s.options.LegacyBinding(ctx, env)
if err != nil {
return
}
if view.InternalKBID == "" && strings.TrimSpace(internal) != "" {
view.InternalFallback = strings.TrimSpace(internal)
}
if view.ExternalKBID == "" && strings.TrimSpace(external) != "" {
view.ExternalFallback = strings.TrimSpace(external)
}
}
// fillExecutionCounts reports how many in-flight release items already have a
// frozen production target. Completed executions are history, not something a
// binding change could still move.
func (s *Store) fillExecutionCounts(ctx context.Context, env string, view *View) {
if env != EnvProduction {
return
}
var frozen, retargetable int
err := s.db.QueryRow(ctx, `
SELECT
COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''),
COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '')
FROM release_item_executions item
JOIN release_executions execution ON execution.id = item.release_execution_id
WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable)
if err != nil {
return
}
view.Frozen, view.Retargetable = frozen, retargetable
}
func keySource(configured bool) string {
if configured {
return "sealed"
@@ -395,6 +486,13 @@ func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey
return "", ErrInvalid
}
return apiKey, nil
case "clear":
// 清除密钥是独立动作:留下地址与绑定,只是这一侧不再有可用凭据,
// 消费者解析会失败关闭(不会悄悄回落到部署文件里的旧 Key)。
if apiKey != "" {
return "", ErrInvalid
}
return "", nil
default:
return "", ErrInvalid
}
@@ -406,10 +504,11 @@ func validAPIKey(value string) bool {
func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) {
return weknora.NewClient(weknora.ClientConfig{
BaseURL: baseURL,
APIKey: apiKey,
Timeout: s.options.Timeout,
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
BaseURL: baseURL,
APIKey: apiKey,
Timeout: s.options.Timeout,
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
AllowPrivateHTTP: s.options.AllowPrivateHTTP[env],
})
}
+83 -2
View File
@@ -1,16 +1,22 @@
package kbbinding
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/secretbox"
)
type emptyDB struct{}
@@ -74,7 +80,7 @@ func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) {
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
})
if err != nil || catalog.Status != statusUnauthorized {
if err != nil || catalog.Status != statusKeyInvalid {
t.Fatalf("denied catalog = %#v, %v", catalog, err)
}
@@ -119,7 +125,6 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
for _, input := range []SaveInput{
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb-in"},
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
} {
@@ -128,3 +133,79 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
}
}
}
func TestCatalogDistinguishesInvalidKeyFromForbiddenKey(t *testing.T) {
invalid := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusUnauthorized})
if invalid.Status != "key_invalid" || !strings.Contains(invalid.Message, "密钥无效") {
t.Fatalf("401 -> %+v", invalid)
}
forbidden := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusForbidden})
if forbidden.Status != "key_forbidden" || !strings.Contains(forbidden.Message, "无权限") {
t.Fatalf("403 -> %+v", forbidden)
}
dead := catalogFailure(context.DeadlineExceeded)
if dead.Status != "unreachable" || !(strings.Contains(dead.Message, "超时") || strings.Contains(dead.Message, "不可达")) {
t.Fatalf("timeout -> %+v", dead)
}
if dead.Status == invalid.Status || invalid.Status == forbidden.Status {
t.Fatal("the three outcomes must stay distinguishable")
}
}
func TestClearKeyIsASeparateAction(t *testing.T) {
store := New(emptyDB{}, Options{})
saved := stored{Environment: EnvTest, Revision: 2, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
key, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "", saved, true)
if err != nil || key != "" {
t.Fatalf("clear = %q, %v", key, err)
}
if _, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
t.Fatalf("clear with a typed key = %v, want ErrInvalid", err)
}
}
func TestKeyTailShowsOnlyFourCharacters(t *testing.T) {
path := filepath.Join(t.TempDir(), "master.key")
if err := os.WriteFile(path, bytes.Repeat([]byte{7}, 32), 0o600); err != nil {
t.Fatal(err)
}
box, err := secretbox.Load(path)
if err != nil {
t.Fatalf("secretbox.Load: %v", err)
}
sealed, err := box.Seal([]byte("sk-live-abcd"), keyAAD(EnvTest, 3))
if err != nil {
t.Fatal(err)
}
store := New(emptyDB{}, Options{MasterKeyFile: path})
tail, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 3}, EnvTest)
if !ok || tail != "abcd" {
t.Fatalf("tail = %q %v", tail, ok)
}
// A different revision must not open — the tail must never leak from a
// ciphertext that no longer matches the row.
if _, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 4}, EnvTest); ok {
t.Fatal("tail opened with the wrong revision")
}
}
func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
store := New(emptyDB{}, Options{LegacyBinding: func(context.Context, string) (string, string, error) {
return "legacy-in-0001", "legacy-out-0001", nil
}})
view := View{Environment: EnvTest}
store.fillFallbacks(context.Background(), EnvTest, &view)
if view.InternalFallback != "legacy-in-0001" || view.ExternalFallback != "legacy-out-0001" {
t.Fatalf("test fallbacks = %+v", view)
}
production := View{Environment: EnvProduction}
store.fillFallbacks(context.Background(), EnvProduction, &production)
if production.InternalFallback != "same-id" || production.ExternalFallback != "same-id" {
t.Fatalf("production fallbacks = %+v", production)
}
bound := View{Environment: EnvTest, InternalKBID: "a", ExternalKBID: "b"}
store.fillFallbacks(context.Background(), EnvTest, &bound)
if bound.InternalFallback != "" || bound.ExternalFallback != "" {
t.Fatalf("bound view must not claim a fallback: %+v", bound)
}
}
+33 -23
View File
@@ -15,7 +15,8 @@ import (
const (
statusOK = "ok"
statusEmpty = "empty"
statusUnauthorized = "unauthorized"
statusKeyInvalid = "key_invalid"
statusKeyForbidden = "key_forbidden"
statusUnreachable = "unreachable"
statusUnsupported = "unsupported"
)
@@ -76,8 +77,10 @@ func catalogFailure(err error) Catalog {
var httpErr *weknora.HTTPError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
return Catalog{Status: statusUnauthorized, Message: "密钥被实例拒绝(HTTP 401/403):检查 API Key 与该实例权限"}
case http.StatusUnauthorized:
return Catalog{Status: statusKeyInvalid, Message: "密钥无效:该实例拒绝了这把 API Key(401)"}
case http.StatusForbidden:
return Catalog{Status: statusKeyForbidden, Message: "密钥无权限读取知识库列表(403)"}
case http.StatusNotFound:
return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"}
default:
@@ -106,12 +109,9 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
return View{}, ErrInvalid
}
// 新页面必须给两个方向各选一个库:显式“未绑定”会回落到部署默认 ID,
// 而那个 ID 可能属于旧实例;在换绑实例后继续沿用就是错误目标。
if internal == "" || external == "" {
return View{}, ErrInvalid
}
if internal == external {
// 留空 = 取消该方向绑定:测试侧回退到部署默认库,生产侧回退到「同 ID 语义」,
// 响应里会写明回退到哪(InternalFallback / ExternalFallback)。
if internal != "" && internal == external {
return View{}, ErrInvalid
}
saved, found, err := s.load(ctx, env)
@@ -122,27 +122,37 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
if err != nil {
return View{}, err
}
client, err := s.client(baseURL, key, env)
if err != nil {
return View{}, ErrInvalid
}
selected, err := s.verifySelection(ctx, client, internal, external)
if err != nil {
return View{}, err
selected := map[string]selectedBase{}
cleared := key == "" && input.KeyAction == "clear"
if !cleared {
client, clientErr := s.client(baseURL, key, env)
if clientErr != nil {
return View{}, ErrInvalid
}
selected, err = s.verifySelection(ctx, client, internal, external)
if err != nil {
return View{}, err
}
}
revision := saved.Revision + 1
if !found {
revision = 1
}
box := s.loadBox()
if box == nil {
return View{}, ErrStorage
}
sealed, err := box.Seal([]byte(key), keyAAD(env, revision))
if err != nil {
return View{}, ErrStorage
sealed := []byte{}
if !cleared {
box := s.loadBox()
if box == nil {
return View{}, ErrStorage
}
sealed, err = box.Seal([]byte(key), keyAAD(env, revision))
if err != nil {
return View{}, ErrStorage
}
}
verification := "verified"
if cleared {
verification = "not_configured"
}
tx, err := s.db.Begin(ctx)
if err != nil {
+6 -1
View File
@@ -13,6 +13,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
// P10: every configured dependency reports Liveness ("process reachable") and
@@ -200,10 +201,14 @@ func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now ti
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
parsed, err := url.Parse(baseURL)
outcome := ProbeOutcome{ObservedAt: now}
if err != nil || parsed.Scheme != "http" && parsed.Scheme != "https" || parsed.Host == "" {
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
outcome.Reachability = errors.New("探测配置无效")
return outcome
}
if !weknora.HTTPAllowed(baseURL, weknora.HTTPPolicy{AllowPrivateHTTP: provider.allowPrivateHTTP}) {
outcome.Reachability = errors.New("探测配置无效:该地址不被允许(https 或已放行的私网/回环 http)")
return outcome
}
parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/health"
parsed.RawQuery, parsed.Fragment = "", ""
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
+6 -1
View File
@@ -50,6 +50,10 @@ type RealProviderConfig struct {
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
// as alive (P10).
WorkerStaleAfter time.Duration
// AllowPrivateHTTP lets the console probe a same-LAN http endpoint — the
// same judgement the WeKnora client uses, so a card can never say 「可达」
// while the client refuses that URL.
AllowPrivateHTTP bool
}
type RealProvider struct {
@@ -63,6 +67,7 @@ type RealProvider struct {
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) (string, error)
workerStaleAfter time.Duration
allowPrivateHTTP bool
health *healthTracker
}
@@ -103,7 +108,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), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, 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, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
}
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
+48 -1
View File
@@ -48,6 +48,53 @@ type ClientConfig struct {
Timeout time.Duration
MaxResponseBytes int64
AllowDockerHTTP bool
// AllowPrivateHTTP relaxes the plain-http rule for RFC1918 / link-local
// literals, because the production instance is only reachable as a same-LAN
// http reverse proxy. Public http hosts stay refused.
AllowPrivateHTTP bool
}
// HTTPPolicy is the single reachability judgement shared by the WeKnora client,
// the console probes and the binding page: two callers must never disagree
// about whether a configured endpoint is acceptable.
type HTTPPolicy struct {
AllowPrivateHTTP bool
AllowDockerHTTP bool
}
// HTTPAllowed reports whether baseURL may be called at all. https is always
// allowed; http only for loopback, an opted-in private address, or a
// single-label docker host.
func HTTPAllowed(rawURL string, policy HTTPPolicy) bool {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || parsed.Host == "" || parsed.User != nil {
return false
}
switch parsed.Scheme {
case "https":
return true
case "http":
host := parsed.Hostname()
if isLoopbackHost(host) {
return true
}
if policy.AllowPrivateHTTP && isPrivateHost(host) {
return true
}
return policy.AllowDockerHTTP && isSingleLabelDockerHost(host)
}
return false
}
// isPrivateHost reports the addresses a same-LAN deployment legitimately uses:
// RFC1918, link-local and IPv6 ULA. A public name is never private, so opting
// in cannot widen the client to the internet.
func isPrivateHost(host string) bool {
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
}
type Client struct {
@@ -65,7 +112,7 @@ func NewClient(config ClientConfig) (*Client, error) {
if baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {
return nil, errors.New("invalid WeKnora base URL")
}
if baseURL.Scheme != "https" && !(baseURL.Scheme == "http" && (isLoopbackHost(baseURL.Hostname()) || (config.AllowDockerHTTP && isSingleLabelDockerHost(baseURL.Hostname())))) {
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
return nil, errors.New("WeKnora base URL must use HTTPS")
}
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
+8 -4
View File
@@ -87,6 +87,9 @@ type Prober struct {
Resolve func(context.Context) (Target, error)
Timeout time.Duration
AllowDockerHTTP bool
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses, the
// same judgement the binding store and the client use.
AllowPrivateHTTP bool
}
func (prober Prober) Check(ctx context.Context) Result {
@@ -106,10 +109,11 @@ func (prober Prober) Check(ctx context.Context) Result {
timeout = 10 * time.Second
}
client, err := weknora.NewClient(weknora.ClientConfig{
BaseURL: target.BaseURL,
APIKey: target.APIKey,
Timeout: timeout,
AllowDockerHTTP: prober.AllowDockerHTTP,
BaseURL: target.BaseURL,
APIKey: target.APIKey,
Timeout: timeout,
AllowDockerHTTP: prober.AllowDockerHTTP,
AllowPrivateHTTP: prober.AllowPrivateHTTP,
})
if err != nil {
return Result{Target: described, Err: err}
+39 -4
View File
@@ -24,6 +24,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
key_tail: '9f2c',
internal_fallback: '',
external_fallback: '',
frozen: 0,
retargetable: 0,
})
const snapshot = {
@@ -181,7 +186,7 @@ describe('KnowledgeBaseBinding', () => {
expect(body.api_key).toBeUndefined()
})
it('does not allow saving until both directions have an explicit base', async () => {
it('allows clearing one direction and says where the empty side falls back', async () => {
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
@@ -195,10 +200,40 @@ describe('KnowledgeBaseBinding', () => {
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', '')
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true)
expect(host.textContent).toContain('未选择不会回落到旧实例的默认库')
await choose('对外知识库', 'kb-new-out-0001')
// 留空 = 取消绑定:允许保存,但必须说清回退到哪里。
expect(save?.hasAttribute('disabled')).toBe(false)
expect(host.textContent).toContain('留空 = 取消该方向绑定')
await choose('对外知识库', 'kb-new-in-0001')
// 两边同一个库仍然不允许保存。
expect(save?.hasAttribute('disabled')).toBe(true)
})
it('clears the key through the dedicated action, not by saving a blank draft', async () => {
const put = vi
.fn()
.mockResolvedValue(
json({ data: { ...binding('test'), key_configured: false, key_tail: '', verification: 'not_configured' } })
)
vi.stubGlobal(
'fetch',
vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return put(url, init)
return Promise.resolve(json({ data: binding('test') }))
})
)
vi.stubGlobal('confirm', () => true)
await render()
const clear = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('清除密钥'))
expect(clear).toBeTruthy()
await act(async () => {
clear!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(put).toHaveBeenCalled()
const body = JSON.parse(String((put.mock.calls[0][1] as { body: string }).body))
expect(body.key_action).toBe('clear')
expect(body.api_key).toBeUndefined()
})
it('gives viewers a read-only summary with no editing inputs', async () => {
+71 -8
View File
@@ -70,6 +70,15 @@ const sameDraft = (draft: Draft, saved: KBEnvironmentBinding): boolean =>
draft.internalID === saved.internal_kb_id &&
draft.externalID === saved.external_kb_id
// 留空不是「什么都没发生」:它意味着回退到部署默认库(测试侧)或同 ID 语义
// (生产侧),页面必须把这一点说出来。
const fallbackLabel = (fallback: string): string =>
!fallback
? '部署默认(未设置)'
: fallback === 'same-id'
? '同 ID 语义'
: `部署默认库 ${shortKnowledgeBaseID(fallback)}`
const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
@@ -148,8 +157,6 @@ export function KnowledgeBaseBinding() {
storageReady &&
endpointValid &&
keyReady &&
draft.internalID !== '' &&
draft.externalID !== '' &&
!duplicate &&
catalogReady
)
@@ -266,13 +273,20 @@ export function KnowledgeBaseBinding() {
view.replanned || view.retired_duplicates
? `;同时把 ${view.replanned} 项未上传的待入库重新指向新库${view.retired_duplicates ? `,${view.retired_duplicates} 项因新库已有同篇而退休` : ''}`
: ''
const fallbacks: string[] = []
if (!view.internal_kb_id) fallbacks.push(`对内回退到${fallbackLabel(view.internal_fallback)}`)
if (!view.external_kb_id) fallbacks.push(`对外回退到${fallbackLabel(view.external_fallback)}`)
const frozen =
view.frozen + view.retargetable > 0
? `;已冻结目标 ${view.frozen} 条(不会被改写),仍可改指向 ${view.retargetable} 条`
: ''
setNotices((current) => ({
...current,
[targetEnv]: {
tone: 'ok',
text: `已保存${environments.find((item) => item.key === targetEnv)?.short}绑定:对内 ${
view.internal_kb_name || shortKnowledgeBaseID(view.internal_kb_id) || '未绑定'
} · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${replan}`,
} · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${fallbacks.length ? `;${fallbacks.join(';')}` : ''}${replan}${frozen}`,
},
}))
} catch (cause) {
@@ -299,6 +313,44 @@ export function KnowledgeBaseBinding() {
}
}
// 清除密钥是独立动作:不换地址、不动绑定,只是这一侧不再有可用凭据。
const runClearKey = async () => {
if (!saved || !isAdmin || busyNow !== '') return
if (!window.confirm('清除后该侧不再有可用密钥:列库与发布会失败,也不会回落到服务器文件里的旧 Key。确定清除?'))
return
const targetEnv = env
const seq = ++saveSeq.current
setBusy((current) => ({ ...current, [targetEnv]: 'saving' }))
setNotices((current) => ({ ...current, [targetEnv]: null }))
try {
const view = await saveKBBinding(targetEnv, {
base_revision: saved.revision,
base_url: saved.base_url,
key_action: 'clear',
internal_kb_id: saved.internal_kb_id,
external_kb_id: saved.external_kb_id,
})
if (seq !== saveSeq.current) return
setSnapshot((current) => (current ? { ...current, [targetEnv]: view } : current))
setDrafts((current) => (current ? { ...current, [targetEnv]: draftFrom(view) } : current))
setNotices((current) => ({
...current,
[targetEnv]: {
tone: 'ok',
text: `已清除${environments.find((item) => item.key === targetEnv)?.short}连接的 API Key;地址与内外库绑定保留。`,
},
}))
} catch (cause) {
if (seq !== saveSeq.current) return
setNotices((current) => ({
...current,
[targetEnv]: { tone: 'error', text: cause instanceof Error ? cause.message : '清除密钥失败' },
}))
} finally {
setBusy((current) => ({ ...current, [targetEnv]: '' }))
}
}
const currentOptions = useMemo<{ internal: KBCatalogOption[]; external: KBCatalogOption[] }>(() => {
const base = draft?.catalog?.options ?? []
const withSelection = (id: string, name: string): KBCatalogOption[] => {
@@ -327,7 +379,9 @@ export function KnowledgeBaseBinding() {
{binding.key_configured
? binding.key_source === 'file'
? 'API Key 来自服务器文件'
: 'API Key 已配置(不回显)'
: binding.key_tail
? `API Key 已配置 · 尾${binding.key_tail}`
: 'API Key 已配置(不回读)'
: 'API Key 未配置'}
{binding.source === 'legacy' ? ' · 旧部署配置' : ` · 版本 ${binding.revision}`}
</small>
@@ -479,6 +533,11 @@ export function KnowledgeBaseBinding() {
{busyNow === 'catalog' ? '正在验证并读取…' : '验证并读取知识库'}
</button>
<small>服务器会用这份地址与密钥真实列库,只读,不写入。</small>
{saved?.key_configured ? (
<button type="button" className="danger" onClick={() => void runClearKey()} disabled={busyNow !== ''}>
清除密钥
</button>
) : null}
</div>
{draft.catalog ? (
<div className={`kb-catalog-status ${statusTone(draft.catalog.status)}`} role="status">
@@ -522,7 +581,9 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">请选择知识库</option>
<option value="">
未绑定({env === 'production' ? '生产侧回退到同 ID 语义' : '测试侧回退到部署默认库'})
</option>
{currentOptions.internal.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
@@ -540,7 +601,9 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">请选择知识库</option>
<option value="">
未绑定({env === 'production' ? '生产侧回退到同 ID 语义' : '测试侧回退到部署默认库'})
</option>
{currentOptions.external.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
@@ -550,8 +613,8 @@ export function KnowledgeBaseBinding() {
</label>
</div>
<small>
名称相同很常见,括号里的短 ID
才是区分依据;对内与对外都必须选择且不能是同一个库。未选择不会回落到旧实例的默认库。
名称相同很常见,括号里的短 ID 才是区分依据;对内与对外不能是同一个库。 留空 = 取消该方向绑定:
{env === 'production' ? '生产侧回退到「同 ID 语义」' : '测试侧回退到部署默认库'}。
</small>
{duplicate ? <p className="error-message">对内和对外不能绑定同一个知识库。</p> : null}
</section>
+5
View File
@@ -26,6 +26,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
key_tail: '9f2c',
internal_fallback: '',
external_fallback: '',
frozen: 0,
retargetable: 0,
})
describe('knowledgeBaseBindings', () => {
+17 -4
View File
@@ -8,6 +8,8 @@ export interface KBEnvironmentBinding {
base_url: string
key_configured: boolean
key_source: string
/** 只用于展示的密钥尾 4 位;服务端不存、不回读明文。 */
key_tail: string
internal_kb_id: string
internal_kb_name: string
external_kb_id: string
@@ -20,6 +22,12 @@ export interface KBEnvironmentBinding {
storage_ready: boolean
replanned: number
retired_duplicates: number
/** 该方向留空时回退到哪:测试侧是部署默认库 ID,生产侧是 same-id。 */
internal_fallback: string
external_fallback: string
/** 生产侧:执行已开始的发布目标已冻结,保存绑定不会改写。 */
frozen: number
retargetable: number
}
export interface KBBindingSnapshot {
@@ -34,7 +42,7 @@ export interface KBCatalogOption {
knowledge_count: number
}
export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported'
export type KBCatalogStatus = 'ok' | 'empty' | 'key_invalid' | 'key_forbidden' | 'unreachable' | 'unsupported'
export interface KBCatalog {
status: KBCatalogStatus
@@ -48,7 +56,7 @@ export interface KBCatalog {
export interface KBCatalogInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
key_action: 'keep' | 'replace' | 'clear'
api_key?: string
page: number
page_size: number
@@ -57,7 +65,7 @@ export interface KBCatalogInput {
export interface KBBindingSaveInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
key_action: 'keep' | 'replace' | 'clear'
api_key?: string
internal_kb_id: string
external_kb_id: string
@@ -90,6 +98,7 @@ function parseBinding(value: unknown): KBEnvironmentBinding {
base_url: text(value.base_url),
key_configured: bool(value.key_configured),
key_source: text(value.key_source),
key_tail: text(value.key_tail),
internal_kb_id: text(value.internal_kb_id),
internal_kb_name: text(value.internal_kb_name),
external_kb_id: text(value.external_kb_id),
@@ -102,6 +111,10 @@ function parseBinding(value: unknown): KBEnvironmentBinding {
storage_ready: bool(value.storage_ready),
replanned: count(value.replanned),
retired_duplicates: count(value.retired_duplicates),
internal_fallback: text(value.internal_fallback),
external_fallback: text(value.external_fallback),
frozen: count(value.frozen),
retargetable: count(value.retargetable),
}
}
@@ -181,7 +194,7 @@ export async function fetchKBCatalog(
if (!record(payload.data)) throw new Error('知识库列表响应无效')
const item = payload.data
const status = text(item.status)
if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) {
if (!['ok', 'empty', 'key_invalid', 'key_forbidden', 'unreachable', 'unsupported'].includes(status)) {
throw new Error('知识库列表响应无效')
}
const options = Array.isArray(item.options)