Skip to content

🧹chore: Improve BasicAuth middleware default security #3522

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

Merged
merged 5 commits into from
Jun 20, 2025

Conversation

gaby
Copy link
Member

@gaby gaby commented Jun 17, 2025

Summary

  • Add new StorePassword config option. Defaults to False to avoid leaking credentials via Context.
  • Add charset parameter. Defaults to UTF-8.
  • Set "no-store" header for Cache Control.

@gaby gaby added the codex label Jun 17, 2025 — with ChatGPT Connector
Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

The BasicAuth middleware has been updated to add two new configuration options: Charset (default "UTF-8") for customizing the WWW-Authenticate header, and StorePassword (default false) to control whether the plaintext password is stored in the context. Documentation, tests, and security headers have been updated accordingly.

Changes

Files/Group Change Summary
docs/middleware/basicauth.md, docs/whats_new.md Updated documentation to reflect new Charset and StorePassword config options and header changes.
middleware/basicauth/basicauth.go Added basicScheme constant, improved Authorization header validation, and conditional password storage.
middleware/basicauth/basicauth_test.go Enhanced tests for StorePassword option and updated header expectations.
middleware/basicauth/config.go Added Charset and StorePassword fields to Config struct and updated default/config logic.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Client
    participant Middleware
    participant Handler

    Client->>Middleware: Sends HTTP request with Authorization header
    Middleware->>Middleware: Validate Authorization header
    alt Authorization header missing or invalid
        Middleware-->>Client: Respond 401 with WWW-Authenticate (charset, no-store)
    else Valid credentials
        alt StorePassword is true
            Middleware->>Handler: Call handler with password in context
        else StorePassword is false
            Middleware->>Handler: Call handler without password in context
        end
    end

Suggested labels

🧹 Updates

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

A rabbit hopped through code so bright,
Adding charset and password in sight.
Now headers are strict, and configs are neat,
With tests that ensure the middleware’s complete.
“No-store!” cries the bunny, with UTF-8 cheer,
Secure and tidy, the changes are here!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b913ae9 and 90246c2.

