Skip to content

Commit 2da8f6a

Browse files
committed
Redirect on bad CSRF instead of presenting bad page
The current CSRF handler is a bit harsh with bad CSRF tokens on webpages I think we can be a little kinder and redirect to base page with a flash error Signed-off-by: Andrew Thornton <[email protected]>
1 parent 5b94a07 commit 2da8f6a

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

modules/context/csrf.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"net/http"
2323
"time"
2424

25+
"code.gitea.io/gitea/modules/setting"
2526
"code.gitea.io/gitea/modules/web/middleware"
2627

2728
"github.com/unknwon/com"
@@ -266,7 +267,12 @@ func Validate(ctx *Context, x CSRF) {
266267
-1,
267268
x.GetCookiePath(),
268269
x.GetCookieDomain()) // FIXME: Do we need to set the Secure, httpOnly and SameSite values too?
269-
x.Error(ctx.Resp)
270+
if middleware.IsAPIPath(ctx.Req) {
271+
x.Error(ctx.Resp)
272+
return
273+
}
274+
ctx.Flash.Error(ctx.Tr("error.invalid_csrf"))
275+
ctx.Redirect(setting.AppSubURL + "/")
270276
}
271277
return
272278
}
@@ -277,10 +283,19 @@ func Validate(ctx *Context, x CSRF) {
277283
-1,
278284
x.GetCookiePath(),
279285
x.GetCookieDomain()) // FIXME: Do we need to set the Secure, httpOnly and SameSite values too?
280-
x.Error(ctx.Resp)
286+
if middleware.IsAPIPath(ctx.Req) {
287+
x.Error(ctx.Resp)
288+
return
289+
}
290+
ctx.Flash.Error(ctx.Tr("error.invalid_csrf"))
291+
ctx.Redirect(setting.AppSubURL + "/")
281292
}
282293
return
283294
}
284-
285-
http.Error(ctx.Resp, "Bad Request: no CSRF token present", http.StatusBadRequest)
295+
if middleware.IsAPIPath(ctx.Req) {
296+
http.Error(ctx.Resp, "Bad Request: no CSRF token present", http.StatusBadRequest)
297+
return
298+
}
299+
ctx.Flash.Error(ctx.Tr("error.missing_csrf"))
300+
ctx.Redirect(setting.AppSubURL + "/")
286301
}

options/locale/locale_en-US.ini

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ error404 = The page you are trying to reach either <strong>does not exist</stron
9696
[error]
9797
occurred = An error has occurred
9898
report_message = If you are sure this is a Gitea bug, please search for issue on <a href="https://github.com/go-gitea/gitea/issues">GitHub</a> and open new issue if necessary.
99+
missing_csrf = Bad Request: no CSRF token present
100+
invalid_csrf = Bad Request: Invalid CSRF token
99101

100102
[startpage]
101103
app_desc = A painless, self-hosted Git service

0 commit comments

Comments
 (0)