package httpapi import ( "io" "net/http" "net/url" "sea-vhost/internal/isolation" "strconv" "strings" ) func (s *Server) phpMyAdmin(w http.ResponseWriter, r *http.Request) { id, _ := projectID(r) base := "/api/v1/projects/" + strconv.FormatUint(id, 10) + "/database-admin/" relative := r.PathValue("pmaPath") if r.Method != "GET" && r.Method != "POST" && r.Method != "HEAD" { writeError(w, 405, "不支持的请求方法") return } if s.cfg.ManagementDomain == "" { writeError(w, 503, "未设置管理域名") return } body, e := io.ReadAll(io.LimitReader(r.Body, (2<<20)+1)) if e != nil || len(body) > 2<<20 { writeError(w, 413, "phpMyAdmin 单次请求上限为 2 MiB") return } var cookies []string for _, c := range r.Cookies() { if !strings.HasPrefix(strings.ToLower(c.Name), "sea_") { cookies = append(cookies, c.Name+"="+c.Value) } } out, e := s.projects.PHPMyAdmin(r.Context(), currentUser(r), id, isolation.PHPMyAdminRequest{Method: r.Method, Path: relative, Query: r.URL.RawQuery, Body: body, Cookie: strings.Join(cookies, "; "), ContentType: r.Header.Get("Content-Type"), BaseURI: "https://" + s.cfg.ManagementDomain + base}) if e != nil { writeError(w, 502, "phpMyAdmin 暂不可用,请检查节点上的 phpMyAdmin / PHP 安装") return } for _, name := range []string{"Content-Type", "Content-Disposition", "Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP"} { if value := out.Header.Get(name); value != "" { w.Header().Set(name, value) } } for _, cookie := range (&http.Response{Header: out.Header}).Cookies() { if strings.HasPrefix(strings.ToLower(cookie.Name), "sea_") { continue } cookie.Domain = "" cookie.Path = base cookie.Secure = true cookie.HttpOnly = true cookie.SameSite = http.SameSiteStrictMode http.SetCookie(w, cookie) } if location := out.Header.Get("Location"); location != "" { u, e := url.Parse(location) if e != nil || u.User != nil || (u.Host != "" && !strings.EqualFold(u.Host, s.cfg.ManagementDomain)) || (u.Scheme != "" && u.Scheme != "https") { writeError(w, 502, "phpMyAdmin 返回了无效跳转") return } if u.IsAbs() || strings.HasPrefix(u.Path, "/") { if !strings.HasPrefix(u.Path, base) { writeError(w, 502, "phpMyAdmin 跳转超出数据库管理范围") return } } else { u.Path = base + strings.TrimPrefix(u.Path, "./") } w.Header().Set("Location", u.String()) } if pmaNeedsAudit(r) { u := currentUser(r) s.store.Log(r.Context(), u.TenantID, u.ID, "manage", "database", strconv.FormatUint(id, 10), requestClientIP(r), out.Status < 400, "使用 phpMyAdmin 管理主机数据库") } w.WriteHeader(out.Status) if r.Method != "HEAD" { _, _ = w.Write(out.Body) } } func pmaNeedsAudit(r *http.Request) bool { if r.Method != http.MethodPost { return false } // These are phpMyAdmin's automatic UI preferences/tree requests. Unknown // routes, SQL execution, imports and other POSTs remain auditable. switch r.URL.Query().Get("route") { case "/config/get", "/config/set", "/navigation": return false } return true }