feat(settings): 页面录入测试/生产 WeKnora 连接与密钥并收敛可达性判定

连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥,
页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功,
换地址或换密钥必须测通才能保存(迁移 000083)。

可达性判定收敛为 weknora.HTTPAllowed,客户端与监控探活共用;新增
WEKNORA_ALLOW_PRIVATE_HTTP 只放行 RFC1918/回环/链路本地。生产绑定只保留下拉,
保存后回报冻结/未冻结条数,已冻结目标不被改写。

(cherry picked from commit ad02e8bb9c)
This commit is contained in:
狐友 GXXP & Miku
2026-11-22 15:05:48 +08:00
committed by 姚章浩
parent 8c76c54d8e
commit 8b900a9ffb
44 changed files with 2798 additions and 198 deletions
+153
View File
@@ -0,0 +1,153 @@
package httpapi
import (
"context"
"errors"
"net"
"net/http"
"net/url"
"strings"
"knowledge-governance/internal/weknoraconn"
)
// WeKnoraConnections is the connection service the routes below call. It is
// deliberately narrow: the page may read state, run one real test, and save a
// tested configuration — nothing here triggers a sync, a release or a reparse.
type WeKnoraConnections interface {
View(ctx context.Context, environment string) ([]weknoraconn.View, error)
Test(ctx context.Context, environment string, input weknoraconn.TestInput) (weknoraconn.TestResult, error)
Save(ctx context.Context, environment string, input weknoraconn.SaveInput, actor string) (weknoraconn.View, error)
}
func weKnoraConnectionError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, weknoraconn.ErrNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": "未知的 WeKnora 环境(只支持 test / production)"})
case errors.Is(err, weknoraconn.ErrStaleRevision):
writeJSON(w, http.StatusConflict, map[string]string{"error": "连接配置已被他人修改,请重新读取后再保存"})
case errors.Is(err, weknoraconn.ErrNotTested):
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_connection_not_tested",
"error": "请先点「测试连接」并成功,才能保存这一侧的配置",
})
case errors.Is(err, weknoraconn.ErrStorageUnavailable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "密钥存储不可用:主密钥文件缺失或权限不是 0600,本次未保存任何密钥",
})
case errors.Is(err, weknoraconn.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "连接配置不合法:地址必填,且更换地址必须重新录入密钥"})
default:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "WeKnora 连接配置处理失败"})
}
}
// weKnoraSecretTransportWithPrivateHTTP decides whether a plaintext key may be
// accepted on this request. It reuses the QA-AI rule (TLS, loopback, trusted
// TLS proxy + same origin) and adds the one case this deployment needs: the
// operator console itself is reached over plain http on a private address, so a
// same-origin fetch from that console is the only accepted non-TLS shape.
func weKnoraSecretTransportWithPrivateHTTP(config Config, r *http.Request) bool {
if qaAISecretTransport(r, config) {
return true
}
if config.WeKnoraTrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" &&
r.Header.Get("Sec-Fetch-Site") == "same-origin" {
origin, err := url.Parse(r.Header.Get("Origin"))
if err == nil && origin.Scheme == "https" {
return true
}
}
if !config.WeKnoraAllowPrivateHTTP {
return false
}
if 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 == "" {
return false
}
if !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")
}
func (config Config) handleWeKnoraConnections(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
views, err := config.WeKnoraConnections.View(r.Context(), r.PathValue("environment"))
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": views})
}
func (config Config) handleWeKnoraConnectionTest(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
var input weknoraconn.TestInput
if err := decodeStrictJSON(r, &input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
return
}
if strings.TrimSpace(input.APIKey) != "" && !weKnoraSecretTransportWithPrivateHTTP(config, r) {
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_secret_secure_transport_required",
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
})
return
}
result, err := config.WeKnoraConnections.Test(r.Context(), r.PathValue("environment"), input)
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
func (config Config) handleSaveWeKnoraConnection(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
if _, ok := requireOperationID(w, r); !ok {
return
}
var input weknoraconn.SaveInput
if err := decodeStrictJSON(r, &input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
return
}
if input.KeyAction != weknoraconn.KeyActionClear && strings.TrimSpace(input.APIKey) != "" &&
!weKnoraSecretTransportWithPrivateHTTP(config, r) {
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_secret_secure_transport_required",
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
})
return
}
view, err := config.WeKnoraConnections.Save(r.Context(), r.PathValue("environment"), input, actorFor(r))
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": view})
}