#19539: security: strengthen CSRF protection with SameSite cookies
size: XS
## Summary
- Enforce `SameSite=Strict` attribute on all `Set-Cookie` headers via response patching
- Return structured JSON error response on CSRF rejection instead of plain text
- Maintain existing Origin/Referer/Sec-Fetch-Site validation
## Security Impact
Adds defense-in-depth against CSRF by ensuring cookies are never sent on cross-site requests, even if the Origin/Referer checks are somehow bypassed.
## Test plan
- [x] Existing CSRF tests still pass (shouldRejectBrowserMutation)
- [ ] Verify SameSite=Strict is appended to Set-Cookie headers
- [ ] Verify JSON error response on CSRF rejection
<!-- greptile_comment -->
<h3>Greptile Summary</h3>
Adds `SameSite=Strict` to all cookies and converts CSRF rejection response from plain text to JSON. The `enforceSameSiteCookies` function monkey-patches the response's `setHeader` method to automatically append `SameSite=Strict` to any `Set-Cookie` headers that don't already have a `SameSite` attribute. This provides defense-in-depth against CSRF attacks by ensuring cookies are never sent on cross-site requests, complementing the existing Origin/Referer/Sec-Fetch-Site validation.
<h3>Confidence Score: 4/5</h3>
- This PR is safe to merge with minimal risk
- The changes implement defense-in-depth security improvements without breaking existing functionality. The `SameSite=Strict` enforcement is backward-compatible (only adds the attribute if missing), and the JSON error response is a minor API improvement. The monkey-patching approach is localized to each request's response object and is a standard pattern for Express middleware. Existing tests for `shouldRejectBrowserMutation` still pass, validating that core CSRF logic remains intact.
- No files require special attention
<sub>Last reviewed commit: 8e471a5</sub>
<!-- greptile_other_comments_section -->
<!-- /greptile_comment -->
Most Similar PRs
#23465: Gateway: strengthen Control UI security headers
by bmendonca3 · 2026-02-22
70.1%
#5649: fix(security): harden file permissions and header merging
by sfo2001 · 2026-01-31
69.7%
#16990: fix(media): strip auth headers on cross-origin redirect in download...
by AI-Reviewer-QS · 2026-02-15
69.5%
#14197: fix(security): harden browser API auth, token comparisons, and hook...
by leecarollyn-gif · 2026-02-11
69.2%
#19525: security: add SSRF validation for external URLs
by Mozzzaic · 2026-02-17
68.9%
#8305: fix(browser): add SSRF protection to browser navigation
by yubrew · 2026-02-03
68.8%
#21159: fix(security): harden data exposure controls
by novalis133 · 2026-02-19
67.9%
#11880: fix: guard decodeURIComponent against malformed percent-encoding in...
by Yida-Dev · 2026-02-08
67.8%
#6906: Add baseline HTTP security headers to gateway responses
by QuantumEdu · 2026-02-02
67.2%
#10745: feat: Security improvements and Windows compatibility fixes
by lluviaoscuradeldoce-design · 2026-02-06
66.8%