fix: validate CSRF on non-safe methods (#9071)

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/9071
Reviewed-by: 0ko <0ko@noreply.codeberg.org>
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
This commit is contained in:
Earl Warren 2025-08-30 13:13:29 +02:00
commit 608f9ee8e6
2 changed files with 23 additions and 1 deletions

View file

@ -192,7 +192,8 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.Cont
return
}
if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" {
safeMethod := ctx.Req.Method == "GET" || ctx.Req.Method == "HEAD" || ctx.Req.Method == "OPTIONS"
if !options.SignOutRequired && !options.DisableCSRF && !safeMethod {
ctx.Csrf.Validate(ctx)
if ctx.Written() {
return

View file

@ -1,4 +1,5 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// Copyright 2025 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
@ -32,3 +33,23 @@ func TestCsrfProtection(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
}
func TestCSRFSafeMethods(t *testing.T) {
defer tests.PrepareTestEnv(t)()
t.Run("DELETE", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
session := loginUser(t, "user2")
resp := session.MakeRequest(t, NewRequest(t, "DELETE", "/user2/repo1/projects/1/2"), http.StatusBadRequest)
assert.Equal(t, "Invalid CSRF token.\n", resp.Body.String())
})
t.Run("PUT", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
session := loginUser(t, "user2")
resp := session.MakeRequest(t, NewRequest(t, "PUT", "/user2/repo1/projects/1/2"), http.StatusBadRequest)
assert.Equal(t, "Invalid CSRF token.\n", resp.Body.String())
})
}