Fix CSRF middleware not setting token when Sec-Fetch-Site passes #2893
+135
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #2874
When
checkSecFetchSiteRequest()returns(true, nil)— e.g. for direct URL navigation whereSec-Fetch-Site: none, or same-origin requests — the CSRF middleware immediately callsreturn next(c)without:c.Set(config.ContextKey, token)Vary: Cookieresponse headerThis breaks all server-rendered forms that use
c.Get("csrf")to embed a CSRF token in HTML for subsequent POST requests. The bug is triggered by every modern browser during direct navigation (typing a URL, clicking a bookmark, or following an external link), since browsers automatically sendSec-Fetch-Site: nonein these scenarios.Changes
middleware/csrf.go: Extract token generation and cookie/context setting into asetTokenInContexthelper closure, and call it in theSec-Fetch-Siteallow path before callingnext(c). The existing legacy token path remains unchanged.middleware/csrf_test.go:expectCookieContainsassertion to the existingSecFetchSite=same-origintest caseSec-Fetch-Site: noneandsame-originGET requestsTestCSRF_SecFetchSiteSetsTokenInContextregression test that verifies the token is accessible in context, the cookie is set, theVaryheader is correct, and existing cookie tokens are reusedTest plan
go test ./middleware/ -run TestCSRF -v)go test -race ./...)🤖 Generated with Claude Code