Skip to content

fix(middleware): invoke CSRFConfig.ErrorHandler on Sec-Fetch-Site rejections - #3251

Open
xgbtxy wants to merge 1 commit into
labstack:masterfrom
xgbtxy:fix/csrf-errorhandler-sec-fetch-site
Open

xgbtxy wants to merge 1 commit into
labstack:masterfrom
xgbtxy:fix/csrf-errorhandler-sec-fetch-site

Conversation

@xgbtxy

@xgbtxy xgbtxy commented Nov 26, 2026 •

Copy link
Copy Markdown

Summary

Invoke CSRFConfig.ErrorHandler when checkSecFetchSiteRequest rejects a request in the CSRF middleware (middleware/csrf.go), matching the legacy token validation error path.

Root Cause

In middleware/csrf.go, legacy token validation routes errors through config.ErrorHandler when configured:

if finalErr != nil {
	if config.ErrorHandler != nil {
		return config.ErrorHandler(c, finalErr)
	}
	return finalErr
}

However, the Sec-Fetch-Site check at the top of the middleware returned err directly without calling config.ErrorHandler:

allow, err := config.checkSecFetchSiteRequest(c)
if err != nil {
	return err
}

Because modern browsers send Sec-Fetch-Site headers by default, applications configuring CSRFConfig.ErrorHandler to return custom responses, record metrics, or redirect on CSRF failures never had ErrorHandler called for Sec-Fetch-Site: cross-site, Sec-Fetch-Site: same-site, or AllowSecFetchSiteFunc rejections.

Fix

  • Route non-nil errors from config.checkSecFetchSiteRequest(c) through config.ErrorHandler(c, err) when config.ErrorHandler != nil (middleware/csrf.go).
  • Expand TestCSRFErrorHandling in middleware/csrf_test.go into a table-driven test covering missing token, Sec-Fetch-Site: cross-site, Sec-Fetch-Site: same-site, and AllowSecFetchSiteFunc custom errors.

Verification

  • go test -race -v -count=1 ./middleware -run '^TestCSRF' (fails before the fix on all 3 Sec-Fetch-Site subtests; passes after the fix).
  • go test -race -count=1 ./middleware
  • go vet ./...

Summary by CodeRabbit

  • Bug Fixes
    • Errors encountered during cross-site request checks are now handled by your configured error handler, so its response is returned consistently. If no custom error handler is configured, the original error is returned. Existing behavior for token-validation errors remains unchanged.

…ections

Legacy token validation in CSRFConfig.ToMiddleware routes validation
errors through config.ErrorHandler when configured, but the
Sec-Fetch-Site check returned checkSecFetchSiteRequest errors directly,
bypassing CSRFConfig.ErrorHandler for cross-site, same-site, and
AllowSecFetchSiteFunc rejections.

Invoke config.ErrorHandler(c, err) on Sec-Fetch-Site rejections when
configured, and expand TestCSRFErrorHandling in middleware/csrf_test.go
to cover Sec-Fetch-Site cross-site, same-site, and custom callback
errors.
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Changes: CSRF error handling

Layer / File(s) Summary
Forward Sec-Fetch-Site check errors
middleware/csrf.go, middleware/csrf_test.go
The middleware passes Sec-Fetch-Site check errors to ErrorHandler when configured. Tests verify the forwarded error, teapot response, and response body for missing tokens, site rejections, and a callback error.

Suggested reviewers: aldas, mojixcoder

Change: Bug fix

Merge Risk: Minimal · up to 7679d

Applications with a custom CSRF error handler will now see Sec-Fetch-Site rejections go through that handler, as they already do for token failures. Behavior without a handler is unchanged, and the added tests cover the new routing. No merge-blocking risk was found.

Security architecture risk: Minimal · up to 7679d

Applications with a custom CSRF error handler can now customize responses to Fetch Metadata rejections. The middleware still stops rejected requests before they reach the protected handler, and behavior is unchanged when no custom handler is configured.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly reachable application code is limited to configured CSRF error handlers on middleware instances that return a Fetch Metadata error. Those handlers receive the original request context and rejection error. Their deployment reach and side effects are not established.

Trust Boundaries and Controls

  • observed — Request headers and method still feed the same Fetch Metadata decision before the error handler runs. A non-nil check error ends the middleware branch regardless of the error handler's return value; the branch does not invoke the protected handler or issue a CSRF cookie.
Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 042a1a16-ac18-486e-9876-68ce2359866f
Commits

Reviewing files that changed from the base of the PR and between 59aacdd and 7679d0a.

Files selected for processing: 2

  • middleware/csrf.go
  • middleware/csrf_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant