Skip to content

Conversation

gaby
Copy link
Member

@gaby gaby commented Jul 29, 2025

Summary

  • implement SHA/Bcrypt based auth verification in config
  • default to SHA-256 hashes when no prefix provided
  • document hashed password requirement
  • update tests for SHA-256 hashes

Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

Walkthrough

The BasicAuth middleware was updated to require and support hashed passwords (SHA-256, SHA-512, SHA-1, MD5, bcrypt) instead of plaintext. Documentation and tests were revised to reflect these changes, including new helper and test functions for various hash formats. The configuration now interprets password hashes and verifies credentials accordingly.

Changes

Cohort / File(s) Change Summary
Documentation Updates
docs/middleware/basicauth.md, docs/whats_new.md
Updated documentation to require hashed passwords, describe supported hash formats, clarify configuration options, and document new middleware behaviors and options.
Test Enhancements
middleware/basicauth/basicauth_test.go
Replaced plaintext passwords with hashed equivalents in tests. Added helper functions for generating hashes. Introduced comprehensive tests for all supported hash types and their validation logic.
Config & Core Logic
middleware/basicauth/config.go
Refactored config to parse and verify multiple hash formats. Added parseHashedPassword function to generate password verifier functions based on hash type. Updated user authentication logic to use these verifiers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Config

    Client->>Middleware: Sends request with Authorization header
    Middleware->>Config: Looks up user verifier by username
    Config-->>Middleware: Returns password verifier function
    Middleware->>Middleware: Calls verifier with provided password
    alt Password valid
        Middleware-->>Client: Allow request to proceed
    else Password invalid
        Middleware-->>Client: Respond with 401 Unauthorized
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • sixcolors
  • ReneWerner87

Poem

A rabbit with whiskers, so clever and neat,
Hopped through the hashes, no plaintext to greet.
With bcrypt and SHA, the passwords are strong,
The docs and the tests all hop right along.
Secure now we munch, on carrots and code—
This patch is a feast on the fiber road! 🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-07-29-14-32-59

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 generate unit tests to generate unit tests for 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.

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!

I've implemented a significant security enhancement to the BasicAuth middleware. This change moves away from plaintext password storage and verification, instead requiring and supporting various hashed password formats like SHA-256 and bcrypt. This makes the BasicAuth component more robust and secure by design.

Highlights

  • Enhanced Security for BasicAuth: The BasicAuth middleware now exclusively accepts pre-hashed passwords (e.g., SHA-256, bcrypt) instead of plaintext, greatly improving credential security.
  • Multi-Algorithm Hashing Support: I've added support for multiple hashing algorithms, including SHA-256 (default), bcrypt, SHA-512, SHA-1, and MD5, identified by specific prefixes.
  • Internalized Hashing Logic: The external go-htpasswd dependency has been removed, and the password verification logic for various hash types is now handled internally within the middleware.
  • Updated Documentation: The documentation has been updated to clearly reflect the new requirement for hashed passwords and provide examples of their usage.
  • Comprehensive Test Coverage: All relevant tests have been updated to incorporate the new hashed password verification, ensuring the feature's correctness and reliability.
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 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 or fill out our survey 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.

Copy link

codecov bot commented Jul 29, 2025

Codecov Report

❌ Patch coverage is 68.75000% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.76%. Comparing base (deabee4) to head (c11533b).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
middleware/basicauth/config.go 68.75% 13 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3631      +/-   ##
==========================================
+ Coverage   91.14%   91.76%   +0.61%     
==========================================
  Files         113      113              
  Lines       11388    11410      +22     
==========================================
+ Hits        10380    10470      +90     
+ Misses        750      675      -75     
- Partials      258      265       +7     
Flag Coverage Δ
unittests 91.76% <68.75%> (+0.61%) ⬆️

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 introduces support for hashed passwords in the BasicAuth middleware, which is a great security improvement. The implementation correctly handles bcrypt and various SHA hashes. My review focuses on further improving security by removing weak hashing algorithms, enhancing documentation clarity, and improving test code quality and maintainability. The most critical issue is the support for MD5 and SHA-1, which are insecure for password hashing.

