Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 fix: CSRF Cookie is removed when using Proxy Middleware #3390

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Apr 2, 2025

Description

This update introduces a new test, Test_CSRF_With_Proxy_Middleware, to ensure that the CSRF cookie is correctly set even when requests are handled by the proxy middleware. Additionally, the CSRF middleware logic has been adjusted to update the CSRF cookie after the next handler is executed, improving its reliability in proxy scenarios.

Fixes #3387

Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Walkthrough

The changes update the CSRF middleware to capture errors using a new err variable and to store the CSRF token in the context before proceeding with the middleware chain. A conditional now checks the token after processing and, if valid, updates the CSRF cookie and sets the Vary header. Additionally, new test functions have been introduced to verify that this middleware correctly maintains CSRF protection when used behind a proxy, ensuring that both the CSRF and session cookies are set appropriately.

Changes

File(s) Change Summary
middleware/csrf/csrf.go Added a new err variable for better error capturing; the token is stored in context before calling c.Next(), and the middleware now conditionally checks and updates the CSRF cookie and Vary header based on the token's existence.
middleware/csrf/csrf_test.go Introduced the Test_CSRF_With_Proxy_Middleware and Test_CSRF_Custom_CookieName_With_Proxy functions to test the middleware’s behavior in proxy scenarios, ensuring that the CSRF and session cookies are set and valid after processing, with proper response status verification.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CSRF_Middleware
    participant Next_Middleware
    participant Proxy_Handler
    participant Target_Server

    Client->>CSRF_Middleware: Sends request with potential token
    CSRF_Middleware->>CSRF_Middleware: Store token in context
    CSRF_Middleware->>Next_Middleware: Call c.Next()
    Next_Middleware-->>CSRF_Middleware: Return control (token now in context)
    CSRF_Middleware-->>CSRF_Middleware: Check token & update CSRF cookie, set Vary header
    alt Proxy scenario
        CSRF_Middleware->>Proxy_Handler: Forward request
        Proxy_Handler->>Target_Server: Proxy request
        Target_Server-->>Proxy_Handler: Return OK response
        Proxy_Handler-->>CSRF_Middleware: Pass response back
    end
    CSRF_Middleware->>Client: Returns response, with captured error if any
Loading

Poem

I’m hopping through code with a joyful beat,
Updating tokens so error-free and neat,
Cookies now dance in the header’s light,
As tests confirm everything’s right.
With every change, my heart does leap,
A rabbit’s cheer for progress deep!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between 713cc98 and d304c36.

📒 Files selected for processing (1)
  • middleware/csrf/csrf.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/csrf/csrf.go

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Apr 2, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.95%. Comparing base (5515703) to head (0fa9a31).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3390      +/-   ##
==========================================
+ Coverage   83.93%   83.95%   +0.01%     
==========================================
  Files         119      119              
  Lines       11904    11914      +10     
==========================================
+ Hits         9992    10002      +10     
  Misses       1484     1484              
  Partials      428      428              
Flag Coverage Δ
unittests 83.95% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JIeJaitt JIeJaitt marked this pull request as ready for review April 2, 2025 09:51
@JIeJaitt JIeJaitt requested a review from a team as a code owner April 2, 2025 09:51
@gaby gaby changed the title 🔥 Feature: Add CSRF support for proxy middleware 🐛 fix: CSRF Cookie is removed when using Proxy Middleware Apr 2, 2025
@gaby gaby requested a review from Copilot April 2, 2025 12:00
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes an issue where the CSRF cookie was removed when using the proxy middleware by updating the CSRF middleware logic and adding a dedicated test.

  • Introduces Test_CSRF_With_Proxy_Middleware to verify that the CSRF cookie is correctly set after proxy handling.
  • Adjusts the CSRF middleware to store the token before calling the next middleware and updates the cookie after c.Next() returns.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
middleware/csrf/csrf_test.go Adds a new test to verify proper CSRF cookie behavior when using the proxy middleware.
middleware/csrf/csrf.go Modifies the CSRF middleware to update the cookie after the next handler returns.

// Store the token in the context
c.Locals(tokenKey, token)
// Retrieve the final token from the context, if it was set.
finalToken, ok := c.Locals(tokenKey).(string)
Copy link
Preview

Copilot AI Apr 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider checking if err is non-nil immediately after c.Next() before updating the CSRF cookie with the final token. This may prevent unintended cookie updates when subsequent middleware fails.

Copilot is powered by AI, so mistakes are possible. Review output carefully before use.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JIeJaitt This is probably needed

Copy link
Contributor Author

@JIeJaitt JIeJaitt Apr 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gaby The logic of the code now disregards unexpected cookie updates on subsequent middleware failures, and I tried something like the following:

		// Execute the next middleware or handler in the stack.
		err = c.Next()
		// If the next handler returned an error, return it immediately.
		// Do not proceed to update the CSRF cookie if the request failed downstream.
		if err != nil {
			return err
		}

		// Retrieve the final token from the context, if it was set.
		finalToken, ok := c.Locals(tokenKey).(string)
		// Check if the token exists and is not empty.
		if ok && finalToken != "" { // Ensure token exists
			// Update the CSRF cookie in the response with the final token.
			updateCSRFCookie(c, cfg, finalToken)

			// Add the Vary: Cookie header to indicate that the response may differ
			// based on the Cookie header, which is important for caching mechanisms.
			// Tell the browser that a new header value is generated
			c.Vary(fiber.HeaderCookie)
		}

		// Return any error that occurred during the execution of the next handlers.
		// Continue stack
		return err

image

Do not proceed to update the CSRF cookie if the request failed downstream. Will result in a large number of errors in existing unitary functions, Such an approach may require careful consideration

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To summarize, I'm going to backtrack on the handling of err. If we need to change the err logic here, we should open an additional separate issue

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah remove it. Try adding a route that returns an error and see if the response still has csrf

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to fetch token from ctx.Locals after c.Next() — it's local and not mutated outside the package.

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 LGTM, just one small thing

@JIeJaitt JIeJaitt requested a review from Copilot April 3, 2025 06:28
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes an issue where the CSRF cookie was removed when requests passed through the proxy middleware. Key changes include the addition of two tests verifying that the CSRF cookie (and the session cookie) are correctly set in proxy scenarios and adjustments to the CSRF middleware logic to update the cookie after executing subsequent handlers.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
middleware/csrf/csrf_test.go Adds tests to ensure that the CSRF (and session) cookies are correctly set via proxy.
middleware/csrf/csrf.go Adjusts middleware logic to update the CSRF cookie after downstream handlers succeed.
Comments suppressed due to low confidence (2)

middleware/csrf/csrf_test.go:1644

  • [nitpick] The session cookie name is hard-coded to 'session_id'. Consider using a constant or configuration value from the session middleware to ensure consistency if the default name ever changes.
sessionCookieName := "session_id" // Default name for session.NewWithStore() unless configured otherwise

middleware/csrf/csrf_test.go:1624

  • It would be beneficial to add a test case covering the scenario where the downstream handler (c.Next) returns an error, ensuring that the CSRF cookie is not updated when an error occurs.
require.NoError(t, err, "app.Test failed")

@sixcolors
Copy link
Member

Will review tomorrow

// Store the token in the context
c.Locals(tokenKey, token)
// Retrieve the final token from the context, if it was set.
finalToken, ok := c.Locals(tokenKey).(string)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to fetch token from ctx.Locals after c.Next() — it's local and not mutated outside the package.

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ I'm not sure I see the point of adding CSRF protection at the proxy level. CSRF is meant to protect user-initiated browser requests to your app — applying it to a proxied backend call doesn't really make sense from a security perspective.

Can you clarify the rationale behind this?

@JIeJaitt
Copy link
Contributor Author

JIeJaitt commented Apr 7, 2025

❓ I'm not sure I see the point of adding CSRF protection at the proxy level. CSRF is meant to protect user-initiated browser requests to your app — applying it to a proxied backend call doesn't really make sense from a security perspective.

Can you clarify the rationale behind this?

hi, there. One can look at the scenario described by the user who initiated the issue : #3387 (comment)

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

Successfully merging this pull request may close these issues.

🐛 [Bug]: CSRF Cookie is removed when using Proxy Middleware
3 participants