-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
🧹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
Conversation
WalkthroughThe BasicAuth middleware has been updated to add two new configuration options: Changes
Sequence Diagram(s)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
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (5)
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 usingutils.Trim
and a new package-level constant for the 'Basic' scheme. The defaultWWW-Authenticate
challenge now includescharset="UTF-8"
and setsCache-Control: no-store
andVary: Authorization
for better security and caching control. - New Configuration Options: Introduced a
Charset
option to allow customization of thecharset
parameter in theWWW-Authenticate
header, and theStorePassword
option to control password storage in the context. - Constant-Time Comparison for Authorizer: The default
Authorizer
function now usessubtle.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 theStorePassword
option is disabled. - Documentation Updates: The
docs/middleware/basicauth.md
anddocs/whats_new.md
files have been updated to reflect the new security enhancements, configuration options, and changes to theWWW-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
-
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. ↩
Codecov ReportAttention: Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this 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.
There was a problem hiding this 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.
There was a problem hiding this 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 sentenceMinor 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 leaksAll new test cases read or at least open
resp.Body
but never close it.
While Go’s GC will eventually do this, closing explicitly keepsgo 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 droputils
if it becomes unused in this file.middleware/basicauth/config.go (2)
45-56
: Field docs are clear but could mention security trade-offConsider 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 tweakUsing
fmt.Sprintf
makes the composition easier to scan and avoids the nestedif
.- 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
📒 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 onPasswordFromContext
explicit.
No further comments here.
125-125
: Header expectation updated – LGTMThe assertion now matches the new
charset="UTF-8"
default.
Looks good.middleware/basicauth/basicauth.go (2)
21-21
: Good extraction of the scheme constantReplacing the magic string with
basicScheme
improves readability.
71-76
: Conditional password storage implemented correctlyThe 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 – LGTMIncluding sane defaults for
Charset
andStorePassword
keeps behaviour predictable.
@sixcolors can you check |
Summary
StorePassword
config option. Defaults toFalse
to avoid leaking credentials viaContext
.charset
parameter. Defaults toUTF-8
."no-store"
header for Cache Control.