Comment on lines 52 to 55
Authorizer: func(user, pass string, c fiber.Ctx) bool {
if user == "john" && pass == "doe" {
return true
}
if user == "admin" && pass == "123456" {
return true
}
return false
// custom validation logic
return (user == "john" || user == "admin")
},
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 example for Authorizer is a bit confusing as it doesn't use the pass parameter, which would result in a linter warning in a real Go program (pass declared and not used).

To make the example clearer and more practical, I suggest modifying it to demonstrate a simple custom validation that uses both the username and password.

Suggested change
Authorizer: func(user, pass string, c fiber.Ctx) bool {
if user == "john" && pass == "doe" {
return true
}
if user == "admin" && pass == "123456" {
return true
}
return false
// custom validation logic
return (user == "john" || user == "admin")
},
Authorizer: func(user, pass string, c fiber.Ctx) bool {
// custom validation logic
if user == "admin" && pass == "supersecret" {
return true
}
return false
},

@gaby gaby added this to v3 Jul 30, 2025
@gaby gaby added this to the v3 milestone Jul 30, 2025
@gaby gaby moved this to In Progress in v3 Jul 30, 2025
@gaby gaby changed the title Support hashed BasicAuth passwords 🔥 feat: Support hashed BasicAuth passwords Jul 30, 2025
@gaby gaby marked this pull request as ready for review July 30, 2025 04:37
@Copilot Copilot AI review requested due to automatic review settings July 30, 2025 04:37
@gaby gaby requested a review from a team as a code owner July 30, 2025 04:37
Copy link
Contributor

@Copilot 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 implements support for hashed password authentication in the BasicAuth middleware, replacing plaintext password storage with secure hashing mechanisms. The change enhances security by requiring pre-hashed passwords and supports multiple hash algorithms including SHA-256, SHA-512, SHA-1, MD5, and bcrypt.

Key changes:

  • Replaced plaintext password comparison with hash verification using multiple algorithms
  • Added default SHA-256 hashing when no prefix is provided
  • Updated all tests to use hashed passwords instead of plaintext

Reviewed Changes

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

File Description
middleware/basicauth/config.go Implements hash parsing and verification logic with support for multiple algorithms
middleware/basicauth/basicauth_test.go Updates all test cases to use hashed passwords and adds comprehensive hash variant testing
docs/whats_new.md Documents the breaking change requiring hashed passwords
docs/middleware/basicauth.md Updates documentation with hash format examples and requirements

for u, hpw := range cfg.Users {
v, err := parseHashedPassword(hpw)
if err != nil {
panic(err)
Copy link
Preview

Copilot AI Jul 30, 2025

Choose a reason for hiding this comment

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

Using panic() during configuration parsing can crash the entire application. Consider returning an error from configDefault() instead and handling it gracefully in the calling code.

Copilot uses AI. Check for mistakes.

Comment on lines +187 to +199
b, err := hex.DecodeString(h)
if err != nil || len(b) != sha256.Size {
if b, err = base64.StdEncoding.DecodeString(h); err != nil {
return nil, fmt.Errorf("decode SHA256 password: %w", err)
}
if len(b) != sha256.Size {
return nil, errors.New("decode SHA256 password: invalid length")
}
}
return func(p string) bool {
sum := sha256.Sum256([]byte(p))
return subtle.ConstantTimeCompare(sum[:], b) == 1
}, nil
Copy link
Preview

Copilot AI Jul 30, 2025

Choose a reason for hiding this comment

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

The fallback logic allows both hex and base64 decoding without clear validation. This could accept malformed input that happens to decode successfully. Consider being more explicit about the expected format or adding stricter validation.

Suggested change
b, err := hex.DecodeString(h)
if err != nil || len(b) != sha256.Size {
if b, err = base64.StdEncoding.DecodeString(h); err != nil {
return nil, fmt.Errorf("decode SHA256 password: %w", err)
}
if len(b) != sha256.Size {
return nil, errors.New("decode SHA256 password: invalid length")
}
}
return func(p string) bool {
sum := sha256.Sum256([]byte(p))
return subtle.ConstantTimeCompare(sum[:], b) == 1
}, nil
// Validate if the input is a valid hex string
if _, err := hex.DecodeString(h); err == nil {
b, err := hex.DecodeString(h)
if err != nil || len(b) != sha256.Size {
return nil, errors.New("decode SHA256 password: invalid hex format or length")
}
return func(p string) bool {
sum := sha256.Sum256([]byte(p))
return subtle.ConstantTimeCompare(sum[:], b) == 1
}, nil
}
// Validate if the input is a valid base64 string
if _, err := base64.StdEncoding.DecodeString(h); err == nil {
b, err := base64.StdEncoding.DecodeString(h)
if err != nil || len(b) != sha256.Size {
return nil, errors.New("decode SHA256 password: invalid base64 format or length")
}
return func(p string) bool {
sum := sha256.Sum256([]byte(p))
return subtle.ConstantTimeCompare(sum[:], b) == 1
}, nil
}
// If neither hex nor base64 validation passes, return an error
return nil, errors.New("decode SHA256 password: invalid format")

Copilot uses AI. Check for mistakes.

{"bcrypt", string(bcryptHash)},
{"sha512", sha512Hash(pass)},
{"sha256", sha256Hash(pass)},
{"sha256-hex", func() string { h := sha256.Sum256([]byte(pass)); return hex.EncodeToString(h[:]) }()},
Copy link
Preview

Copilot AI Jul 30, 2025

Choose a reason for hiding this comment

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

[nitpick] The inline function makes the test case definition hard to read. Consider extracting this to a helper function like the other hash functions or computing it before the test cases array.

Suggested change
{"sha256-hex", func() string { h := sha256.Sum256([]byte(pass)); return hex.EncodeToString(h[:]) }()},
{"sha256-hex", sha256HexHash(pass)},

Copilot uses AI. Check for mistakes.

{"bcrypt", string(bcryptHash)},
{"sha512", sha512Hash(pass)},
{"sha256", sha256Hash(pass)},
{"sha256-hex", func() string { h := sha256.Sum256([]byte(pass)); return hex.EncodeToString(h[:]) }()},
Copy link
Preview

Copilot AI Jul 30, 2025

Choose a reason for hiding this comment

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

[nitpick] Duplicate inline function logic from the previous test. Consider creating a reusable helper function or variable to avoid code duplication.

Suggested change
{"sha256-hex", func() string { h := sha256.Sum256([]byte(pass)); return hex.EncodeToString(h[:]) }()},
{"sha256-hex", sha256HexHash(pass)},

Copilot uses AI. Check for mistakes.

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

♻️ Duplicate comments (5)
middleware/basicauth/config.go (3)

4-5: Security concern: Support for weak hash algorithms MD5 and SHA1

These algorithms are cryptographically weak and vulnerable to attacks. While marked for compatibility, their use should be strongly discouraged in the documentation.


117-120: Consider returning an error instead of panic

Using panic() during configuration parsing can crash the entire application. Consider returning an error from configDefault() and handling it gracefully in the calling code.


187-199: Simplify the default case logic for better readability

The nested logic for parsing hex and base64 encoded hashes is difficult to follow and hides the original error from hex.DecodeString. Consider refactoring to handle hex and base64 decoding separately.

docs/whats_new.md (1)

1057-1057: Add security warnings for MD5 and SHA-1 hash support

The documentation mentions support for {MD5} and {SHA} (SHA-1) without security warnings. Please clarify these are supported only for backward compatibility and add strong recommendations against their use.

Also applies to: 1950-1950

middleware/basicauth/basicauth_test.go (1)

400-400: Extract inline SHA256 hex generation

The inline anonymous functions make test cases harder to read. Consider creating a helper function or using hex.EncodeToString directly.

+func sha256HexHash(p string) string {
+    sum := sha256.Sum256([]byte(p))
+    return hex.EncodeToString(sum[:])
+}

// In test cases:
-{"sha256-hex", func() string { h := sha256.Sum256([]byte(pass)); return hex.EncodeToString(h[:]) }()},
+{"sha256-hex", sha256HexHash(pass)},

Also applies to: 432-432

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a01f97 and c11533b.

📒 Files selected for processing (4)
  • docs/middleware/basicauth.md (3 hunks)
  • docs/whats_new.md (2 hunks)
  • middleware/basicauth/basicauth_test.go (14 hunks)
  • middleware/basicauth/config.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Review and update the contents of the docs folder if necessary when modifying code

Files:

  • docs/middleware/basicauth.md
  • docs/whats_new.md
🧠 Learnings (5)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#0
File: :0-0
Timestamp: 2024-12-01T10:28:36.011Z
Learning: Feature request #3224 has been created to add support for square bracket notation and comma-separated values in multipart form data in Fiber, while maintaining binary data transfer capabilities. This would bring parity with the existing form-urlencoded functionality.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-07-01T03:33:22.283Z
Learning: Unit tests for key length enforcement in `DecryptCookie` have been added to ensure consistency and security in the encryption processes.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in `DecryptCookie` have been added to ensure consistency and security in the encryption processes.
middleware/basicauth/config.go (6)

Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:257-331
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the GetByID method, when handling a decode error, use decodeErr in the error message to accurately report the decoding failure.

Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:257-331
Timestamp: 2024-10-02T22:57:30.345Z
Learning: In the GetByID method, when handling a decode error, use decodeErr in the error message to accurately report the decoding failure.

Learnt from: mdelapenya
PR: #3434
File: app.go:623-636
Timestamp: 2025-05-08T08:14:37.302Z
Learning: In the gofiber/fiber framework, service startup failures should panic rather than allowing the application to continue running with degraded functionality, as this is the agreed-upon design decision.

Learnt from: sixcolors
PR: #3625
File: middleware/session/config.go:57-58
Timestamp: 2025-07-27T17:28:53.403Z
Learning: In the session middleware Config struct, the Extractor field uses function closures (like FromCookie(key)), making it impossible to introspect extractor parameters at runtime for validation purposes without complex reflection techniques.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:16-26
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the session middleware Config struct, Store is backed by fiber.Storage; they are different entities serving distinct purposes in session management.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:16-26
Timestamp: 2024-09-25T16:17:00.969Z
Learning: In the session middleware Config struct, Store is backed by fiber.Storage; they are different entities serving distinct purposes in session management.

docs/middleware/basicauth.md (3)

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: mdelapenya
PR: #3434
File: docs/api/services.md:39-43
Timestamp: 2025-05-07T13:07:33.899Z
Learning: When documenting Go interface methods in the Fiber project, avoid showing method signatures with the interface type as the receiver (e.g., func (d *Service) Method()) since interfaces cannot be used as receivers in Go. Instead, show just the method signature without a receiver or use a placeholder implementation name.

docs/whats_new.md (8)

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: hcancelik
PR: #3036
File: docs/middleware/cache.md:103-103
Timestamp: 2024-06-15T19:26:06.401Z
Learning: There are no hard tabs in the lines 100 to 105 of the docs/middleware/cache.md file. Future comments about formatting should accurately reflect the actual content.

Learnt from: hcancelik
PR: #3036
File: docs/middleware/cache.md:103-103
Timestamp: 2024-10-08T19:06:06.583Z
Learning: There are no hard tabs in the lines 100 to 105 of the docs/middleware/cache.md file. Future comments about formatting should accurately reflect the actual content.

Learnt from: ckoch786
PR: #3230
File: docs/whats_new.md:944-951
Timestamp: 2024-12-15T19:56:45.935Z
Learning: Detailed usage examples and explanations for new methods like RemoveRoute and RemoveRouteByName are documented in docs/api/app.md, so it's unnecessary to duplicate them in docs/whats_new.md.

Learnt from: sixcolors
PR: #3598
File: docs/middleware/csrf.md:37-42
Timestamp: 2025-07-19T14:06:29.884Z
Learning: In Fiber v3, the CookieSameSite constants use lowercase values: CookieSameSiteLaxMode = "lax", CookieSameSiteStrictMode = "strict", CookieSameSiteNoneMode = "none". Documentation examples should use lowercase string values or the typed constants, not capitalized strings like "Lax".

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using ctx.Response.Header.Cookie may not be suitable for parsing cookies from the response header, as it requires a *Cookie and fills it rather than returning a string value; thus, manual parsing of the Set-Cookie header may be necessary.

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
Learning: In the Fiber framework tests, using ctx.Response.Header.Cookie may not be suitable for parsing cookies from the response header, as it requires a *Cookie and fills it rather than returning a string value; thus, manual parsing of the Set-Cookie header may be necessary.

middleware/basicauth/basicauth_test.go (28)

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both EncryptCookie and DecryptCookie functions have been added to ensure robust validation and prevent potential runtime errors.

Learnt from: sixcolors
PR: #3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for Session.Save already exist in the middleware/session/session_test.go file, specifically in the Test_Session_Save and Test_Session_Save_Expiration functions.

Learnt from: sixcolors
PR: #3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for Session.Save already exist in the middleware/session/session_test.go file, specifically in the Test_Session_Save and Test_Session_Save_Expiration functions.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The encryptcookie_test.go file contains unit tests that validate key lengths for both EncryptCookie and DecryptCookie functions, ensuring that invalid key lengths raise appropriate errors.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The encryptcookie_test.go file contains unit tests that validate key lengths for both EncryptCookie and DecryptCookie functions, ensuring that invalid key lengths raise appropriate errors.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in DecryptCookie have been added to ensure consistency and security in the encryption processes.

Learnt from: gaby
PR: #3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-07-01T03:33:22.283Z
Learning: Unit tests for key length enforcement in DecryptCookie have been added to ensure consistency and security in the encryption processes.

Learnt from: sixcolors
PR: #3016
File: middleware/session/middleware_test.go:400-407
Timestamp: 2024-09-25T17:09:03.756Z
Learning: In the Test_Session_Next function in middleware/session/middleware_test.go, the variable doNext is properly synchronized with the muNext mutex for both read and write access.

Learnt from: sixcolors
PR: #2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Learnt from: efectn
PR: #3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the require methods from the testify package for assertions instead of manual comparisons and calls to t.Fatal or t.Fatalf.

Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.

Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.

Learnt from: sixcolors
PR: #2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
Learning: In the Fiber framework tests, using ctx.Response.Header.Cookie may not be suitable for parsing cookies from the response header, as it requires a *Cookie and fills it rather than returning a string value; thus, manual parsing of the Set-Cookie header may be necessary.

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using ctx.Response.Header.Cookie may not be suitable for parsing cookies from the response header, as it requires a *Cookie and fills it rather than returning a string value; thus, manual parsing of the Set-Cookie header may be necessary.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:16-26
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the session middleware Config struct, Store is backed by fiber.Storage; they are different entities serving distinct purposes in session management.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:16-26
Timestamp: 2024-09-25T16:17:00.969Z
Learning: In the session middleware Config struct, Store is backed by fiber.Storage; they are different entities serving distinct purposes in session management.

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:164-165
Timestamp: 2024-09-25T17:08:07.693Z
Learning: In the Test_CSRF_WithSession_Middleware function, calling session.NewWithStore() without arguments is acceptable, as the default configuration is sufficient.

Learnt from: gaby
PR: #3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the middleware/adaptor/adaptor.go file of the Fiber framework, when updating context handling, replacing c.Context() with c.RequestCtx() is appropriate to access the fasthttp.RequestCtx.

Learnt from: efectn
PR: #3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the Test_App_ShutdownWithContext function in app_test.go, the clientDone channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional time.Sleep calls.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:122-122
Timestamp: 2024-09-25T16:18:34.719Z
Learning: In DefaultErrorHandler(c *fiber.Ctx, err error), since c is a pointer to an interface, we need to dereference *c when calling interface methods like SendStatus.

Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:122-122
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In DefaultErrorHandler(c *fiber.Ctx, err error), since c is a pointer to an interface, we need to dereference *c when calling interface methods like SendStatus.

Learnt from: ReneWerner87
PR: #3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the Test method in app.go.

Learnt from: gaby
PR: #3170
File: ctx_test.go:1721-1724
Timestamp: 2024-10-16T12:12:30.506Z
Learning: In the Go unit tests in ctx_test.go, it is acceptable to use invalid CIDR notation such as "0.0.0.1/31junk" for testing purposes.

Learnt from: sixcolors
PR: #3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-09-25T17:05:06.991Z
Learning: When testing session IdleTimeout expiration, it's acceptable to use time.Sleep to simulate the passage of time in tests.

Learnt from: sixcolors
PR: #3016
File: middleware/csrf/csrf_test.go:164-165
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Test_CSRF_WithSession_Middleware function, calling session.NewWithStore() without arguments is acceptable, as the default configuration is sufficient.

Learnt from: sixcolors
PR: #3625
File: middleware/session/config.go:57-58
Timestamp: 2025-07-27T17:28:53.403Z
Learning: In the session middleware Config struct, the Extractor field uses function closures (like FromCookie(key)), making it impossible to introspect extractor parameters at runtime for validation purposes without complex reflection techniques.

🔇 Additional comments (4)
middleware/basicauth/basicauth_test.go (4)

21-39: Well-structured helper functions

Good implementation of helper functions to reduce code duplication across tests. This addresses the previous concern about repeated SHA256 hash creation logic.


61-63: Proper error handling for bcrypt

Good job adding error handling for bcrypt.GenerateFromPassword using require.NoError.


355-386: Comprehensive test coverage for parseHashedPassword

Excellent test coverage that validates all supported hash formats and includes both positive and negative test cases.


388-449: Excellent integration test coverage

The HashVariants tests provide comprehensive coverage of the BasicAuth middleware with all supported hash formats, testing both successful and failed authentication scenarios.

Comment on lines +69 to +71
- `"{SHA512}"`, `"{SHA256}"`, or `"{SHA}"` followed by a base64 encoded digest
- `"{MD5}"` followed by a base64 encoded digest
- standard bcrypt strings beginning with `$2`
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add security warnings for weak hash algorithms

The documentation mentions {SHA} (SHA-1) and {MD5} without any security warnings. Please add a clear warning that these algorithms are insecure and supported only for backward compatibility. Recommend using bcrypt or SHA-256/SHA-512 instead.

- `"{SHA512}"`, `"{SHA256}"`, or `"{SHA}"` followed by a base64 encoded digest
- `"{MD5}"` followed by a base64 encoded digest
+ `"{SHA512}"`, `"{SHA256}"` followed by a base64 encoded digest
+ `"{SHA}"` (SHA-1) followed by a base64 encoded digest (**insecure, use only for backward compatibility**)
+ `"{MD5}"` followed by a base64 encoded digest (**insecure, use only for backward compatibility**)
- standard bcrypt strings beginning with `$2`
+ standard bcrypt strings beginning with `$2` (**recommended**)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- `"{SHA512}"`, `"{SHA256}"`, or `"{SHA}"` followed by a base64 encoded digest
- `"{MD5}"` followed by a base64 encoded digest
- standard bcrypt strings beginning with `$2`
- `"{SHA512}"`, `"{SHA256}"` followed by a base64 encoded digest
- `"{SHA}"` (SHA-1) followed by a base64 encoded digest (**insecure, use only for backward compatibility**)
- `"{MD5}"` followed by a base64 encoded digest (**insecure, use only for backward compatibility**)
- standard bcrypt strings beginning with `$2` (**recommended**)
🤖 Prompt for AI Agents
In docs/middleware/basicauth.md around lines 69 to 71, add a clear security
warning that the `{SHA}` (SHA-1) and `{MD5}` hash algorithms are insecure and
only supported for backward compatibility. Update the documentation to recommend
using stronger algorithms like bcrypt or SHA-256/SHA-512 instead, emphasizing
best security practices.

@ReneWerner87 ReneWerner87 merged commit 2e544ae into main Jul 30, 2025
14 of 15 checks passed
@ReneWerner87 ReneWerner87 deleted the 2025-07-29-14-32-59 branch July 30, 2025 06:45
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jul 30, 2025
@ReneWerner87
Copy link
Member

cli migration gofiber/cli#150

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