fix(web): clean up form data parsing (#40558)

`FormStrings` only parsed the form with `ParseMultipartForm`, which
returns `http.ErrNotMultipart` for urlencoded bodies, so it returned nil
unless something else had parsed the form first. The CSRF check used to
do that, and since it was removed the "Associate accessible OIDs" button
on the LFS pointers page sends no OIDs and fails with a 500. The global
multipart parse in the web and API contexts is also removed, form
helpers now parse on demand.

Fixes: https://github.com/go-gitea/gitea/issues/40551

Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
authored and GitHub committed 2026-11-27 06:15:41 +00:00
1 parent c6bdd3efd6
commit 63b2af6f37
19 files changed
+80 -113

No files matched your search

+1 -1
View File
@@ -271,7 +271,7 @@ func loadServerFrom(rootCfg ConfigProvider) {
appTempPathInternal, _ = filepath.Abs(appTempPathInternal)
}
// TODO: GOLANG-HTTP-TMPDIR: Some Golang packages (like "http") use os.TempDir() to create temporary files when uploading files.
// HINT: GOLANG-HTTP-TMPDIR: Some Golang packages (like "http") use os.TempDir() to create temporary files when uploading files.
// So ideally we should set the TMPDIR environment variable to make them use our managed temp directory.
// But there is no clear place to set it currently, for example: when running "install" page, the AppDataPath is not ready yet, then AppDataTempDir won't work
+2 -2
View File
@@ -45,7 +45,7 @@ const (
ErrInclude = "IncludeError"
)
const multipartMaxMemory = 10 * 1024 * 1024
var ParseMultipartFormMaxMemory int64 = 10 * 1024 * 1024
type (
Errors []Error
@@ -218,7 +218,7 @@ func (b *Binder) bindForm(req *http.Request, formStruct any) (errs Errors) {
}
func (b *Binder) bindMultipartForm(req *http.Request, formStruct any) (errs Errors) {
if err := req.ParseMultipartForm(multipartMaxMemory); err != nil {
if err := req.ParseMultipartForm(ParseMultipartFormMaxMemory); err != nil {
errs.addDeserializationError(err)
}
if req.MultipartForm != nil {
+11 -10
View File
@@ -25,7 +25,6 @@ func RouterMockPoint(pointName string) func(next http.Handler) http.Handler {
if !setting.IsInTesting {
return nil
}
routeMockPoints[pointName] = nil
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h := routeMockPoints[pointName]; h != nil {
@@ -37,6 +36,15 @@ func RouterMockPoint(pointName string) func(next http.Handler) http.Handler {
}
}
func RouterMockPointCall(pointName string, w http.ResponseWriter, r *http.Request) {
if !setting.IsInTesting {
return
}
if h := routeMockPoints[pointName]; h != nil {
h(nil).ServeHTTP(w, r)
}
}
// RouteMock uses the registered mock point to mock the route execution, example:
//
// defer web.RouteMockReset()
@@ -47,19 +55,12 @@ func RouterMockPoint(pointName string) func(next http.Handler) http.Handler {
// Then the mock function will be executed as a middleware at the mock point.
// It only takes effect in testing mode (setting.IsInTesting == true).
func RouteMock(pointName string, h any) func() {
if _, ok := routeMockPoints[pointName]; !ok {
panic("route mock point not found: " + pointName)
}
old := routeMockPoints[pointName]
routeMockPoints[pointName] = toHandlerProvider(h)
return func() {
routeMockPoints[pointName] = old
}
return func() { routeMockPoints[pointName] = old }
}
// RouteMockReset resets all mock points (no mock anymore)
func RouteMockReset() {
for k := range routeMockPoints {
routeMockPoints[k] = nil // keep the keys because RouteMock will check the keys to make sure no misspelling
}
clear(routeMockPoints)
}
+1 -4
View File
@@ -142,11 +142,8 @@ func UploadPackageFile(ctx *context.Context) {
return
}
// Ensure ctx.Req.Form exists.
_ = ctx.Req.ParseForm()
var homepageURL string
projectURLs := ctx.Req.Form["project_urls"]
projectURLs := ctx.FormStrings("project_urls")
for _, purl := range projectURLs {
label, url, found := strings.Cut(purl, ",")
if !found {
+2 -3
View File
@@ -134,9 +134,8 @@ func validateConfigKeyValue(dynKey, input string) error {
}
func ChangeConfig(ctx *context.Context) {
_ = ctx.Req.ParseForm()
configKeys := ctx.Req.Form["key"]
configValues := ctx.Req.Form["value"]
configKeys := ctx.FormStrings("key")
configValues := ctx.FormStrings("value")
configSettings := map[string]string{}
loop:
for i, key := range configKeys {
+1 -1
View File
@@ -78,7 +78,7 @@ func SignInOAuth(ctx *context.Context) {
func SignInOAuthCallback(ctx *context.Context) {
if ctx.Req.FormValue("error") != "" {
var errorKeyValues []string
for k, vv := range ctx.Req.Form {
for k, vv := range ctx.FormValues() {
for _, v := range vv {
errorKeyValues = append(errorKeyValues, fmt.Sprintf("%s = %s", html.EscapeString(k), html.EscapeString(v)))
}
+6 -10
View File
@@ -46,12 +46,12 @@ func List(ctx *context.Context) {
ctx.HTML(http.StatusOK, "devtest/devtest-list")
}
func buildMockResponse(prefix string, ctx *context.Context) string {
return prefix + ctx.Req.Method + " " + ctx.Req.RequestURI + "\n" + "Request Form: " + ctx.FormValues().Encode()
}
func FetchActionTest(ctx *context.Context) {
_ = ctx.Req.ParseForm()
ctx.Flash.Info("fetch action: " + ctx.Req.Method + " " + ctx.Req.RequestURI + "\n" +
"Form: " + ctx.Req.Form.Encode() + "\n" +
"PostForm: " + ctx.Req.PostForm.Encode(),
)
ctx.Flash.Info(buildMockResponse("Fetch Action: ", ctx))
time.Sleep(2 * time.Second)
ctx.JSONRedirect("")
}
@@ -315,11 +315,7 @@ func prepareMockDataUnicodeEscape(ctx *context.Context) {
func TmplCommon(ctx *context.Context) {
prepareMockData(ctx)
if ctx.Req.Method == http.MethodPost && ctx.FormBool("mock_response_delay") {
ctx.Flash.Info("form submit: "+ctx.Req.Method+" "+ctx.Req.RequestURI+"\n"+
"Form: "+ctx.Req.Form.Encode()+"\n"+
"PostForm: "+ctx.Req.PostForm.Encode(),
true,
)
ctx.Flash.Info(buildMockResponse("Form Submit: ", ctx), true)
time.Sleep(2 * time.Second)
}
ctx.HTML(http.StatusOK, templates.TplName("devtest"+path.Clean("/"+ctx.PathParam("sub"))))
+1 -7
View File
@@ -159,13 +159,7 @@ func Repos(ctx *context.Context) {
ownerID = ctx.Doer.ID
}
onlyShowRelevant := setting.UI.OnlyShowRelevantRepos
_ = ctx.Req.ParseForm() // parse the form first, to prepare the ctx.Req.Form field
if len(ctx.Req.Form[relevantReposOnlyParam]) != 0 {
onlyShowRelevant = ctx.FormBool(relevantReposOnlyParam)
}
onlyShowRelevant := ctx.FormBool(relevantReposOnlyParam, setting.UI.OnlyShowRelevantRepos)
RenderRepoSearch(ctx, &RepoSearchOptions{
PageSize: setting.UI.ExplorePagingNum,
OwnerID: ownerID,
+4 -6
View File
@@ -12,9 +12,9 @@ import (
"gitea.dev/models/unit"
"gitea.dev/modules/httpcache"
"gitea.dev/modules/httplib"
"gitea.dev/modules/log"
"gitea.dev/modules/setting"
"gitea.dev/modules/storage"
"gitea.dev/modules/web"
"gitea.dev/services/attachment"
"gitea.dev/services/context"
"gitea.dev/services/context/upload"
@@ -49,7 +49,7 @@ func uploadAttachment(ctx *context.Context, repoID int64, uploadFunc attachment.
return
}
file, header, err := ctx.Req.FormFile("file")
file, header, err := ctx.FormFile("file")
if err != nil {
ctx.ServerErrorAuto(err)
return
@@ -71,10 +71,8 @@ func uploadAttachment(ctx *context.Context, repoID int64, uploadFunc attachment.
return
}
log.Trace("New attachment uploaded: %s", attach.UUID)
ctx.JSON(http.StatusOK, map[string]string{
"uuid": attach.UUID,
})
ctx.JSON(http.StatusOK, map[string]string{"uuid": attach.UUID})
web.RouterMockPointCall("mockpoint-attachment-uploaded", ctx.Resp, ctx.Req)
}
func DeletePendingAttachment(ctx *context.Context) {
+1 -1
View File
@@ -650,7 +650,7 @@ func EditReleasePost(ctx *context.Context) {
editAttachments := make(map[string]string) // uuid -> new name
if setting.Attachment.Enabled {
addAttachmentUUIDs = form.Files
for k, v := range ctx.Req.Form {
for k, v := range ctx.FormValues() {
if strings.HasPrefix(k, delPrefix) && v[0] == "true" {
delAttachmentUUIDs = append(delAttachmentUUIDs, k[len(delPrefix):])
} else if strings.HasPrefix(k, editPrefix) {
+1 -2
View File
@@ -70,10 +70,9 @@ func CreateAccessToken(ctx *context.Context, owner *user_model.User) {
return
}
_ = ctx.Req.ParseForm()
var scopeNames []string
const accessTokenScopePrefix = "scope-"
for k, v := range ctx.Req.Form {
for k, v := range ctx.FormValues() {
if strings.HasPrefix(k, accessTokenScopePrefix) {
scopeNames = append(scopeNames, v...)
}
+12 -11
View File
@@ -81,18 +81,19 @@ func (o *OAuth2) Name() string {
// parseToken returns the token from request, and a boolean value
// representing whether the token exists or not
func parseToken(req *http.Request) (string, bool) {
_ = req.ParseForm()
if !setting.DisableQueryAuthToken {
// Check token.
if token := req.Form.Get("token"); token != "" {
return token, true
if strings.Contains(req.URL.RawQuery, "token=") {
// only parse the legacy query parameters if the query parameters contain "token=" (also includes "access_token=")
queryParams := req.URL.Query()
if !setting.DisableQueryAuthToken {
if token := queryParams.Get("token"); token != "" {
return token, true
}
if token := queryParams.Get("access_token"); token != "" {
return token, true
}
} else if queryParams.Get("token") != "" || queryParams.Get("access_token") != "" {
log.Warn("API token sent in query string but DISABLE_QUERY_AUTH_TOKEN=true")
}
// Check access token.
if token := req.Form.Get("access_token"); token != "" {
return token, true
}
} else if req.Form.Get("token") != "" || req.Form.Get("access_token") != "" {
log.Warn("API token sent in query string but DISABLE_QUERY_AUTH_TOKEN=true")
}
// check header token
-8
View File
@@ -193,14 +193,6 @@ func APIContexter() func(http.Handler) http.Handler {
}
ctx.SetContextValue(apiContextKey, ctx)
httplib.MarkRequestSupportPublicURL(ctx)
// FIXME: GLOBAL-PARSE-FORM: see more details in another FIXME comment
if ctx.Req.Method == http.MethodPost && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
if !ctx.ParseMultipartForm() {
return
}
}
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{})
next.ServeHTTP(ctx.Resp, ctx.Req)
})
-17
View File
@@ -4,7 +4,6 @@
package context
import (
"errors"
"fmt"
"html/template"
"io"
@@ -44,22 +43,6 @@ type Base struct {
Locale translation.Locale
}
var ParseMultipartFormMaxMemory = int64(32 << 20)
func (b *Base) ParseMultipartForm() bool {
err := b.Req.ParseMultipartForm(ParseMultipartFormMaxMemory)
if err != nil {
// TODO: all errors caused by client side should be ignored (connection closed).
if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
// Errors caused by server side (disk full) should be logged.
log.Error("Failed to parse request multipart form for %s: %v", b.Req.RequestURI, err)
}
b.HTTPError(http.StatusInternalServerError, "failed to parse request multipart form")
return false
}
return true
}
// AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header
func (b *Base) AppendAccessControlExposeHeaders(names ...string) {
val := b.RespHeader().Get("Access-Control-Expose-Headers")
+23 -14
View File
@@ -4,36 +4,35 @@
package context
import (
"mime/multipart"
"net/url"
"strconv"
"strings"
"gitea.dev/modules/base"
"gitea.dev/modules/optional"
"gitea.dev/modules/util"
"gitea.dev/modules/web/binding"
)
// FormString returns the first value matching the provided key in the form as a string
// It works the same as http.Request.FormValue:
// try urlencoded request body first, then query string, then multipart form body
func (b *Base) FormString(key string, def ...string) string {
s := b.Req.FormValue(key)
if s == "" {
s = util.OptionalArg(def)
if v := b.FormValues().Get(key); v != "" {
return v
}
return s
return util.OptionalArg(def)
}
// FormStrings returns a values for the key in the form (including query parameters), similar to FormString
func (b *Base) FormStrings(key string) []string {
if b.Req.Form == nil {
if err := b.Req.ParseMultipartForm(32 << 20); err != nil {
return nil
}
}
if v, ok := b.Req.Form[key]; ok {
return v
}
return nil
return b.FormValues()[key]
}
func (b *Base) FormValues() url.Values {
_ = b.Req.ParseMultipartForm(binding.ParseMultipartFormMaxMemory) // the same logic as http.Request.FormValue
return b.Req.Form
}
func (b *Base) FormStringInt64s(key string) []int64 {
@@ -41,6 +40,13 @@ func (b *Base) FormStringInt64s(key string) []int64 {
return vals
}
func (b *Base) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
if err := b.Req.ParseMultipartForm(binding.ParseMultipartFormMaxMemory); err != nil {
return nil, nil, err
}
return b.Req.FormFile(key)
}
// FormTrim returns the first value for the provided key in the form as a space trimmed string
func (b *Base) FormTrim(key string) string {
return strings.TrimSpace(b.Req.FormValue(key))
@@ -59,8 +65,11 @@ func (b *Base) FormInt64(key string) int64 {
}
// FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
func (b *Base) FormBool(key string) bool {
func (b *Base) FormBool(key string, def ...bool) bool {
s := b.Req.FormValue(key)
if s == "" {
return util.OptionalArg(def)
}
v, _ := strconv.ParseBool(s)
v = v || strings.EqualFold(s, "on")
return v
+9
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"gitea.dev/modules/setting"
@@ -29,3 +30,11 @@ func TestRedirect(t *testing.T) {
assert.JSONEq(t, `{"redirect":"/other"}`, resp.Body.String())
assert.Equal(t, http.StatusOK, resp.Code)
}
func TestFormStrings(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/?q=1", strings.NewReader("oid=a&oid=b"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
b := NewBaseContextForTest(t, httptest.NewRecorder(), req)
assert.Equal(t, []string{"a", "b"}, b.FormStrings("oid"))
assert.Equal(t, []string{"1"}, b.FormStrings("q"))
}
-10
View File
@@ -171,16 +171,6 @@ func Contexter() func(next http.Handler) http.Handler {
}
})
// FIXME: GLOBAL-PARSE-FORM: this ParseMultipartForm was used for parsing the csrf token from multipart/form-data
// We have dropped the csrf token, so ideally this global ParseMultipartForm should be removed.
// When removing this, we need to avoid regressions in the handler functions because Golang's http framework is quite fragile
// and developers sometimes need to manually parse the form before accessing some values.
if ctx.Req.Method == http.MethodPost && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
if !ctx.ParseMultipartForm() {
return
}
}
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{})
ctx.Data["SystemConfig"] = setting.Config()
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func (ctx *Context) UploadStream() (rd io.ReadCloser, needToClose bool, err error) {
contentType := strings.ToLower(ctx.Req.Header.Get("Content-Type"))
if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") || strings.HasPrefix(contentType, "multipart/form-data") {
if err := ctx.Req.ParseMultipartForm(32 << 20); err != nil {
if err := ctx.Req.ParseMultipartForm(32 * 1024 * 1024); err != nil {
return nil, false, err
}
if ctx.Req.MultipartForm.File == nil {
+4 -5
View File
@@ -19,8 +19,7 @@ import (
"gitea.dev/modules/storage"
"gitea.dev/modules/test"
"gitea.dev/modules/web"
route_web "gitea.dev/routers/web"
"gitea.dev/services/context"
"gitea.dev/modules/web/binding"
"gitea.dev/tests"
"github.com/stretchr/testify/assert"
@@ -171,14 +170,14 @@ func TestAttachments(t *testing.T) {
func testUploadAttachmentDeleteTemp(t *testing.T) {
session := loginUser(t, "user2")
countTmpFile := func() int {
// TODO: GOLANG-HTTP-TMPDIR: Golang saves the uploaded file to os.TempDir() when it exceeds the max memory limit.
// HINT: GOLANG-HTTP-TMPDIR: Golang saves the uploaded file to os.TempDir() when it exceeds the max memory limit.
files, err := fs.Glob(os.DirFS(os.TempDir()), "multipart-*") //nolint:usetesting // Golang's "http" package's behavior
require.NoError(t, err)
return len(files)
}
var tmpFileCountDuringUpload int
defer test.MockVariableValue(&context.ParseMultipartFormMaxMemory, 1)()
defer web.RouteMock(route_web.RouterMockPointBeforeWebRoutes, func(resp http.ResponseWriter, req *http.Request) {
defer test.MockVariableValue(&binding.ParseMultipartFormMaxMemory, 1)()
defer web.RouteMock("mockpoint-attachment-uploaded", func(http.ResponseWriter, *http.Request) {
tmpFileCountDuringUpload = countTmpFile()
})()
_ = testCreateIssueAttachment(t, session, "/user2/repo1", "image.png", testGeneratePngBytes(), http.StatusOK)