Skip to content

🔥 feat: Add context.Context support to CSRF middleware#3340

Closed
JIeJaitt wants to merge 9 commits intogofiber:mainfrom
JIeJaitt:JIeJaitt-jiejaitt-feature/add-CSRF-userContext-support
Closed

🔥 feat: Add context.Context support to CSRF middleware#3340
JIeJaitt wants to merge 9 commits intogofiber:mainfrom
JIeJaitt:JIeJaitt-jiejaitt-feature/add-CSRF-userContext-support

Conversation

@JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Mar 6, 2025

In order to maintain the consistency of the fiber middleware, this pr is proposed to add the corresponding function mentioned in #3212 to the CSRF middleware.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

The changes update the CSRF middleware to support a generic context parameter. The functions TokenFromContext and HandlerFromContext now accept a generic type (any), allowing them to work with both fiber.Ctx and Go’s standard context.Context. The middleware’s New function has been updated to store values in both contexts. In addition, comprehensive tests have been added to verify functionality across various context types, ensure token consistency, handle unsupported contexts, and validate token passing across requests.

Changes

File Change Summary
middleware/csrf/csrf.go Updated TokenFromContext and HandlerFromContext to accept a generic parameter (any). Implemented type assertions to support both fiber.Ctx and context.Context, added error handling for unsupported types, and updated New to store in both contexts.
middleware/csrf/csrf_test.go Added multiple tests (Test_CSRF_Context, Test_CSRF_ServiceLayer, Test_CSRF_TokenConsistency, Test_CSRF_CrossRequest) to validate correct behavior of the CSRF middleware across different context types and request flows.

Sequence Diagram(s)

sequenceDiagram
    participant Req as Request
    participant CSRF as CSRF Middleware
    participant Ctx as Context (fiber.Ctx / context.Context)
    participant Log as Logger

    Req->>CSRF: Incoming Request
    CSRF->>Ctx: Retrieve token and handler
    alt Valid fiber.Ctx or context.Context
        Ctx-->>CSRF: Return valid token and handler
    else Unsupported type
        CSRF->>Log: Log error message
        Log-->>CSRF: Error logged
    end
    CSRF->>Req: Process request with retrieved token/handler
Loading

Poem

I'm a little rabbit, hopping in the code,
With tokens and contexts, on a brilliant road.
I nibble bugs and fix with glee,
Ensuring CSRF flows naturally.
A hop of joy in every line I see! 🐰
Cheers to clean code and harmony!


📜 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 1df0862 and 33f5bd9.

📒 Files selected for processing (1)
  • middleware/csrf/csrf.go (2 hunks)

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 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.

@codecov
Copy link

codecov bot commented Mar 6, 2025

Codecov Report

Attention: Patch coverage is 90.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 83.61%. Comparing base (395c8fa) to head (f1214e2).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
middleware/csrf/csrf.go 90.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3340      +/-   ##
==========================================
- Coverage   83.61%   83.61%   -0.01%     
==========================================
  Files         118      118              
  Lines       11727    11746      +19     
==========================================
+ Hits         9806     9821      +15     
- Misses       1491     1495       +4     
  Partials      430      430              
Flag Coverage Δ
unittests 83.61% <90.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 March 6, 2025 08:23
@JIeJaitt JIeJaitt requested a review from a team as a code owner March 6, 2025 08:23
@JIeJaitt JIeJaitt requested review from ReneWerner87, efectn, gaby and sixcolors and removed request for a team March 6, 2025 08:23
@ReneWerner87 ReneWerner87 added this to v3 Mar 6, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 6, 2025
@gaby gaby changed the title 🔥 Feature: Enhance CSRF Context Handling with Go Standard Context Sup… 🔥 feat: Enhance CSRF Context Handling with Go Standard Context Sup… Mar 6, 2025
@gaby gaby moved this to In Progress in v3 Mar 6, 2025
@gaby gaby changed the title 🔥 feat: Enhance CSRF Context Handling with Go Standard Context Sup… 🔥 feat: Add context.Context support to CSRF middleware Mar 11, 2025
@gaby
Copy link
Member

gaby commented Mar 11, 2025

@JIeJaitt Take a lot at the changes that were added to #3287 those would need to be applied here too. For example, removing the logger.

@JIeJaitt
Copy link
Contributor Author

@ReneWerner87 @gaby hi there. how can i fix this lint error?

@gaby
Copy link
Member

