feat(settings): 知识库绑定按环境一次保存连接与内外库
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥, 也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址 与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与 绑定,回读真实生效值。 服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件 凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥 不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储 解析当前连接,避免只保存了页面数据。 验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错; make verify 在本提交上执行(结果见交付说明)。
This commit is contained in:
@@ -141,6 +141,11 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 「知识库绑定」saves a connection (address + key) and both bindings for one
|
||||
// environment in one write: same authority as the annotation binding.
|
||||
if strings.HasPrefix(path, "/api/v1/kb-bindings") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Choosing the production base a release writes into is a production
|
||||
// authority change, exactly like the annotation binding above.
|
||||
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
// KBBindingStore is the environment-scoped 「知识库绑定」capability. Save does
|
||||
// the real candidate read itself, so the HTTP layer decides no policy beyond
|
||||
// status/role.
|
||||
type KBBindingStore interface {
|
||||
List(context.Context) ([]kbbinding.View, error)
|
||||
Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error)
|
||||
Save(context.Context, string, kbbinding.SaveInput, string, time.Time) (kbbinding.View, error)
|
||||
ResolveBaseURL(context.Context, string) string
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
views, err := config.KBBindings.List(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load knowledge base bindings"})
|
||||
return
|
||||
}
|
||||
storageReady := false
|
||||
for _, view := range views {
|
||||
storageReady = storageReady || view.StorageReady
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.CatalogInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": catalog})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.SaveInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view, "operation": "saved"})
|
||||
}
|
||||
|
||||
func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, kbbinding.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "绑定参数不合法:请检查地址、密钥与内外库选择"})
|
||||
case errors.Is(err, kbbinding.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "该环境的绑定已被其他保存更新;草稿未写入,旧绑定保持不变,请重新读取后再试"})
|
||||
case errors.Is(err, kbbinding.ErrKeyForwarding):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址"})
|
||||
case errors.Is(err, kbbinding.ErrNotConfigured):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "这个地址还没有可用 API Key:请输入密钥或先选择已配置的连接"})
|
||||
case errors.Is(err, kbbinding.ErrStorage):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "独立安全存储未就绪(WEKNORA_BINDING_MASTER_KEY_FILE);未写入任何绑定"})
|
||||
case errors.Is(err, kbbinding.ErrRejected):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrRejected.Error()+":")})
|
||||
case errors.Is(err, kbbinding.ErrUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrUnreachable.Error()+":")})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
type fakeKBBindings struct {
|
||||
views []kbbinding.View
|
||||
catalog kbbinding.Catalog
|
||||
saveErr error
|
||||
catalogErr error
|
||||
lastSave kbbinding.SaveInput
|
||||
lastActor string
|
||||
}
|
||||
|
||||
func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) {
|
||||
return fake.views, nil
|
||||
}
|
||||
func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) {
|
||||
return fake.catalog, fake.catalogErr
|
||||
}
|
||||
func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) {
|
||||
fake.lastSave = input
|
||||
fake.lastActor = actor
|
||||
if fake.saveErr != nil {
|
||||
return kbbinding.View{}, fake.saveErr
|
||||
}
|
||||
return fake.views[0], nil
|
||||
}
|
||||
func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" }
|
||||
|
||||
func kbBindingHandler(t *testing.T, store KBBindingStore) *Config {
|
||||
t.Helper()
|
||||
config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }}
|
||||
return config
|
||||
}
|
||||
|
||||
func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{
|
||||
Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example",
|
||||
KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部",
|
||||
ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true,
|
||||
}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} {
|
||||
if strings.Contains(body, forbidden) {
|
||||
t.Fatalf("read response exposes %q: %s", forbidden, body)
|
||||
}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("save without intent status = %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
||||
store := &fakeKBBindings{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}},
|
||||
saveErr: kbbinding.ErrConflict,
|
||||
}
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") {
|
||||
t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
|
||||
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
|
||||
config := kbBindingHandler(t, store)
|
||||
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
||||
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") {
|
||||
t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "typed-key") {
|
||||
t.Fatal("catalog response echoed the typed key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} {
|
||||
if role := classifyRole(http.MethodPut, path); role != roleAdmin {
|
||||
t.Fatalf("PUT %s role = %s, want admin", path, role)
|
||||
}
|
||||
if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer {
|
||||
t.Fatalf("GET bindings role = %s, want viewer", role)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
switch value := node.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range value {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" && path != "components.schemas.KBBindingEnvironmentView.properties" && path != "components.schemas.KBCatalogInput.properties" && path != "components.schemas.KBBindingSaveInput.properties" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/pgdsn"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
@@ -88,6 +89,11 @@ func (config Config) libraryPublishTarget() libraryPublishTargetView {
|
||||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||||
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
|
||||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||||
if config.KBBindings != nil {
|
||||
if resolved := strings.TrimSpace(config.KBBindings.ResolveBaseURL(ctx, kbbinding.EnvProduction)); resolved != "" {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||||
return resolved
|
||||
|
||||
@@ -2,11 +2,9 @@ package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
)
|
||||
|
||||
func qaAIError(w http.ResponseWriter, err error) {
|
||||
@@ -42,24 +40,7 @@ func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
|
||||
return true
|
||||
}
|
||||
func qaAISecretTransport(r *http.Request, c Config) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsed, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsed
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
if c.QAAITrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
return secretTransportAllowed(r, c.QAAITrustTLSProxy)
|
||||
}
|
||||
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// secretTransportAllowed is the single rule for typing a secret into the
|
||||
// console: a real TLS connection, a loopback request, or a same-origin HTTPS
|
||||
// request that a trusted reverse proxy forwarded. The browser's origin scheme
|
||||
// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit
|
||||
// a key even if it spoofs X-Forwarded-Proto.
|
||||
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsedHost
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -137,6 +137,10 @@ type Config struct {
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
// KBBindings is the environment-scoped 「知识库绑定」store: connection +
|
||||
// internal/external bindings saved together. Nil keeps the page read-only
|
||||
// and reports unavailable, never a fake success.
|
||||
KBBindings KBBindingStore
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
|
||||
@@ -404,6 +408,15 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleSaveRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/kb-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/kb-bindings/{environment}/catalog", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingCatalog(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/kb-bindings/{environment}", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingSave(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
|
||||
Reference in New Issue
Block a user