在既有 kbbinding(迁移 000081)上补齐任务要求,不另建表、不另起路由: - 测试连接区分 401/403(密钥无效 / 无权限)与不可达、成功四态; - 视图回显密钥尾 4 位(服务端不存、不回读明文); - key_action=clear 作为独立动作,清除后解析失败关闭、不回落文件旧 Key; - 内外库留空 = 取消绑定,回报回退来源(测试侧部署默认库 / 生产侧同 ID 语义); - 生产绑定回报在飞执行的冻结/仍可改指向条数,已冻结目标不被改写; - 新增 WEKNORA_ALLOW_PRIVATE_HTTP:客户端/探活/连接页共用 HTTPAllowed, 只放行 RFC1918/回环/链路本地 http,生产 18093 同网段反代因此可用。
This commit is contained in:
@@ -47,6 +47,9 @@ type Config struct {
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
TestWeKnoraAPIKeyFile string
|
||||
// WeKnoraAllowPrivateHTTP 放行同网段 http(生产 18093 反代);只接受
|
||||
// RFC1918/回环/链路本地,公网 http 仍拒绝。监控探活与列库共用同一判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
@@ -362,6 +365,12 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
if raw := getenv("WEKNORA_ALLOW_PRIVATE_HTTP"); raw != "" {
|
||||
config.WeKnoraAllowPrivateHTTP, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("WEKNORA_ALLOW_PRIVATE_HTTP: %w", err)
|
||||
}
|
||||
}
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) {
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -32,3 +32,29 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
|
||||
// fetch from the operator console itself when it is served over plain http on a
|
||||
// private address. That is the only non-TLS shape this deployment needs, and it
|
||||
// still requires an exact Origin/Host match.
|
||||
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
||||
if secretTransportAllowed(r, trustTLSProxy) {
|
||||
return true
|
||||
}
|
||||
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
return strings.EqualFold(host, "localhost")
|
||||
}
|
||||
|
||||
@@ -142,6 +142,9 @@ type Config struct {
|
||||
// internal/external bindings saved together. Nil keeps the page read-only
|
||||
// and reports unavailable, never a fake success.
|
||||
KBBindings KBBindingStore
|
||||
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
|
||||
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
|
||||
|
||||
@@ -48,11 +48,14 @@ var (
|
||||
// View is the public projection. It never carries a key, ciphertext or any
|
||||
// value derived from the key beyond "configured or not".
|
||||
type View struct {
|
||||
Environment string `json:"environment"`
|
||||
Revision int64 `json:"revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyConfigured bool `json:"key_configured"`
|
||||
KeySource string `json:"key_source"`
|
||||
Environment string `json:"environment"`
|
||||
Revision int64 `json:"revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyConfigured bool `json:"key_configured"`
|
||||
KeySource string `json:"key_source"`
|
||||
// KeyTail is the only part of the key the page may show. It is derived at
|
||||
// read time and never stored, so a rotated master key cannot resurrect it.
|
||||
KeyTail string `json:"key_tail"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
@@ -69,6 +72,13 @@ type View struct {
|
||||
// rows that had never been uploaded; a plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
// 留空绑定 = 取消绑定,页面必须说清回退到了哪里:测试侧回退到部署默认库,
|
||||
// 生产侧回退到「同 ID 语义」。空串表示该方向仍有显式绑定。
|
||||
InternalFallback string `json:"internal_fallback"`
|
||||
ExternalFallback string `json:"external_fallback"`
|
||||
// 生产侧冻结计数:执行已开始的发布项目标已钉死,保存绑定不会改写它们。
|
||||
Frozen int `json:"frozen"`
|
||||
Retargetable int `json:"retargetable"`
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
@@ -119,6 +129,9 @@ type Options struct {
|
||||
// AllowDockerHTTP mirrors the per-environment client policy (a single-label
|
||||
// docker host may be reached over plain HTTP in the internal network).
|
||||
AllowDockerHTTP map[string]bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses
|
||||
// (production 18093 reverse proxy). Public http stays refused.
|
||||
AllowPrivateHTTP map[string]bool
|
||||
// LegacyBaseURL resolves the pre-existing endpoint (web setting first, then
|
||||
// the deployment env value). It is only consulted when no row exists.
|
||||
LegacyBaseURL func(context.Context, string) string
|
||||
@@ -253,6 +266,13 @@ func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
||||
view.UpdatedBy = saved.UpdatedBy
|
||||
view.UpdatedAt = saved.UpdatedAt
|
||||
view.Source = "web"
|
||||
if s.options.MasterKeyFile != "" {
|
||||
if tail, ok := s.keyTail(saved, env); ok {
|
||||
view.KeyTail = tail
|
||||
}
|
||||
}
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
return view, nil
|
||||
}
|
||||
// Legacy fallback: exactly what the consumers use before any page save.
|
||||
@@ -270,10 +290,81 @@ func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
||||
view.ExternalKBID = external
|
||||
}
|
||||
view.Verification = "legacy"
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
s.fillNames(ctx, &view)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// keyTail decrypts only to keep the last four characters. It never returns the
|
||||
// key and never writes the tail anywhere.
|
||||
func (s *Store) keyTail(saved stored, env string) (string, bool) {
|
||||
box := s.loadBox()
|
||||
if box == nil || len(saved.KeyCiphertext) == 0 {
|
||||
return "", false
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
runes := []rune(string(raw))
|
||||
if len(runes) <= 4 {
|
||||
return string(runes), true
|
||||
}
|
||||
return string(runes[len(runes)-4:]), true
|
||||
}
|
||||
|
||||
// fillFallbacks explains where an unbound direction routes to. Without this the
|
||||
// page could only say 「留空」without saying what 「空」means.
|
||||
func (s *Store) fillFallbacks(ctx context.Context, env string, view *View) {
|
||||
if view.InternalKBID != "" && view.ExternalKBID != "" {
|
||||
return
|
||||
}
|
||||
if env == EnvProduction {
|
||||
if view.InternalKBID == "" {
|
||||
view.InternalFallback = "same-id"
|
||||
}
|
||||
if view.ExternalKBID == "" {
|
||||
view.ExternalFallback = "same-id"
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.options.LegacyBinding == nil {
|
||||
return
|
||||
}
|
||||
internal, external, err := s.options.LegacyBinding(ctx, env)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if view.InternalKBID == "" && strings.TrimSpace(internal) != "" {
|
||||
view.InternalFallback = strings.TrimSpace(internal)
|
||||
}
|
||||
if view.ExternalKBID == "" && strings.TrimSpace(external) != "" {
|
||||
view.ExternalFallback = strings.TrimSpace(external)
|
||||
}
|
||||
}
|
||||
|
||||
// fillExecutionCounts reports how many in-flight release items already have a
|
||||
// frozen production target. Completed executions are history, not something a
|
||||
// binding change could still move.
|
||||
func (s *Store) fillExecutionCounts(ctx context.Context, env string, view *View) {
|
||||
if env != EnvProduction {
|
||||
return
|
||||
}
|
||||
var frozen, retargetable int
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''),
|
||||
COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '')
|
||||
FROM release_item_executions item
|
||||
JOIN release_executions execution ON execution.id = item.release_execution_id
|
||||
WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
view.Frozen, view.Retargetable = frozen, retargetable
|
||||
}
|
||||
|
||||
func keySource(configured bool) string {
|
||||
if configured {
|
||||
return "sealed"
|
||||
@@ -395,6 +486,13 @@ func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return apiKey, nil
|
||||
case "clear":
|
||||
// 清除密钥是独立动作:留下地址与绑定,只是这一侧不再有可用凭据,
|
||||
// 消费者解析会失败关闭(不会悄悄回落到部署文件里的旧 Key)。
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return "", nil
|
||||
default:
|
||||
return "", ErrInvalid
|
||||
}
|
||||
@@ -406,10 +504,11 @@ func validAPIKey(value string) bool {
|
||||
|
||||
func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) {
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: s.options.Timeout,
|
||||
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: s.options.Timeout,
|
||||
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
|
||||
AllowPrivateHTTP: s.options.AllowPrivateHTTP[env],
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
type emptyDB struct{}
|
||||
@@ -74,7 +80,7 @@ func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) {
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusUnauthorized {
|
||||
if err != nil || catalog.Status != statusKeyInvalid {
|
||||
t.Fatalf("denied catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
@@ -119,7 +125,6 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
|
||||
for _, input := range []SaveInput{
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb-in"},
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
|
||||
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
|
||||
} {
|
||||
@@ -128,3 +133,79 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesInvalidKeyFromForbiddenKey(t *testing.T) {
|
||||
invalid := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusUnauthorized})
|
||||
if invalid.Status != "key_invalid" || !strings.Contains(invalid.Message, "密钥无效") {
|
||||
t.Fatalf("401 -> %+v", invalid)
|
||||
}
|
||||
forbidden := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusForbidden})
|
||||
if forbidden.Status != "key_forbidden" || !strings.Contains(forbidden.Message, "无权限") {
|
||||
t.Fatalf("403 -> %+v", forbidden)
|
||||
}
|
||||
dead := catalogFailure(context.DeadlineExceeded)
|
||||
if dead.Status != "unreachable" || !(strings.Contains(dead.Message, "超时") || strings.Contains(dead.Message, "不可达")) {
|
||||
t.Fatalf("timeout -> %+v", dead)
|
||||
}
|
||||
if dead.Status == invalid.Status || invalid.Status == forbidden.Status {
|
||||
t.Fatal("the three outcomes must stay distinguishable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearKeyIsASeparateAction(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 2, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
key, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "", saved, true)
|
||||
if err != nil || key != "" {
|
||||
t.Fatalf("clear = %q, %v", key, err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("clear with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyTailShowsOnlyFourCharacters(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "master.key")
|
||||
if err := os.WriteFile(path, bytes.Repeat([]byte{7}, 32), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
box, err := secretbox.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("secretbox.Load: %v", err)
|
||||
}
|
||||
sealed, err := box.Seal([]byte("sk-live-abcd"), keyAAD(EnvTest, 3))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := New(emptyDB{}, Options{MasterKeyFile: path})
|
||||
tail, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 3}, EnvTest)
|
||||
if !ok || tail != "abcd" {
|
||||
t.Fatalf("tail = %q %v", tail, ok)
|
||||
}
|
||||
// A different revision must not open — the tail must never leak from a
|
||||
// ciphertext that no longer matches the row.
|
||||
if _, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 4}, EnvTest); ok {
|
||||
t.Fatal("tail opened with the wrong revision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{LegacyBinding: func(context.Context, string) (string, string, error) {
|
||||
return "legacy-in-0001", "legacy-out-0001", nil
|
||||
}})
|
||||
view := View{Environment: EnvTest}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &view)
|
||||
if view.InternalFallback != "legacy-in-0001" || view.ExternalFallback != "legacy-out-0001" {
|
||||
t.Fatalf("test fallbacks = %+v", view)
|
||||
}
|
||||
production := View{Environment: EnvProduction}
|
||||
store.fillFallbacks(context.Background(), EnvProduction, &production)
|
||||
if production.InternalFallback != "same-id" || production.ExternalFallback != "same-id" {
|
||||
t.Fatalf("production fallbacks = %+v", production)
|
||||
}
|
||||
bound := View{Environment: EnvTest, InternalKBID: "a", ExternalKBID: "b"}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &bound)
|
||||
if bound.InternalFallback != "" || bound.ExternalFallback != "" {
|
||||
t.Fatalf("bound view must not claim a fallback: %+v", bound)
|
||||
}
|
||||
}
|
||||
|
||||
+33
-23
@@ -15,7 +15,8 @@ import (
|
||||
const (
|
||||
statusOK = "ok"
|
||||
statusEmpty = "empty"
|
||||
statusUnauthorized = "unauthorized"
|
||||
statusKeyInvalid = "key_invalid"
|
||||
statusKeyForbidden = "key_forbidden"
|
||||
statusUnreachable = "unreachable"
|
||||
statusUnsupported = "unsupported"
|
||||
)
|
||||
@@ -76,8 +77,10 @@ func catalogFailure(err error) Catalog {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.StatusCode {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return Catalog{Status: statusUnauthorized, Message: "密钥被实例拒绝(HTTP 401/403):检查 API Key 与该实例权限"}
|
||||
case http.StatusUnauthorized:
|
||||
return Catalog{Status: statusKeyInvalid, Message: "密钥无效:该实例拒绝了这把 API Key(401)"}
|
||||
case http.StatusForbidden:
|
||||
return Catalog{Status: statusKeyForbidden, Message: "密钥无权限读取知识库列表(403)"}
|
||||
case http.StatusNotFound:
|
||||
return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"}
|
||||
default:
|
||||
@@ -106,12 +109,9 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
|
||||
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
// 新页面必须给两个方向各选一个库:显式“未绑定”会回落到部署默认 ID,
|
||||
// 而那个 ID 可能属于旧实例;在换绑实例后继续沿用就是错误目标。
|
||||
if internal == "" || external == "" {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
if internal == external {
|
||||
// 留空 = 取消该方向绑定:测试侧回退到部署默认库,生产侧回退到「同 ID 语义」,
|
||||
// 响应里会写明回退到哪(InternalFallback / ExternalFallback)。
|
||||
if internal != "" && internal == external {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
@@ -122,27 +122,37 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
client, err := s.client(baseURL, key, env)
|
||||
if err != nil {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
selected, err := s.verifySelection(ctx, client, internal, external)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
selected := map[string]selectedBase{}
|
||||
cleared := key == "" && input.KeyAction == "clear"
|
||||
if !cleared {
|
||||
client, clientErr := s.client(baseURL, key, env)
|
||||
if clientErr != nil {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
selected, err = s.verifySelection(ctx, client, internal, external)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
}
|
||||
revision := saved.Revision + 1
|
||||
if !found {
|
||||
revision = 1
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
sealed, err := box.Seal([]byte(key), keyAAD(env, revision))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
sealed := []byte{}
|
||||
if !cleared {
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
sealed, err = box.Seal([]byte(key), keyAAD(env, revision))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
verification := "verified"
|
||||
if cleared {
|
||||
verification = "not_configured"
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// P10: every configured dependency reports Liveness ("process reachable") and
|
||||
@@ -200,10 +201,14 @@ func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now ti
|
||||
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
|
||||
parsed, err := url.Parse(baseURL)
|
||||
outcome := ProbeOutcome{ObservedAt: now}
|
||||
if err != nil || parsed.Scheme != "http" && parsed.Scheme != "https" || parsed.Host == "" {
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||
outcome.Reachability = errors.New("探测配置无效")
|
||||
return outcome
|
||||
}
|
||||
if !weknora.HTTPAllowed(baseURL, weknora.HTTPPolicy{AllowPrivateHTTP: provider.allowPrivateHTTP}) {
|
||||
outcome.Reachability = errors.New("探测配置无效:该地址不被允许(https 或已放行的私网/回环 http)")
|
||||
return outcome
|
||||
}
|
||||
parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/health"
|
||||
parsed.RawQuery, parsed.Fragment = "", ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
|
||||
@@ -50,6 +50,10 @@ type RealProviderConfig struct {
|
||||
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
|
||||
// as alive (P10).
|
||||
WorkerStaleAfter time.Duration
|
||||
// AllowPrivateHTTP lets the console probe a same-LAN http endpoint — the
|
||||
// same judgement the WeKnora client uses, so a card can never say 「可达」
|
||||
// while the client refuses that URL.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type RealProvider struct {
|
||||
@@ -63,6 +67,7 @@ type RealProvider struct {
|
||||
productionWeKnoraResolver func(ctx context.Context) string
|
||||
weknoraReadiness func(ctx context.Context) (string, error)
|
||||
workerStaleAfter time.Duration
|
||||
allowPrivateHTTP bool
|
||||
health *healthTracker
|
||||
}
|
||||
|
||||
@@ -103,7 +108,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
|
||||
if stale <= 0 {
|
||||
stale = time.Minute
|
||||
}
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
|
||||
}
|
||||
|
||||
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
|
||||
|
||||
@@ -48,6 +48,53 @@ type ClientConfig struct {
|
||||
Timeout time.Duration
|
||||
MaxResponseBytes int64
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for RFC1918 / link-local
|
||||
// literals, because the production instance is only reachable as a same-LAN
|
||||
// http reverse proxy. Public http hosts stay refused.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
// HTTPPolicy is the single reachability judgement shared by the WeKnora client,
|
||||
// the console probes and the binding page: two callers must never disagree
|
||||
// about whether a configured endpoint is acceptable.
|
||||
type HTTPPolicy struct {
|
||||
AllowPrivateHTTP bool
|
||||
AllowDockerHTTP bool
|
||||
}
|
||||
|
||||
// HTTPAllowed reports whether baseURL may be called at all. https is always
|
||||
// allowed; http only for loopback, an opted-in private address, or a
|
||||
// single-label docker host.
|
||||
func HTTPAllowed(rawURL string, policy HTTPPolicy) bool {
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || parsed.Host == "" || parsed.User != nil {
|
||||
return false
|
||||
}
|
||||
switch parsed.Scheme {
|
||||
case "https":
|
||||
return true
|
||||
case "http":
|
||||
host := parsed.Hostname()
|
||||
if isLoopbackHost(host) {
|
||||
return true
|
||||
}
|
||||
if policy.AllowPrivateHTTP && isPrivateHost(host) {
|
||||
return true
|
||||
}
|
||||
return policy.AllowDockerHTTP && isSingleLabelDockerHost(host)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isPrivateHost reports the addresses a same-LAN deployment legitimately uses:
|
||||
// RFC1918, link-local and IPv6 ULA. A public name is never private, so opting
|
||||
// in cannot widen the client to the internet.
|
||||
func isPrivateHost(host string) bool {
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
@@ -65,7 +112,7 @@ func NewClient(config ClientConfig) (*Client, error) {
|
||||
if baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {
|
||||
return nil, errors.New("invalid WeKnora base URL")
|
||||
}
|
||||
if baseURL.Scheme != "https" && !(baseURL.Scheme == "http" && (isLoopbackHost(baseURL.Hostname()) || (config.AllowDockerHTTP && isSingleLabelDockerHost(baseURL.Hostname())))) {
|
||||
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
|
||||
return nil, errors.New("WeKnora base URL must use HTTPS")
|
||||
}
|
||||
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
|
||||
|
||||
@@ -87,6 +87,9 @@ type Prober struct {
|
||||
Resolve func(context.Context) (Target, error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses, the
|
||||
// same judgement the binding store and the client use.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (prober Prober) Check(ctx context.Context) Result {
|
||||
@@ -106,10 +109,11 @@ func (prober Prober) Check(ctx context.Context) Result {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
AllowPrivateHTTP: prober.AllowPrivateHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return Result{Target: described, Err: err}
|
||||
|
||||
Reference in New Issue
Block a user