gaby commented Mar 13, 2025

@JIeJaitt I'm fixing it in a branch. It randomly broke without us updating the version

Comment on lines +185 to +186
ctx := context.WithValue(c.Context(), tokenKey, token)
ctx = context.WithValue(ctx, handlerKey, handler)
Copy link
Member

Choose a reason for hiding this comment

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

I'm unsure I understand the benefit of retaining the references in both c.Context and c.Locals. Given that the UserContext used is always linked to the ctx.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

When the developer controller layer will fiber.Ctx converted to context.Context, in the service layer will have a lot of inconvenience when using, for example, requestid can not be directly inherited from the ctx, can only rely on the external incoming ... This is the initial idea, other middleware, perhaps to maintain the consistency of the middleware fiber framework it

Copy link
Member

Choose a reason for hiding this comment

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

I’m still not sure I understand. Could you perhaps provide a code example demonstrating the issue you are seeking to address?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fiber's fiber.Ctx is specific to the Fiber framework. If we only store CSRF information in fiber.Ctx.Locals, it will not be accessible when we switch to Go's native context.Context in the service layer or other parts of the application.

Go's native context.Context is widely used across libraries and frameworks. By injecting CSRF information into the native context, we ensure that it can be accessed seamlessly in the service layer or any other part of the application that relies on context.Context.

code example like this:

.
├── main.go
├── controllers
│   └── user_controller.go
├── services
│   └── user_service.go
├── middlewares
│   └── csrf_middleware.go
└── utils
    └── context_utils.go

Controller Layer (controllers/user_controller.go)

package controllers

import (
    "context"
    "github.com/gofiber/fiber/v2"
    "your_project/services"
)

type UserController struct {
    userService *services.UserService
}

func NewUserController(userService *services.UserService) *UserController {
    return &UserController{userService: userService}
}

func (uc *UserController) CreateUser(c *fiber.Ctx) error {
    // Convert Fiber context to native context
    ctx := c.Context()

    // Call service layer with native context
    err := uc.userService.CreateUser(ctx)
    if err != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
            "error": err.Error(),
        })
    }

    return c.Status(fiber.StatusOK).JSON(fiber.Map{
        "message": "User created successfully",
    })
}
package services

import (
    "context"
    "fmt"
)

type UserService struct{}

func NewUserService() *UserService {
    return &UserService{}
}

func (us *UserService) CreateUser(ctx context.Context) error {
    // Retrieve CSRF token from context
    csrfToken := ctx.Value("csrf").(string)

    // Use CSRF token in the service logic
    fmt.Println("CSRF Token:", csrfToken)

    // Business logic here...

    return nil
}

If we don't inject a csrf into the context, then we can't get the csrf information at the service level unless we pass it in as a parameter manually, but this is obviously not that elegant.

Copy link
Member

@sixcolors sixcolors Mar 19, 2025

Choose a reason for hiding this comment

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

The assumption here is incorrect—Fiber’s CSRF token is not stored in context.Context using a string key like "csrf". Instead, it is stored in c.Locals with an unexported key, and the correct way to retrieve it is:

csrfToken := csrf.TokenFromContext(c)

Even in the PR proposed approach, the token is still being redundantly stored in context.Context using an unexported key. This means the service layer must be aware of the Fiber middleware and use csrf.TokenFromContext to retrieve the token—making the change ineffective in addressing the issue.

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.

Thanks for your contribution! However, I do not support merging this change due to the reasons outlined in issue #3358.

Fiber is designed to be lightweight and high-performance, and modifying context.Context within middleware introduces unnecessary overhead.

If you need context.Context integration, you can implement a custom middleware to copy values into context.Context for your specific use case without affecting Fiber’s default behavior.

For more details, see: this comment.

I recommend closing this PR. Thanks again! 🚀

@JIeJaitt
Copy link
Contributor Author

Thanks for your contribution! However, I do not support merging this change due to the reasons outlined in issue #3358.

Fiber is designed to be lightweight and high-performance, and modifying context.Context within middleware introduces unnecessary overhead.

If you need context.Context integration, you can implement a custom middleware to copy values into context.Context for your specific use case without affecting Fiber’s default behavior.

For more details, see: this comment.

I recommend closing this PR. Thanks again! 🚀

thinks,I've already understood the whole working process and I will close this pr

@JIeJaitt JIeJaitt closed this Mar 19, 2025
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Mar 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants