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}) }