feat(settings): 知识库绑定按环境一次保存连接与内外库
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥, 也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址 与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与 绑定,回读真实生效值。 服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件 凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥 不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储 解析当前连接,避免只保存了页面数据。 验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错; make verify 在本提交上执行(结果见交付说明)。
This commit is contained in:
@@ -47,16 +47,19 @@ type Config struct {
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
TestWeKnoraAPIKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
|
||||
TestAutoReviewPolicy string
|
||||
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
|
||||
@@ -203,6 +206,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
@@ -344,6 +348,9 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
// Package kbbinding 是「知识库绑定」的唯一服务端入口:按环境保存连接
|
||||
// (地址 + 加密后的 API Key)和对内/对外知识库绑定,并提供候选人列库、
|
||||
// 选库归属校验与消费者解析。旧的部署文件凭据/默认绑定在没有任何新行时
|
||||
// 继续生效,所以升级不需要回填数据。
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvTest = "test"
|
||||
EnvProduction = "production"
|
||||
)
|
||||
|
||||
func Environments() []string { return []string{EnvTest, EnvProduction} }
|
||||
|
||||
func ValidEnvironment(value string) bool {
|
||||
return value == EnvTest || value == EnvProduction
|
||||
}
|
||||
|
||||
func EnvironmentLabel(value string) string {
|
||||
if value == EnvProduction {
|
||||
return "生产 090"
|
||||
}
|
||||
return "测试 090"
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid knowledge base binding")
|
||||
ErrConflict = errors.New("knowledge base binding revision conflict")
|
||||
ErrKeyForwarding = errors.New("old key must not follow a new address")
|
||||
ErrNotConfigured = errors.New("weknora connection is not configured")
|
||||
ErrStorage = errors.New("secure binding storage is not ready")
|
||||
ErrRejected = errors.New("weknora rejected the candidate connection")
|
||||
ErrUnreachable = errors.New("weknora candidate connection is unreachable")
|
||||
)
|
||||
|
||||
// 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"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
Verification string `json:"verification"`
|
||||
CheckedAt *time.Time `json:"checked_at"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
// Source says where this effective configuration comes from: a row saved on
|
||||
// this page, or the pre-existing deployment file/default binding.
|
||||
Source string `json:"source"`
|
||||
StorageReady bool `json:"storage_ready"`
|
||||
// Replanned / RetiredDuplicates only report what a save just did to 待入库
|
||||
// rows that had never been uploaded; a plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
}
|
||||
|
||||
type Catalog struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
Options []Option `json:"options"`
|
||||
}
|
||||
|
||||
type CatalogInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type SaveInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
}
|
||||
|
||||
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
||||
// reach the effective instance. It never leaves the server.
|
||||
type Target struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Revision int64
|
||||
Source string
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
MasterKeyFile string
|
||||
Timeout time.Duration
|
||||
// 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
|
||||
// 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
|
||||
// LegacyKey reads the deployment credential file. It is only consulted when
|
||||
// no row exists, or when a keep action targets exactly that legacy address.
|
||||
LegacyKey func(string) (string, error)
|
||||
// LegacyBinding resolves the pre-existing internal/external binding ids.
|
||||
LegacyBinding func(context.Context, string) (string, string, error)
|
||||
// RoutingDefaults are the deployment bootstrap ids used to replan pending
|
||||
// publications when a saved side is empty.
|
||||
RoutingDefaults func() (string, string)
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type DB interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db DB
|
||||
options Options
|
||||
}
|
||||
|
||||
func New(db DB, options Options) *Store {
|
||||
if options.Timeout <= 0 {
|
||||
options.Timeout = 10 * time.Second
|
||||
}
|
||||
if options.Now == nil {
|
||||
options.Now = time.Now
|
||||
}
|
||||
return &Store{db: db, options: options}
|
||||
}
|
||||
|
||||
type stored struct {
|
||||
Environment string
|
||||
Revision int64
|
||||
BaseURL string
|
||||
KeyCiphertext []byte
|
||||
InternalKBID string
|
||||
ExternalKBID string
|
||||
InternalKBName string
|
||||
ExternalKBName string
|
||||
Verification string
|
||||
CheckedAt *time.Time
|
||||
UpdatedBy string
|
||||
UpdatedAt *time.Time
|
||||
}
|
||||
|
||||
const bindingColumns = `environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at`
|
||||
|
||||
func scanStored(row pgx.Row) (stored, bool, error) {
|
||||
var value stored
|
||||
err := row.Scan(&value.Environment, &value.Revision, &value.BaseURL, &value.KeyCiphertext,
|
||||
&value.InternalKBID, &value.ExternalKBID, &value.InternalKBName, &value.ExternalKBName,
|
||||
&value.Verification, &value.CheckedAt, &value.UpdatedBy, &value.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return stored{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return stored{}, false, err
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) load(ctx context.Context, env string) (stored, bool, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return stored{}, false, ErrInvalid
|
||||
}
|
||||
return scanStored(s.db.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1`, env))
|
||||
}
|
||||
|
||||
func (s *Store) StorageReady() bool {
|
||||
return s.loadBox() != nil
|
||||
}
|
||||
|
||||
func (s *Store) loadBox() *secretbox.Box {
|
||||
box, err := secretbox.Load(s.options.MasterKeyFile)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return box
|
||||
}
|
||||
|
||||
func (s *Store) legacyBaseURL(ctx context.Context, env string) string {
|
||||
if s.options.LegacyBaseURL == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(s.options.LegacyBaseURL(ctx, env))
|
||||
}
|
||||
|
||||
func (s *Store) legacyKey(env string) (string, error) {
|
||||
if s.options.LegacyKey == nil {
|
||||
return "", nil
|
||||
}
|
||||
value, err := s.options.LegacyKey(env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
|
||||
// List returns both environments' effective views for the page header and the
|
||||
// environment switch. Names are best-effort: an unreachable instance yields
|
||||
// short ids instead of hiding the binding.
|
||||
func (s *Store) List(ctx context.Context) ([]View, error) {
|
||||
views := make([]View, 0, 2)
|
||||
for _, env := range Environments() {
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view := View{Environment: env, StorageReady: s.StorageReady(), Source: "legacy"}
|
||||
if found {
|
||||
view.Revision = saved.Revision
|
||||
view.BaseURL = saved.BaseURL
|
||||
view.KeyConfigured = len(saved.KeyCiphertext) > 0
|
||||
view.KeySource = keySource(view.KeyConfigured)
|
||||
view.InternalKBID = saved.InternalKBID
|
||||
view.InternalKBName = saved.InternalKBName
|
||||
view.ExternalKBID = saved.ExternalKBID
|
||||
view.ExternalKBName = saved.ExternalKBName
|
||||
view.Verification = saved.Verification
|
||||
view.CheckedAt = saved.CheckedAt
|
||||
view.UpdatedBy = saved.UpdatedBy
|
||||
view.UpdatedAt = saved.UpdatedAt
|
||||
view.Source = "web"
|
||||
return view, nil
|
||||
}
|
||||
// Legacy fallback: exactly what the consumers use before any page save.
|
||||
view.BaseURL = s.legacyBaseURL(ctx, env)
|
||||
if key, keyErr := s.legacyKey(env); keyErr == nil && key != "" {
|
||||
view.KeyConfigured = true
|
||||
view.KeySource = "file"
|
||||
}
|
||||
if s.options.LegacyBinding != nil {
|
||||
internal, external, bindErr := s.options.LegacyBinding(ctx, env)
|
||||
if bindErr != nil {
|
||||
return View{}, bindErr
|
||||
}
|
||||
view.InternalKBID = internal
|
||||
view.ExternalKBID = external
|
||||
}
|
||||
view.Verification = "legacy"
|
||||
s.fillNames(ctx, &view)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func keySource(configured bool) string {
|
||||
if configured {
|
||||
return "sealed"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// fillNames reads names from the effective instance for the legacy view. A
|
||||
// failure leaves names empty; ids still identify the binding.
|
||||
func (s *Store) fillNames(ctx context.Context, view *View) {
|
||||
if view.BaseURL == "" || (view.InternalKBID == "" && view.ExternalKBID == "") {
|
||||
return
|
||||
}
|
||||
// 只是把 ID 换成名字:不能让一次不可达的旧实例拖住整个页面读取。
|
||||
namesCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
key, err := s.legacyKey(view.Environment)
|
||||
if err != nil || key == "" {
|
||||
return
|
||||
}
|
||||
client, err := s.client(view.BaseURL, key, view.Environment)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
names := map[string]string{}
|
||||
page := 1
|
||||
for page <= 20 {
|
||||
result, err := client.ListKnowledgeBasesPage(namesCtx, page, 100)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, base := range result.Items {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
if result.Total <= int64(page*100) || len(result.Items) < 100 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
view.InternalKBName = names[view.InternalKBID]
|
||||
view.ExternalKBName = names[view.ExternalKBID]
|
||||
}
|
||||
|
||||
// Resolve returns the effective connection consumers must use. A saved row is
|
||||
// authoritative: if its key cannot be opened we fail closed instead of falling
|
||||
// back to the file credential (that would send the old key to a new address).
|
||||
func (s *Store) Resolve(ctx context.Context, env string) (Target, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
return Target{BaseURL: saved.BaseURL, APIKey: string(raw), Revision: saved.Revision, Source: "web"}, nil
|
||||
}
|
||||
baseURL := s.legacyBaseURL(ctx, env)
|
||||
key, err := s.legacyKey(env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if baseURL == "" || key == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
return Target{BaseURL: baseURL, APIKey: key, Source: "legacy"}, nil
|
||||
}
|
||||
|
||||
// ResolveBaseURL is for health probes that only need the endpoint (no key).
|
||||
func (s *Store) ResolveBaseURL(ctx context.Context, env string) string {
|
||||
if saved, found, err := s.load(ctx, env); err == nil && found && saved.BaseURL != "" {
|
||||
return saved.BaseURL
|
||||
}
|
||||
return s.legacyBaseURL(ctx, env)
|
||||
}
|
||||
|
||||
func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey string, saved stored, found bool) (string, error) {
|
||||
switch action {
|
||||
case "keep":
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return "", ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
// First save on an upgraded deployment: keeping the deployment file key
|
||||
// is allowed only for exactly that legacy address.
|
||||
if s.legacyBaseURL(ctx, env) != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
return s.legacyKey(env)
|
||||
case "replace":
|
||||
if !validAPIKey(apiKey) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return apiKey, nil
|
||||
default:
|
||||
return "", ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func validAPIKey(value string) bool {
|
||||
return value != "" && len(value) <= 4096 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\r\n\x00")
|
||||
}
|
||||
|
||||
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],
|
||||
})
|
||||
}
|
||||
|
||||
func keyAAD(env string, revision int64) string {
|
||||
return "weknora-binding:" + env + ":" + strconv.FormatInt(revision, 10)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type emptyDB struct{}
|
||||
|
||||
func (emptyDB) QueryRow(context.Context, string, ...any) pgx.Row { return emptyRow{} }
|
||||
func (emptyDB) Begin(context.Context) (pgx.Tx, error) {
|
||||
return nil, errors.New("no transaction in unit test")
|
||||
}
|
||||
|
||||
type emptyRow struct{}
|
||||
|
||||
func (emptyRow) Scan(...any) error { return pgx.ErrNoRows }
|
||||
|
||||
// fakeWeKnora serves the two reads the candidate validation makes: one page of
|
||||
// knowledge bases and a single base by id.
|
||||
func fakeWeKnora(t *testing.T, wantKey string, bases []struct{ id, name string }, total int64) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("X-API-Key"); got != wantKey {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/knowledge-bases" {
|
||||
items := make([]string, 0, len(bases))
|
||||
for _, base := range bases {
|
||||
items = append(items, `{"id":"`+base.id+`","name":"`+base.name+`","knowledge_count":2}`)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[` + strings.Join(items, ",") + `],"total":` + strconv.FormatInt(total, 10) + `}`))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/") {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/")
|
||||
for _, base := range bases {
|
||||
if base.id == id {
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + base.id + `","name":"` + base.name + `"}}`))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
|
||||
empty := fakeWeKnora(t, "key-1", nil, 0)
|
||||
catalog, err := store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: empty.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusEmpty || catalog.Total != 0 {
|
||||
t.Fatalf("empty catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
denied := fakeWeKnora(t, "another-key", nil, 0)
|
||||
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 {
|
||||
t.Fatalf("denied catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
down := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
downURL := down.URL
|
||||
down.Close()
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: downURL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusUnreachable {
|
||||
t.Fatalf("unreachable catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogPaginatesAndReturnsNamesWithShortIDsAreStable(t *testing.T) {
|
||||
server := fakeWeKnora(t, "key-1", []struct{ id, name string }{{"kb-1", "技术资料"}}, 1)
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
catalog, err := store.Catalog(context.Background(), EnvTest, CatalogInput{
|
||||
BaseURL: server.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusOK || len(catalog.Options) != 1 || catalog.Options[0].Name != "技术资料" {
|
||||
t.Fatalf("catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyActionRulesRejectForwardingAndInvalidInput(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 1, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://new.example", "", saved, true); !errors.Is(err, ErrKeyForwarding) {
|
||||
t.Fatalf("keep with a new address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("keep with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "replace", "https://new.example", " ", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("replace with blank key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
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/1"},
|
||||
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
|
||||
} {
|
||||
if _, err := store.Save(context.Background(), EnvTest, input, "admin", now); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("input %#v error = %v, want ErrInvalid", input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package kbbinding_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/postgres/pgtest"
|
||||
)
|
||||
|
||||
// testSecret() 在运行时拼出测试夹具密钥,避免把任何字面量误当成真实凭据入库。
|
||||
func testSecret() string { return "fixture-" + strings.Repeat("k", 24) }
|
||||
|
||||
func fakeCandidate(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != testSecret() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/knowledge-bases":
|
||||
_, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func masterKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "binding-master.key")
|
||||
if err := os.WriteFile(path, []byte(strings.Repeat("k", 32)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing.T) {
|
||||
databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
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)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
||||
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
||||
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope');
|
||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||
('version-kbb','item-kbb','locator:r1',NULL,'unknown');
|
||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||
('pub-kbb','version-kbb','kb-old','planned','pending','internal');
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := fakeCandidate(t)
|
||||
store := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: masterKey(t),
|
||||
Timeout: 2 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
||||
RoutingDefaults: func() (string, string) { return "env-in", "env-out" },
|
||||
})
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
if view.Revision != 1 || !view.KeyConfigured || view.InternalKBName != "内部技术资料" || view.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("view = %#v", view)
|
||||
}
|
||||
if view.Replanned != 1 {
|
||||
t.Fatalf("replanned = %d, want 1", view.Replanned)
|
||||
}
|
||||
target, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || target.BaseURL != server.URL || target.APIKey != testSecret() || target.Revision != 1 {
|
||||
t.Fatalf("Resolve() = %#v, %v", target, err)
|
||||
}
|
||||
var routingInternal, routingExternal string
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal, &routingExternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" || routingExternal != "kb-out" {
|
||||
t.Fatalf("routing binding = %s/%s", routingInternal, routingExternal)
|
||||
}
|
||||
var pendingKB string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&pendingKB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pendingKB != "kb-in" {
|
||||
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
||||
}
|
||||
|
||||
// A stale revision must not overwrite the saved connection or re-point work.
|
||||
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "keep",
|
||||
InternalKBID: "kb-out", ExternalKBID: "kb-in",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if !errors.Is(err, kbbinding.ErrConflict) {
|
||||
t.Fatalf("stale save error = %v, want ErrConflict", err)
|
||||
}
|
||||
unchanged, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || unchanged.APIKey != testSecret() {
|
||||
t.Fatalf("connection changed after conflict: %#v, %v", unchanged, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" {
|
||||
t.Fatalf("routing binding changed after conflict: %s", routingInternal)
|
||||
}
|
||||
|
||||
// A base from another instance (404 here) must be refused and leave no row
|
||||
// for a different environment.
|
||||
if _, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "not-there", ExternalKBID: "kb-out",
|
||||
}, "admin", now); !errors.Is(err, kbbinding.ErrRejected) {
|
||||
t.Fatalf("unknown base error = %v, want ErrRejected", err)
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM weknora_environment_bindings WHERE environment='production'`).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("failed production save wrote %d rows", count)
|
||||
}
|
||||
|
||||
// The old key must never be forwarded: keep is only legal for the saved URL.
|
||||
if _, err := store.Catalog(ctx, kbbinding.EnvTest, kbbinding.CatalogInput{
|
||||
BaseURL: "https://another.example", KeyAction: "keep", Page: 1, PageSize: 20,
|
||||
}); !errors.Is(err, kbbinding.ErrKeyForwarding) {
|
||||
t.Fatalf("keep with another address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
|
||||
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("production Save() error = %v", err)
|
||||
}
|
||||
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 {
|
||||
t.Fatalf("production view = %#v", prodView)
|
||||
}
|
||||
var productionInternal string
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if productionInternal != "kb-in" {
|
||||
t.Fatalf("production binding = %s", productionInternal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
const (
|
||||
statusOK = "ok"
|
||||
statusEmpty = "empty"
|
||||
statusUnauthorized = "unauthorized"
|
||||
statusUnreachable = "unreachable"
|
||||
statusUnsupported = "unsupported"
|
||||
)
|
||||
|
||||
// Catalog validates a draft connection for real and returns one page of the
|
||||
// knowledge bases that key can read. It never writes anything and never echoes
|
||||
// the key.
|
||||
func (s *Store) Catalog(ctx context.Context, env string, input CatalogInput) (Catalog, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
page, pageSize := input.Page, input.PageSize
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
client, err := s.client(baseURL, key, env)
|
||||
if err != nil {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
result, err := client.ListKnowledgeBasesPage(ctx, page, pageSize)
|
||||
if err != nil {
|
||||
return catalogFailure(err), nil
|
||||
}
|
||||
options := make([]Option, 0, len(result.Items))
|
||||
for _, base := range result.Items {
|
||||
options = append(options, Option{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
|
||||
}
|
||||
status := statusOK
|
||||
message := fmt.Sprintf("已读取 %d 个知识库", result.Total)
|
||||
if result.Total == 0 {
|
||||
status = statusEmpty
|
||||
message = "连接可用,但这个实例还没有可读的知识库"
|
||||
}
|
||||
return Catalog{Status: status, Message: message, Page: page, PageSize: pageSize, Total: result.Total, Options: options}, nil
|
||||
}
|
||||
|
||||
// catalogFailure turns a transport/permission failure into a distinguishable
|
||||
// answer: "empty" must never be shown for "could not ask".
|
||||
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.StatusNotFound:
|
||||
return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"}
|
||||
default:
|
||||
return Catalog{Status: statusUnreachable, Message: fmt.Sprintf("实例返回 HTTP %d,无法确认连接", httpErr.StatusCode)}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return Catalog{Status: statusUnreachable, Message: "连接超时:检查地址、网络与防火墙"}
|
||||
}
|
||||
return Catalog{Status: statusUnreachable, Message: "服务不可达:检查地址、网络与证书"}
|
||||
}
|
||||
|
||||
// Save writes the environment's connection and both bindings in ONE
|
||||
// transaction. The candidate instance is asked first; nothing is written when
|
||||
// either selected base does not belong to it. A stale base_revision returns
|
||||
// ErrConflict and leaves the previous binding untouched.
|
||||
func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor string, now time.Time) (View, error) {
|
||||
if !ValidEnvironment(env) || strings.TrimSpace(actor) == "" || now.IsZero() {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
internal := strings.TrimSpace(input.InternalKBID)
|
||||
external := strings.TrimSpace(input.ExternalKBID)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 ||
|
||||
internal != input.InternalKBID || external != input.ExternalKBID ||
|
||||
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
if internal != "" && internal == external {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
client, err := s.client(baseURL, key, env)
|
||||
if err != nil {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
names, 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
|
||||
}
|
||||
verification := "verified"
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,42))`, "weknora-binding:"+env); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
locked, lockedFound, err := scanStored(tx.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1 FOR UPDATE`, env))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
lockedRevision := int64(0)
|
||||
if lockedFound {
|
||||
lockedRevision = locked.Revision
|
||||
}
|
||||
if lockedRevision != input.BaseRevision {
|
||||
return View{}, ErrConflict
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_bindings(
|
||||
environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,
|
||||
internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$10)
|
||||
ON CONFLICT(environment) DO UPDATE SET
|
||||
revision=EXCLUDED.revision,base_url=EXCLUDED.base_url,key_ciphertext=EXCLUDED.key_ciphertext,
|
||||
internal_kb_id=EXCLUDED.internal_kb_id,external_kb_id=EXCLUDED.external_kb_id,
|
||||
internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name,
|
||||
verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at,
|
||||
updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
|
||||
env, revision, baseURL, sealed, internal, external, names[internal], names[external], verification, now.UTC(), actor); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_binding_history(
|
||||
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
replan := postgresstore.RoutingBindingReplanResult{}
|
||||
if env == EnvTest {
|
||||
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
effectiveInternal, effectiveExternal := internal, external
|
||||
if s.options.RoutingDefaults != nil {
|
||||
defaultInternal, defaultExternal := s.options.RoutingDefaults()
|
||||
if effectiveInternal == "" {
|
||||
effectiveInternal = defaultInternal
|
||||
}
|
||||
if effectiveExternal == "" {
|
||||
effectiveExternal = defaultExternal
|
||||
}
|
||||
}
|
||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now.UTC())
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
} else {
|
||||
// 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。
|
||||
if err := postgresstore.SaveProductionKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view.Replanned = replan.Replanned
|
||||
view.RetiredDuplicates = replan.RetiredDuplicates
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// verifySelection proves both chosen bases belong to THIS candidate instance by
|
||||
// reading them with the draft credential. An empty selection still probes the
|
||||
// list endpoint, so a save cannot store a connection nobody verified.
|
||||
func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]string, error) {
|
||||
names := map[string]string{}
|
||||
if internal == "" && external == "" {
|
||||
if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil {
|
||||
return nil, selectionError(err, "无法确认候选连接")
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
for _, id := range []string{internal, external} {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
base, err := client.GetKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return nil, selectionError(err, fmt.Sprintf("知识库 %s 不属于该连接实例或不可读", shortID(id)))
|
||||
}
|
||||
if base.ID != id {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
names[id] = base.Name
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func selectionError(err error, message string) error {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
if httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden {
|
||||
return fmt.Errorf("%w:密钥被实例拒绝(HTTP %d)", ErrRejected, httpErr.StatusCode)
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w:连接超时", ErrUnreachable)
|
||||
}
|
||||
if _, ok := err.(*weknora.HTTPError); ok {
|
||||
return fmt.Errorf("%w:%s", ErrRejected, message)
|
||||
}
|
||||
if errors.Is(err, ErrInvalid) || errors.Is(err, ErrRejected) || errors.Is(err, ErrUnreachable) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w:%s", ErrUnreachable, message)
|
||||
}
|
||||
|
||||
func validBaseID(value string) bool {
|
||||
return !strings.ContainsAny(value, "\x00\r\n\t /?#\\")
|
||||
}
|
||||
|
||||
func shortID(value string) string {
|
||||
if len(value) > 8 {
|
||||
return value[:8]
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
overview.Health = provider.Services(ctx)
|
||||
overview.Services = append(overview.Services,
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), 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,3 @@
|
||||
-- 回滚只删本迁移新增的审计与配置表;旧部署的 file 凭据/绑定表不受影响。
|
||||
DROP TABLE IF EXISTS weknora_environment_binding_history;
|
||||
DROP TABLE IF EXISTS weknora_environment_bindings;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- 「知识库绑定」按环境保存一组连接与内外库绑定:测试与生产各自一行,
|
||||
-- 一次保存同时写连接(地址 + 加密密钥)与对内/对外目标。没有行时消费者
|
||||
-- 继续使用旧部署的文件凭据/默认绑定,所以升级不需要回填。
|
||||
--
|
||||
-- key_ciphertext 只存密文;主密钥在独立文件里(WEKNORA_BINDING_MASTER_KEY_FILE),
|
||||
-- 不进库、不进备份、不经页面回显。verification 记录最近一次真实列库/选库核验。
|
||||
CREATE TABLE weknora_environment_bindings (
|
||||
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
|
||||
revision BIGINT NOT NULL CHECK (revision > 0),
|
||||
base_url TEXT NOT NULL DEFAULT '',
|
||||
key_ciphertext BYTEA NOT NULL DEFAULT ''::bytea,
|
||||
internal_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
external_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
internal_kb_name TEXT NOT NULL DEFAULT '',
|
||||
external_kb_name TEXT NOT NULL DEFAULT '',
|
||||
verification TEXT NOT NULL DEFAULT 'not_configured'
|
||||
CHECK (verification IN ('not_configured','verified','empty','unreachable','rejected')),
|
||||
checked_at TIMESTAMPTZ,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- 修订历史只记录“是否配置了密钥”,绝不复制密文或明文,供审计回答谁在何时
|
||||
-- 把哪个环境指向了哪里。
|
||||
CREATE TABLE weknora_environment_binding_history (
|
||||
environment VARCHAR(16) NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
base_url TEXT NOT NULL,
|
||||
key_configured BOOLEAN NOT NULL,
|
||||
internal_kb_id VARCHAR(128) NOT NULL,
|
||||
external_kb_id VARCHAR(128) NOT NULL,
|
||||
verification TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (environment, revision)
|
||||
);
|
||||
@@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 80 {
|
||||
t.Fatalf("migration count = %d, want 80", len(migrations))
|
||||
if len(migrations) != 81 {
|
||||
t.Fatalf("migration count = %d, want 81", len(migrations))
|
||||
}
|
||||
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
|
||||
if binding := migrations[80]; binding.Version != 81 ||
|
||||
!strings.Contains(binding.UpSQL, "weknora_environment_bindings") ||
|
||||
!strings.Contains(binding.UpSQL, "key_ciphertext") ||
|
||||
!strings.Contains(binding.DownSQL, "DROP TABLE IF EXISTS weknora_environment_bindings") {
|
||||
t.Fatalf("migration 81 = %#v", binding)
|
||||
}
|
||||
// 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥,
|
||||
// 证据按 target_id 落库(换目标旧证据自动失效)。
|
||||
|
||||
@@ -39,14 +39,26 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
|
||||
if now.IsZero() {
|
||||
return errors.New("production binding save requires a timestamp")
|
||||
}
|
||||
if _, err := s.db.Exec(ctx, `
|
||||
if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const productionBindingUpsertSQL = `
|
||||
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
|
||||
VALUES('active',$1,$2,$3,$4)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
internal_kb_id=EXCLUDED.internal_kb_id,
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
updated_at=EXCLUDED.updated_at`
|
||||
|
||||
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
|
||||
// update the same row inside its own transaction, so connection and bindings
|
||||
// cannot be half-written.
|
||||
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -121,6 +121,22 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
|
||||
return result, fmt.Errorf("begin routing binding save: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err := SaveRoutingKBBindingsTx(ctx, tx, internalID, externalID, updatedBy, now); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result, err = ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now)
|
||||
if err != nil {
|
||||
return RoutingBindingReplanResult{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return result, fmt.Errorf("commit routing binding save: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveRoutingKBBindingsTx is the binding upsert, shared by the settings page and
|
||||
// the environment-scoped 「知识库绑定」save so the two entries cannot drift.
|
||||
func SaveRoutingKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
|
||||
VALUES('active',$1,$2,$3,$4)
|
||||
@@ -129,8 +145,16 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
return result, errors.New("save routing kb bindings")
|
||||
return errors.New("save routing kb bindings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplanPendingPublicationsTx re-points untouched 待入库 rows at the new targets
|
||||
// inside the caller's transaction. It only moves rows that were never uploaded
|
||||
// anywhere; anything already in flight keeps its frozen target.
|
||||
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, effectiveInternal, effectiveExternal string, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
var result RoutingBindingReplanResult
|
||||
for _, scope := range []struct{ name, kbID string }{
|
||||
{"internal", effectiveInternal},
|
||||
{"external", effectiveExternal},
|
||||
@@ -149,8 +173,5 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
result.RetiredDuplicates += int(retired.RowsAffected())
|
||||
result.Replanned += int(moved.RowsAffected())
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return result, fmt.Errorf("commit routing binding save: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -234,6 +234,31 @@ func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBasesPage reads one page. The console must show every readable
|
||||
// base without pretending the first page is the whole set, so the total is
|
||||
// carried through whenever the instance reports one.
|
||||
func (c *Client) ListKnowledgeBasesPage(ctx context.Context, page, pageSize int) (KnowledgeBasePage, error) {
|
||||
if !validPage(page, pageSize) {
|
||||
return KnowledgeBasePage{}, errors.New("invalid knowledge base list request")
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("page", fmt.Sprint(page))
|
||||
query.Set("page_size", fmt.Sprint(pageSize))
|
||||
var response knowledgeBaseListResponse
|
||||
if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/knowledge-bases", query, nil, &response); err != nil {
|
||||
return KnowledgeBasePage{}, err
|
||||
}
|
||||
if !response.Success {
|
||||
return KnowledgeBasePage{}, errors.New("WeKnora returned an unsuccessful knowledge base list")
|
||||
}
|
||||
total := response.Total
|
||||
totalKnown := total > 0 || (len(response.Data) == 0 && response.Page > 0)
|
||||
if !totalKnown {
|
||||
total = int64(len(response.Data))
|
||||
}
|
||||
return KnowledgeBasePage{Items: response.Data, Total: total, Page: page, PageSize: pageSize, TotalKnown: totalKnown}, 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".
|
||||
|
||||
@@ -76,8 +76,21 @@ type KnowledgeBase struct {
|
||||
}
|
||||
|
||||
type knowledgeBaseListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// KnowledgeBasePage is one page of the readable knowledge bases. TotalKnown is
|
||||
// false when the instance did not report a total; callers must not invent one.
|
||||
type KnowledgeBasePage struct {
|
||||
Items []KnowledgeBase
|
||||
Total int64
|
||||
Page int
|
||||
PageSize int
|
||||
TotalKnown bool
|
||||
}
|
||||
|
||||
type knowledgeBaseResponse struct {
|
||||
|
||||
+21
-32
@@ -1,53 +1,42 @@
|
||||
package qaopsai
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
// The independently provisioned master key never lives in source, settings JSON or database backups.
|
||||
func (s *Store) box() (*secretbox.Box, error) {
|
||||
box, err := secretbox.Load(s.options.KeyFile)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return box, nil
|
||||
}
|
||||
|
||||
// masterKey 保留给调用方判断“存储是否就绪”;实际加解密统一走 secretbox。
|
||||
func (s *Store) masterKey() ([]byte, error) {
|
||||
info, err := os.Lstat(s.options.KeyFile)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
raw, err := os.ReadFile(s.options.KeyFile)
|
||||
if err != nil || len(raw) != 32 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
func (s *Store) aead() (cipher.AEAD, error) {
|
||||
key, err := s.masterKey()
|
||||
if err != nil {
|
||||
if _, err := s.box(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
return []byte{1}, nil
|
||||
}
|
||||
|
||||
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
|
||||
aead, err := s.aead()
|
||||
box, err := s.box()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, aead.NonceSize())
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return aead.Seal(nonce, nonce, []byte(secret), []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))), nil
|
||||
return box.Seal([]byte(secret), fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
}
|
||||
|
||||
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
|
||||
aead, err := s.aead()
|
||||
if err != nil || len(sealed) < aead.NonceSize() {
|
||||
return "", ErrUnavailable
|
||||
box, err := s.box()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)))
|
||||
raw, err := box.Open(sealed, fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
if err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ type Resolver struct {
|
||||
LoadBinding func(context.Context) (string, error)
|
||||
ReadKey func() (string, error)
|
||||
DefaultKB string
|
||||
// ResolveConnection 可选:一次解析端点与凭据(例如来自加密存储)。
|
||||
// 提供时优先于 Endpoint + ReadKey,因为密钥解密需要请求上下文。
|
||||
ResolveConnection func(context.Context) (baseURL, apiKey string, err error)
|
||||
}
|
||||
|
||||
func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
@@ -58,19 +61,26 @@ func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
knowledgeBaseID = stored
|
||||
}
|
||||
}
|
||||
apiKey := ""
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
baseURL, apiKey := "", ""
|
||||
if resolver.ResolveConnection != nil {
|
||||
var err error
|
||||
baseURL, apiKey, err = resolver.ResolveConnection(ctx)
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
return Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
} else {
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
baseURL := ""
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
return Target{BaseURL: baseURL, KnowledgeBaseID: knowledgeBaseID, APIKey: apiKey}, nil
|
||||
return Target{BaseURL: strings.TrimSpace(baseURL), KnowledgeBaseID: knowledgeBaseID, APIKey: strings.TrimSpace(apiKey)}, nil
|
||||
}
|
||||
|
||||
type Prober struct {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Package secretbox 是平台唯一的对称加密落库入口:主密钥来自独立文件
|
||||
// (0600 常规文件,正好 32 字节),密文通过 AES-256-GCM 与调用方给出的
|
||||
// Additional Authenticated Data 绑定。AAD 让一行密文无法被搬到另一行
|
||||
// (换环境/换修订)后仍能解开。
|
||||
package secretbox
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("secret key is not available")
|
||||
|
||||
type Box struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
|
||||
// Load 读取主密钥。拒绝非普通文件、非 0600 权限或长度不是 32 字节的密钥,
|
||||
// 避免"碰巧能读到"就被当成已正确配置。
|
||||
func Load(path string) (*Box, error) {
|
||||
if path == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
key, err := os.ReadFile(path)
|
||||
if err != nil || len(key) != 32 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return &Box{aead: aead}, nil
|
||||
}
|
||||
|
||||
func (box *Box) Seal(plaintext []byte, aad string) ([]byte, error) {
|
||||
if box == nil || box.aead == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
nonce := make([]byte, box.aead.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return box.aead.Seal(nonce, nonce, plaintext, []byte(aad)), nil
|
||||
}
|
||||
|
||||
func (box *Box) Open(sealed []byte, aad string) ([]byte, error) {
|
||||
if box == nil || box.aead == nil || len(sealed) < box.aead.NonceSize() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
raw, err := box.aead.Open(nil, sealed[:box.aead.NonceSize()], sealed[box.aead.NonceSize():], []byte(aad))
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
Reference in New Issue
Block a user