Skip to content

🐛 fix: Middlewares immutable config handling#3494

Merged
ReneWerner87 merged 2 commits intomainfrom
codex/fix-middlewares-respecting-immutable-flag
Jun 1, 2025
Merged

🐛 fix: Middlewares immutable config handling#3494
ReneWerner87 merged 2 commits intomainfrom
codex/fix-middlewares-respecting-immutable-flag

Conversation

@gaby
Copy link
Member

@gaby gaby commented May 29, 2025

Summary

  • ensure basic auth doesn't rely on unsafe string conversion when immutable
  • use SetRequestURI or SetRequestURIBytes in proxy middleware based on Immutable flag

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 29, 2025

"""

Walkthrough

The changes introduce conditional logic in two middleware components to handle string conversion differently based on the application's immutability configuration. Specifically, string conversion methods are chosen depending on whether the Immutable flag is set in the application's configuration, affecting how byte slices are converted to strings in authentication and proxy request handling. Additionally, new tests verify middleware behavior under immutable configuration.

Changes

File(s) Change Summary
middleware/basicauth/basicauth.go Updated credential string extraction to use different conversion methods based on Immutable.
middleware/proxy/proxy.go Modified request URI setting to conditionally use different methods depending on Immutable.
middleware/basicauth/basicauth_test.go Added test verifying BasicAuth middleware behavior with Immutable: true.
middleware/proxy/proxy_test.go Added test verifying proxy middleware behavior with Immutable: true.

Sequence Diagram(s)

sequenceDiagram
    participant AppConfig as App Config
    participant Middleware as Middleware Function
    participant Utils as Utils

    AppConfig->>Middleware: Check Immutable flag
    alt Immutable is true
        Middleware->>Middleware: Use standard string/byte conversion
    else Immutable is false
        Middleware->>Utils: Use UnsafeString conversion
    end
    Middleware->>Middleware: Continue with authentication/proxy logic
Loading

Suggested reviewers

  • sixcolors
  • efectn

Poem

A toggle for Immutable, oh what a sight,
Now bytes become strings in a way that is right.
Whether proxy or auth, the code is astute,
With careful conversion, the bugs are now mute.
🐇✨ Code hops along—robust and bright!
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@gaby gaby changed the title Fix middleware immutable handling 🐛 fix: Middlewares immutable config handling May 29, 2025
@gaby gaby added this to v3 May 29, 2025
@gaby gaby added this to the v3 milestone May 29, 2025
@gaby gaby moved this to In Progress in v3 May 29, 2025
@gaby gaby marked this pull request as ready for review May 29, 2025 13:10
Copilot AI review requested due to automatic review settings May 29, 2025 13:10
@gaby gaby requested a review from a team as a code owner May 29, 2025 13:10
@gaby gaby requested review from ReneWerner87, efectn and sixcolors May 29, 2025 13:10
@codecov
Copy link

codecov bot commented May 29, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.83%. Comparing base (09d9e16) to head (a95fcc6).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3494      +/-   ##
==========================================
- Coverage   83.89%   83.83%   -0.06%     
==========================================
  Files         120      120              
  Lines       12268    12272       +4     
==========================================
- Hits        10292    10288       -4     
- Misses       1553     1559       +6     
- Partials      423      425       +2     
Flag Coverage Δ
unittests 83.83% <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.

Copy link
Contributor

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 updates middleware to respect the Immutable flag in the app config, avoiding unsafe string conversions when immutability is enabled and routing requests appropriately.

  • Proxy middleware now uses SetRequestURIBytes when Immutable is true, and SetRequestURI otherwise.
  • Basic auth middleware switches between string(raw) and utils.UnsafeString(raw) based on the Immutable flag.

Reviewed Changes

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

File Description
middleware/proxy/proxy.go Added conditional branch to use byte-based URI setting
middleware/basicauth/basicauth.go Refactored credential extraction to handle immutable config
Comments suppressed due to low confidence (2)

middleware/proxy/proxy.go:80

  • Introduce unit tests for both branches of the Immutable flag to verify that SetRequestURIBytes and SetRequestURI(utils.UnsafeString) behave as expected.
if c.App().Config().Immutable {

middleware/basicauth/basicauth.go:50

  • Add coverage in your basic-auth tests for when Immutable is true and false to ensure both string(raw) and utils.UnsafeString(raw) paths are validated.
if c.App().Config().Immutable {

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 09d9e16 and a1e7e3b.

📒 Files selected for processing (2)
  • middleware/basicauth/basicauth.go (1 hunks)
  • middleware/proxy/proxy.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
middleware/basicauth/basicauth.go

[warning] 51-51: middleware/basicauth/basicauth.go#L51
Added line #L51 was not covered by tests

middleware/proxy/proxy.go

[warning] 81-81: middleware/proxy/proxy.go#L81
Added line #L81 was not covered by tests

🪛 GitHub Check: CodeQL
middleware/proxy/proxy.go

[failure] 81-81: Uncontrolled data used in network request
The URL of this request depends on a user-provided value.

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: unit (1.24.x, windows-latest)
🔇 Additional comments (1)
middleware/proxy/proxy.go (1)

80-84:

Details

❓ Verification inconclusive

LGTM! Consistent implementation of immutable config handling.

The conditional logic properly handles URI setting based on immutability configuration:

  • Uses SetRequestURIBytes to work directly with bytes when immutable mode is enabled
  • Uses SetRequestURI with unsafe string conversion for performance when immutable mode is disabled

This approach is consistent with the basicauth middleware changes and follows the same safety-vs-performance pattern.

Two concerns to address:

  1. Test Coverage: Static analysis indicates this code path lacks test coverage. Please add tests for both immutable and non-immutable modes.

  2. Security Analysis: CodeQL flagged "Uncontrolled data used in network request" for line 81. While this may be a false positive (since we're using the same request URI), please verify this doesn't introduce security risks:


🏁 Script executed:

#!/bin/bash
# Verify the relationship between SetRequestURI and SetRequestURIBytes methods
ast-grep --pattern $'func ($$$) SetRequestURI($$$) {
  $$$
}'

# Check if there are any security validations around URI handling
rg -A 5 -B 5 "SetRequestURI.*validation|sanitize.*URI|validate.*URI"

Length of output: 133


To locate the actual implementations and verify any URI validation, let’s search for the definitions and usages of both methods:


🏁 Script executed:

#!/bin/bash
# Find definitions of SetRequestURI and SetRequestURIBytes
rg -n "func .*SetRequestURI" .
rg -n "func .*SetRequestURIBytes" .

# Inspect all call sites to see if any validation/sanitization is applied upstream
rg -n "SetRequestURI(" .
rg -n "SetRequestURIBytes(" .

Length of output: 297


Add Tests and Manually Verify URI Setter Security

Before merging, please address two points:

  • Test Coverage
    • Add unit tests for proxy.go to cover both c.App().Config().Immutable = true and false paths, ensuring SetRequestURIBytes and SetRequestURI(utils.UnsafeString(...)) behave as expected.

  • Security Review of URI Setters
    We couldn’t find SetRequestURI or SetRequestURIBytes definitions in this repo (they’re likely in the external fasthttp library). Please manually inspect those implementations to confirm that using UnsafeString (and the byte‐based setter) does not bypass necessary URI validation or introduce injection risks.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 81-81: middleware/proxy/proxy.go#L81
Added line #L81 was not covered by tests

🪛 GitHub Check: CodeQL

[failure] 81-81: Uncontrolled data used in network request
The URL of this request depends on a user-provided value.

@gaby
Copy link
Member Author

gaby commented May 29, 2025

Let me generate more tests with immutable True

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 (2)
middleware/proxy/proxy_test.go (1)

881-904: LGTM! Well-implemented test for immutable configuration.

The test follows established patterns and properly verifies that the proxy middleware continues to function correctly when the Fiber app is configured with Immutable: true. The test structure is solid with appropriate error handling and assertions.

Consider enhancing the test to specifically verify immutable behavior differences (e.g., testing that string conversions are handled safely), though the current implementation serves well as a regression test.

middleware/basicauth/basicauth_test.go (1)

203-219: LGTM! Clean test implementation for immutable configuration.

The test correctly verifies that BasicAuth middleware functions properly when the Fiber app is configured with Immutable: true. The implementation follows existing test patterns with proper base64 encoding, error handling, and assertions.

Consider adding a test case for invalid credentials under immutable mode to ensure comprehensive coverage, though the current positive test case effectively serves as a regression test for immutable functionality.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1e7e3b and a95fcc6.

📒 Files selected for processing (2)
  • middleware/basicauth/basicauth_test.go (1 hunks)
  • middleware/proxy/proxy_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Compare
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: repeated

@ReneWerner87 ReneWerner87 merged commit 5eb1432 into main Jun 1, 2025
14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jun 1, 2025
@gaby gaby deleted the codex/fix-middlewares-respecting-immutable-flag branch June 1, 2025 12:22
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