diff --git a/modules/setting/server.go b/modules/setting/server.go index 525dac067d4..e1b62418270 100644 --- a/modules/setting/server.go +++ b/modules/setting/server.go @@ -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 diff --git a/modules/web/binding/binding.go b/modules/web/binding/binding.go index 857b1f1b368..d5662fb6da5 100644 --- a/modules/web/binding/binding.go +++ b/modules/web/binding/binding.go @@ -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 { diff --git a/modules/web/routemock.go b/modules/web/routemock.go index bbb8021193f..0acadb54d7f 100644 --- a/modules/web/routemock.go +++ b/modules/web/routemock.go @@ -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) } diff --git a/routers/api/packages/pypi/pypi.go b/routers/api/packages/pypi/pypi.go index 25558f58bb8..b07e89b35f7 100644 --- a/routers/api/packages/pypi/pypi.go +++ b/routers/api/packages/pypi/pypi.go @@ -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 { diff --git a/routers/web/admin/config.go b/routers/web/admin/config.go index e979a230762..20bf2618af5 100644 --- a/routers/web/admin/config.go +++ b/routers/web/admin/config.go @@ -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 { diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index dd4154b0180..ecad27c350c 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -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))) } diff --git a/routers/web/devtest/devtest.go b/routers/web/devtest/devtest.go index 24c953d9203..7df9e5b70ca 100644 --- a/routers/web/devtest/devtest.go +++ b/routers/web/devtest/devtest.go @@ -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")))) diff --git a/routers/web/explore/repo.go b/routers/web/explore/repo.go index a8325aab071..bbaa59a5290 100644 --- a/routers/web/explore/repo.go +++ b/routers/web/explore/repo.go @@ -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, diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index a0a0f44762f..42a63cea3f6 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -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) { diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index 9d3c63f2713..3da5f975a06 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -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) { diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index 512cd69c6b3..3ebbc8500d5 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -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...) } diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index 7ea7bb3e6f5..da1d3764018 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -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 diff --git a/services/context/api.go b/services/context/api.go index 5f69a804bbe..b7d352a5a5f 100644 --- a/services/context/api.go +++ b/services/context/api.go @@ -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) }) diff --git a/services/context/base.go b/services/context/base.go index e07236ad34b..9baa4090550 100644 --- a/services/context/base.go +++ b/services/context/base.go @@ -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") diff --git a/services/context/base_form.go b/services/context/base_form.go index 840a78f117f..3db68c061b2 100644 --- a/services/context/base_form.go +++ b/services/context/base_form.go @@ -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 diff --git a/services/context/base_test.go b/services/context/base_test.go index a4c8f24479f..7b50311f013 100644 --- a/services/context/base_test.go +++ b/services/context/base_test.go @@ -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")) +} diff --git a/services/context/context.go b/services/context/context.go index 48a0deaa396..90b9c522982 100644 --- a/services/context/context.go +++ b/services/context/context.go @@ -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() diff --git a/services/context/context_request.go b/services/context/context_request.go index 984b9ac793e..108b923b95c 100644 --- a/services/context/context_request.go +++ b/services/context/context_request.go @@ -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 { diff --git a/tests/integration/attachment_test.go b/tests/integration/attachment_test.go index 3f61029163b..3100e016bd1 100644 --- a/tests/integration/attachment_test.go +++ b/tests/integration/attachment_test.go @@ -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)