📒 Files selected for processing (1)
  • docs/middleware/basicauth.md (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/middleware/basicauth.md
⏰ 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

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 added this to v3 Jun 17, 2025
@gaby gaby added this to the v3 milestone Jun 17, 2025
@gaby gaby moved this to In Progress in v3 Jun 17, 2025
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.

Summary of Changes

Hello @gaby, 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 robustness of the BasicAuth middleware. It introduces new configuration options to give developers more control over authentication behavior, improves the parsing of authentication headers, and strengthens the default security posture by preventing plaintext password storage and adding security-focused response headers. The changes are accompanied by updated documentation and new test cases to ensure correctness.

Highlights

  • Enhanced Security Defaults: The BasicAuth middleware no longer stores plaintext passwords in the request context by default, significantly improving security. A new StorePassword option allows explicit control over this behavior.
  • Improved Header Handling: The Authorization header parsing has been made more robust by using utils.Trim and a new package-level constant for the 'Basic' scheme. The default WWW-Authenticate challenge now includes charset="UTF-8" and sets Cache-Control: no-store and Vary: Authorization for better security and caching control.
  • New Configuration Options: Introduced a Charset option to allow customization of the charset parameter in the WWW-Authenticate header, and the StorePassword option to control password storage in the context.
  • Constant-Time Comparison for Authorizer: The default Authorizer function now uses subtle.ConstantTimeCompare for both username and password validation, mitigating potential timing attacks.
  • Comprehensive Testing: A new test case (Test_BasicAuth_NoStorePassword) has been added to specifically verify that passwords are not stored in the context when the StorePassword option is disabled.
  • Documentation Updates: The docs/middleware/basicauth.md and docs/whats_new.md files have been updated to reflect the new security enhancements, configuration options, and changes to the WWW-Authenticate header.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.

@gaby gaby changed the title Improve BasicAuth middleware security 🔥 feat: Improve BasicAuth middleware security Jun 17, 2025
Copy link

codecov bot commented Jun 17, 2025

Codecov Report

Attention: Patch coverage is 94.11765% with 1 line in your changes missing coverage. Please review.

Project coverage is 90.41%. Comparing base (3b2af61) to head (d959b79).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
middleware/basicauth/basicauth.go 85.71% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3522   +/-   ##
=======================================
  Coverage   90.40%   90.41%           
=======================================
  Files         110      110           
  Lines       10939    10949   +10     
=======================================
+ Hits         9889     9899   +10     
  Misses        791      791           
  Partials      259      259           
Flag Coverage Δ
unittests 90.41% <94.11%> (+<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.

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 improves the security of the BasicAuth middleware by refining header parsing, removing extraneous comments, and adding a test for password omission. The changes enhance robustness and provide better control over password storage.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: d959b79 Previous: 3b2af61 Ratio
Benchmark_Ctx_SendString_B 14.96 ns/op 0 B/op 0 allocs/op 9.364 ns/op 0 B/op 0 allocs/op 1.60
Benchmark_Ctx_SendString_B - ns/op 14.96 ns/op 9.364 ns/op 1.60

This comment was automatically generated by workflow using github-action-benchmark.

@gaby gaby marked this pull request as ready for review June 17, 2025 02:34
@gaby gaby requested a review from a team as a code owner June 17, 2025 02:34
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 (6)
docs/whats_new.md (1)

978-979: Comma missing in explanatory sentence

Minor style nit: add a comma before “so” to separate the two independent clauses.

-The BasicAuth middleware now validates the `Authorization` header more rigorously and sets security-focused response headers. The default challenge includes the `charset="UTF-8"` parameter and disables caching. Passwords are no longer stored in the request context by default; use the new `StorePassword` option to retain them. A `Charset` option controls the value used in the challenge header.
+The BasicAuth middleware now validates the `Authorization` header more rigorously and sets security-focused response headers. The default challenge includes the `charset="UTF-8"` parameter and disables caching. Passwords are no longer stored in the request context by default; use the new `StorePassword` option to retain them. A `Charset` option controls the value used in the challenge header, so clients know how credentials are encoded.
middleware/basicauth/basicauth_test.go (1)

95-114: Close the response body to avoid fd leaks

All new test cases read or at least open resp.Body but never close it.
While Go’s GC will eventually do this, closing explicitly keeps go test -count=N -run … -race squeaky-clean.

-	resp, err := app.Test(req)
+	resp, err := app.Test(req)
 	require.NoError(t, err)
 	require.Equal(t, fiber.StatusOK, resp.StatusCode)
+	_ = resp.Body.Close()

Apply the same pattern to other tests that open bodies.

middleware/basicauth/basicauth.go (1)

35-44: Broaden trimming to all whitespace characters

utils.Trim(s, ' ') only strips the ASCII space; headers with leading tabs (\t) or newlines will slip through.
strings.TrimSpace handles the full Unicode white-space set and is inlinable.

-		auth := utils.Trim(c.Get(fiber.HeaderAuthorization), ' ')
+		auth := strings.TrimSpace(c.Get(fiber.HeaderAuthorization))

Remember to add strings to the imports and drop utils if it becomes unused in this file.

middleware/basicauth/config.go (2)

45-56: Field docs are clear but could mention security trade-off

Consider adding a short warning that enabling StorePassword places the plaintext password in memory for the lifetime of the request and should be enabled only when absolutely necessary.


100-108: Header construction – minor readability tweak

Using fmt.Sprintf makes the composition easier to scan and avoids the nested if.

-			header := "Basic realm=" + strconv.Quote(cfg.Realm)
-			if cfg.Charset != "" {
-				header += ", charset=" + strconv.Quote(cfg.Charset)
-			}
+			header := fmt.Sprintf("Basic realm=%s, charset=%s",
+				strconv.Quote(cfg.Realm),
+				strconv.Quote(cfg.Charset))

Functionally identical, purely cosmetic.

docs/middleware/basicauth.md (1)

81-83: Punctuation: add comma before “so”

Same nit as in whats_new.md – comma separates clauses.

-| Charset         | `string`                    | Charset sent in the `WWW-Authenticate` header so clients know how credentials are encoded. | `"UTF-8"` |
+| Charset         | `string`                    | Charset sent in the `WWW-Authenticate` header, so clients know how credentials are encoded. | `"UTF-8"` |
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0590709 and b913ae9.

📒 Files selected for processing (5)
  • docs/middleware/basicauth.md (3 hunks)
  • docs/whats_new.md (1 hunks)
  • middleware/basicauth/basicauth.go (3 hunks)
  • middleware/basicauth/basicauth_test.go (3 hunks)
  • middleware/basicauth/config.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
middleware/basicauth/basicauth.go (2)
constants.go (1)
  • HeaderAuthorization (161-161)
ctx.go (1)
  • Locals (1007-1019)
🪛 LanguageTool
docs/middleware/basicauth.md

[uncategorized] ~81-~81: Use a comma before ‘so’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...et sent in the WWW-Authenticate header so clients know how credentials are encode...

(COMMA_COMPOUND_SENTENCE_2)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (5)
middleware/basicauth/basicauth_test.go (2)

39-40: Test reveals intent clearly – nice!

Enabling StorePassword: true in the main happy-path test makes the assertion on PasswordFromContext explicit.
No further comments here.


125-125: Header expectation updated – LGTM

The assertion now matches the new charset="UTF-8" default.
Looks good.

middleware/basicauth/basicauth.go (2)

21-21: Good extraction of the scheme constant

Replacing the magic string with basicScheme improves readability.


71-76: Conditional password storage implemented correctly

The conditional call respects the new flag and keeps PII out of context by default – nice defensive design.

middleware/basicauth/config.go (1)

60-68: Defaults extended – LGTM

Including sane defaults for Charset and StorePassword keeps behaviour predictable.

@gaby gaby changed the title 🔥 feat: Improve BasicAuth middleware security 🧹chore: Improve BasicAuth middleware default security Jun 17, 2025
@ReneWerner87
Copy link
Member

@sixcolors can you check

@ReneWerner87 ReneWerner87 merged commit 6d16bf5 into main Jun 20, 2025
13 of 14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jun 20, 2025
@gaby gaby deleted the codex/2025-06-17-02-22-11 branch June 20, 2025 11:03
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.

2 participants