package httpapi import ( "context" "errors" "knowledge-governance/internal/ppauth" "net/http" "net/url" "time" ) func credentialAdmin(w http.ResponseWriter, r *http.Request, action string) bool { w.Header().Set("Cache-Control", "no-store") identity, ok := requireSessionIdentity(w, r) if !ok { return false } if identity.Role != roleAdmin { writeJSON(w, 403, map[string]string{"error": "需要管理员身份管理来源凭据"}) return false } if r.Method != "GET" { originOK := true if raw := r.Header.Get("Origin"); raw != "" { u, err := url.Parse(raw) originOK = err == nil && u.Host == r.Host && (u.Scheme == "http" || u.Scheme == "https") } if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != action { writeJSON(w, 403, map[string]string{"error": "请从本平台的数据源配置页操作"}) return false } } return true } func writePPError(w http.ResponseWriter, err error) { status := http.StatusBadRequest if errors.Is(err, ppauth.ErrConflict) { status = http.StatusConflict } writeJSON(w, status, map[string]string{"error": err.Error()}) } func registerPPConnectionRoutes(mux *http.ServeMux, config Config) { for _, pattern := range []string{"GET /api/v1/pp-connection", "PUT /api/v1/pp-connection", "POST /api/v1/pp-connection/test"} { mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { if !credentialAdmin(w, r, "pp-connection") { return } if config.PPConnection == nil { writeJSON(w, 503, map[string]string{"error": "PP 配置服务未接通,请联系管理员"}) return } if r.Method == "GET" { v, err := config.PPConnection.View() if err != nil { writeJSON(w, 503, map[string]string{"error": err.Error()}) return } writeJSON(w, 200, map[string]any{"data": v}) return } var draft ppauth.Draft r.Body = http.MaxBytesReader(w, r.Body, 16384) if decodeJSONStrict(r, &draft) != nil { writeJSON(w, 400, map[string]string{"error": "PP 配置请求格式不正确"}) return } ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second) defer cancel() if r.Method == "POST" { result, err := config.PPConnection.Test(ctx, draft, actorFor(r)) if err != nil { writePPError(w, err) return } writeJSON(w, 200, map[string]any{"data": result}) return } result, err := config.PPConnection.Save(ctx, draft, actorFor(r)) if err != nil { status := 400 if errors.Is(err, ppauth.ErrConflict) { status = 409 } if errors.Is(err, ppauth.ErrRejected) { status = 422 } writeJSON(w, status, map[string]any{"error": err.Error(), "data": result}) return } writeJSON(w, 200, map[string]any{"data": result}) }) } }