Skip to content

Conversation

@sixcolors
Copy link
Member

@sixcolors sixcolors commented Dec 12, 2025

This PR migrates Fiber middlewares from using UUID or UUIDv4 to SecureToken for key generation, providing better security and privacy.

Changes

Code Changes

  • Session Middleware: Changed default KeyGenerator from utils.UUIDv4 to utils.SecureToken
  • CSRF Middleware: Changed default KeyGenerator from utils.UUIDv4 to utils.SecureToken
  • RequestID Middleware: Changed default Generator from utils.UUID to utils.SecureToken
  • RequestID Optimization: Removed redundant SecureToken retry loop, now uses single fallback
  • Test Updates: Changed test key generation to use utils.UUIDv4() for predictable test IDs

Documentation Updates

  • Updated middleware documentation to reflect SecureToken defaults
  • Updated RequestID docs to reflect single SecureToken fallback behavior
  • Updated Session and CSRF docs in what's new guide

Dependencies

  • Updated go.mod to use latest utils version with SecureToken support

Security Benefits

  • SecureToken provides cryptographically secure random tokens
  • Prevents information leakage about request patterns (unlike sequential UUIDs)
  • Better privacy protection for users

Breaking Changes

  • Default key generators now produce base64-encoded tokens instead of UUID format
  • RequestID middleware behavior slightly changed (single fallback instead of multiple retries)

Testing

  • All tests pass
  • Audit checks pass
  • Code generation and formatting verified

Note

Waiting on utils release for SecureToken availability in production.

Related

gofiber/utils#175
gofiber/utils#171
gofiber/utils#170
GHSA-m98w-cqp3-qcqr

- Replace UUIDv4 with SecureToken in session, csrf, and requestid middlewares
- Optimize requestid middleware to use single SecureToken fallback instead of retry loop
- Update test files to use UUIDv4 for predictable test IDs
- Update middleware documentation to reflect SecureToken defaults
- Update go.mod to use latest utils version with SecureToken support
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 12, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/adopt-secure-token

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sixcolors, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the security and privacy of key generation within several core middlewares by transitioning from UUID-based identifiers to cryptographically secure tokens. This change impacts Session, CSRF, and RequestID middlewares, making them more robust against potential information leakage. Alongside this, the RequestID middleware's internal logic for ID generation and fallback has been optimized, and various string manipulation operations across the codebase have been refactored for improved readability and efficiency. The update also includes necessary documentation adjustments and a dependency bump to support these new security features.

Highlights

  • Enhanced Security and Privacy: The default key generation mechanism for Session, CSRF, and RequestID middlewares has been migrated from UUIDv4 (or UUID) to utils.SecureToken. This change provides cryptographically secure random tokens, preventing information leakage about request patterns and offering better privacy protection.
  • RequestID Middleware Optimization: The RequestID middleware's fallback logic has been streamlined. It now uses a single fallback to SecureToken if a custom generator fails to produce a valid ID, removing redundant retry loops previously involving UUIDs.
  • Documentation Updates: Relevant documentation for CSRF, RequestID, and Session middlewares, including the 'What's New' guide, has been updated to reflect the new SecureToken defaults and the revised RequestID fallback behavior.
  • Dependency Update: The go.mod file has been updated to utilize the latest version of github.com/gofiber/utils/v2, which includes support for SecureToken.
  • Code Refactoring for String Operations: Several instances of strings.Index and manual slicing have been replaced with the more idiomatic and often more efficient strings.Cut function for parsing strings like credentials, host headers, and range headers.
  • Breaking Changes: Default key generators now produce base64-encoded tokens instead of the UUID format. Additionally, the RequestID middleware's fallback behavior has slightly changed, as noted above.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great initiative to enhance security by migrating from UUIDv4 to the more secure SecureToken for key generation in various middlewares. The changes are well-implemented across the session, CSRF, and request ID middlewares, including necessary documentation and test updates. The code also benefits from several refactorings that improve readability and adopt modern Go idioms, such as using strings.Cut. My main feedback is a minor suggestion to improve the robustness of the fallback logic in the request ID middleware to ensure it aligns perfectly with the documented behavior.

Comment on lines 65 to 68
if generator != nil {
for range 3 {
rid = utils.UUID()
if isValidRequestID(rid) {
return rid
}
}
rid = utils.SecureToken()
return rid
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The result of utils.SecureToken() is returned directly without validation. While it's highly likely to be a valid request ID, for robustness, it would be better to validate it with isValidRequestID before returning. This would also align with the function's documentation which states it falls back to an empty string if a valid ID cannot be produced. This change ensures that if utils.SecureToken() were to produce an invalid ID, the function would correctly fall back to returning an empty string.

Suggested change
if generator != nil {
for range 3 {
rid = utils.UUID()
if isValidRequestID(rid) {
return rid
}
}
rid = utils.SecureToken()
return rid
}
if generator != nil {
rid = utils.SecureToken()
if isValidRequestID(rid) {
return rid
}
}

Copy link
Member Author

Choose a reason for hiding this comment

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

@gemini-code-assist The utils.SecureToken() function doesn’t require explicit validation because it panics on any RNG failure, just like the underlying crypto/rand.Read function it relies on. Furthermore, it uses base64.RawURLEncoding.EncodeToString, which always produces valid ASCII characters (0x20-0x7E). This makes additional checks redundant and adds unnecessary overhead. The middleware now relies on SecureToken's internal guarantees for robustness, avoiding 'generally' applied suggestions that don't account for the specific implementation details.

Copy link
Contributor

Choose a reason for hiding this comment

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

Thank you for the detailed explanation, @sixcolors. I understand now that utils.SecureToken() is designed to always produce a valid, visible ASCII string due to its use of base64.RawURLEncoding.EncodeToString and its panic-on-failure behavior for RNG. Given these strong guarantees, the isValidRequestID check for the output of utils.SecureToken() is indeed redundant and would add unnecessary overhead. I withdraw my previous suggestion.

@codecov
Copy link

codecov bot commented Dec 12, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.67%. Comparing base (b9f99fa) to head (25ee058).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3946      +/-   ##
==========================================
+ Coverage   91.58%   91.67%   +0.09%     
==========================================
  Files         119      119              
  Lines       10165    10155      -10     
==========================================
  Hits         9310     9310              
+ Misses        543      535       -8     
+ Partials      312      310       -2     
Flag Coverage Δ
unittests 91.67% <100.00%> (+0.09%) ⬆️

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.

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

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants