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

🔥 feat: Add support for context.Context in keyauth middleware #3287

Merged
merged 9 commits into from
Mar 7, 2025

Conversation

vhespanha
Copy link
Contributor

pretty straightforward option to use context.Context instead of just fiber.Ctx, tests added accordingly.

Description

as discussed in #3212 and #3175, some of the middleware would benefit from exposing support for raw context.Context, for usage outside of the HTTP layer. this is the first out of 3 pull requests for middlewares that are deemed necessary to support this as of now.

Middlewares to update:

  • keyauth

  • csrf

  • session

Type of change

  • Enhancement (improvement to existing features and functionality)

Draft

i'm opening this as a draft PR as of now, if it aligns with what the issues requested, i'm happy to update the documentation and benchmarks, i feel like it's correct tho, since it basically mirrors the implementation and usage of the same feature for requestID (from #3200).

pretty straightforward option to use context.Context instead of just
fiber.Ctx, tests added accordingly.
Copy link

welcome bot commented Jan 22, 2025

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

This pull request enhances API key middleware by refining context handling and token retrieval. The New function now stores the API key in both the request's Locals and its context using context.WithValue. The TokenFromContext function is updated to accept an any type and uses a type switch to retrieve the token from either a fiber.Ctx or a context.Context, returning an empty string if the token is absent. Additional sub-tests have been added to verify proper behavior for each context type and to ensure that invalid types trigger a panic.

Changes

File(s) Change Summary
middleware/keyauth/keyauth.go Added the context package import; modified the New function to store the API key in both Locals and the request context; updated the TokenFromContext function to accept an any type and use a type switch for token retrieval, returning an empty string if not found.
middleware/keyauth/keyauth_test.go Refactored tests by splitting Test_TokenFromContext into three sub-tests, covering token retrieval from fiber.Ctx, context.Context, and verifying that a panic occurs with an unsupported context type.

Sequence Diagram(s)

sequenceDiagram
    participant Req as Request
    participant MW as Middleware
    participant KA as KeyAuth Module

    Req->>MW: Send request with API key
    MW->>KA: Call New() to validate & store API key
    KA-->>MW: Set token in Locals and Context
    Note over MW,KA: Later, token is retrieved for authorization
    MW->>KA: Call TokenFromContext(context)
    alt context type is fiber.Ctx
        KA-->>MW: Return token from Locals
    else context type is context.Context
        KA-->>MW: Return token from context.Value
    else unsupported context type
        KA-->>MW: Panic with error message
    end

Poem

I'm a little rabbit hopping in the code,
API keys on the run, easing every load.
With context flowing, tokens now take flight,
Fiber or context, all turns out right.
Bugs retreat as tests sing out loud—
Hoppity change makes me ever so proud! 🐰


📜 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 a5c7b77 and 8a5aea3.

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

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

Copy link

codecov bot commented Feb 4, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.61%. Comparing base (a5c7b77) to head (8a5aea3).
Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3287      +/-   ##
==========================================
- Coverage   83.66%   83.61%   -0.06%     
==========================================
  Files         118      118              
  Lines       11714    11724      +10     
==========================================
+ Hits         9801     9803       +2     
- Misses       1485     1491       +6     
- Partials      428      430       +2     
Flag Coverage Δ
unittests 83.61% <100.00%> (-0.06%) ⬇️

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.

@gaby
Copy link
Member

gaby commented Feb 11, 2025

@vhespanha Are you done with the changes? Can we review it? If so, remove the "Draft" status.

@gaby gaby changed the title add support for raw context.Context in keyauth middleware 🔥 feat: Add support for context.Context in keyauth middleware Mar 4, 2025
@gaby gaby self-assigned this Mar 5, 2025
@gaby gaby marked this pull request as ready for review March 6, 2025 02:57
@gaby gaby requested a review from a team as a code owner March 6, 2025 02:57
@gaby gaby requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 6, 2025 02:57
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
middleware/keyauth/keyauth.go (1)

75-89: Well-structured type handling for multiple context types.

The function has been updated to work with both context.Context and fiber.Ctx types through a type switch pattern, which is an idiomatic approach in Go. The panic for unsupported types is appropriate for programming errors.

Consider adding documentation comments about the expected context types and panic behavior to help users understand how to properly use this function.

// TokenFromContext returns the bearer token from the request context.
// returns an empty string if the token does not exist
+// Accepts either fiber.Ctx or context.Context, and panics for other types
func TokenFromContext(c any) string {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5c7b77 and 8a5aea3.

📒 Files selected for processing (2)
  • middleware/keyauth/keyauth.go (3 hunks)
  • middleware/keyauth/keyauth_test.go (1 hunks)
🔇 Additional comments (5)
middleware/keyauth/keyauth.go (2)

5-5: Added context import for Go's standard context package.

Good addition necessary for the planned context support.


63-67: Good implementation for dual context support.

This is an excellent approach that maintains backward compatibility while adding new functionality. The token is now stored in both Locals (for backward compatibility) and the request context (for the new feature), ensuring a smooth transition.

middleware/keyauth/keyauth_test.go (3)

507-531: Good test coverage for fiber.Ctx token retrieval.

This first sub-test properly verifies that the TokenFromContext function can retrieve the token from a fiber.Ctx instance. The test setup, execution, and assertions are clear and comprehensive.


533-560: Excellent test for context.Context support.

This test is critical for confirming that the new functionality works as expected. It verifies that the token can be retrieved from a standard Go context using the same TokenFromContext function, which demonstrates the dual nature of the enhanced API.


562-566: Good error handling test.

Testing that the function properly panics for invalid context types is important for ensuring robust error handling. This test will prevent regressions where someone might mistakenly pass an invalid type to the function.

@ReneWerner87 ReneWerner87 added the v3 label Mar 6, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 6, 2025
@ReneWerner87 ReneWerner87 merged commit 4177ab4 into gofiber:main Mar 7, 2025
18 checks passed
Copy link

welcome bot commented Mar 7, 2025

Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

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.

3 participants