Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented May 28, 2025

Summary

  • ensure cookies are removed when decryption fails
  • validate user-provided encryption key early during middleware setup instead of during runtime.
  • add invalid config keys unit tests
  • refactor duplicate key validation code into one common function

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 28, 2025

Walkthrough

This update introduces explicit encryption key validation in the configDefault function, centralizes key decoding and validation logic into reusable helper functions, and modifies cookie error handling to remove invalid cookies instead of clearing their values. Unit tests are added to verify the new key validation behavior.

Changes

File(s) Change Summary
middleware/encryptcookie/config.go Adds explicit validation of encryption key in configDefault using new validateKey function.
middleware/encryptcookie/config_test.go Introduces unit tests for key validation logic in configDefault.
middleware/encryptcookie/encryptcookie.go Changes error handling to delete cookies upon decryption failure instead of clearing their values.
middleware/encryptcookie/utils.go Refactors key decoding/validation into new decodeKey and validateKey helpers; updates related function logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Utils

    Client->>Middleware: Send request with encrypted cookie
    Middleware->>Utils: validateKey(cfg.Key)
    alt Key invalid
        Utils-->>Middleware: error
        Middleware-->>Client: Panic with error
    else Key valid
        Utils-->>Middleware: success
        Middleware->>Utils: DecryptCookie(cookie, key)
        alt Decryption fails
            Utils-->>Middleware: error
            Middleware->>Middleware: DelCookieBytes(key)
        else Decryption succeeds
            Utils-->>Middleware: decrypted value
            Middleware->>Client: Proceed with request
        end
    end
Loading

Possibly related PRs

  • gofiber/fiber#3056: Both PRs modify key length validation logic in middleware/encryptcookie/utils.go and related configuration, making their changes directly related.

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

Encryption keys must fit just right,
Or panics send us into fright.
Now cookies vanish, not just fade,
With helpers new, our code’s remade.
Tests ensure we’re safe and sound—
In Fiber’s fields, security’s found!
🥕✨


📜 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 a779888 and ab6755e.

📒 Files selected for processing (4)
  • middleware/encryptcookie/config.go (1 hunks)
  • middleware/encryptcookie/config_test.go (1 hunks)
  • middleware/encryptcookie/encryptcookie.go (1 hunks)
  • middleware/encryptcookie/utils.go (2 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
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: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: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: 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.
middleware/encryptcookie/config_test.go (4)
Learnt from: gaby
PR: gofiber/fiber#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: gofiber/fiber#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: 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.
middleware/encryptcookie/utils.go (2)
Learnt from: gaby
PR: gofiber/fiber#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: gofiber/fiber#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.
🧬 Code Graph Analysis (1)
middleware/encryptcookie/config_test.go (2)
middleware/encryptcookie/config.go (1)
  • Config (8-35)
middleware/encryptcookie/utils.go (1)
  • ErrInvalidKeyLength (14-14)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.24.x, macos-13)
🔇 Additional comments (8)
middleware/encryptcookie/encryptcookie.go (1)

26-26: Excellent improvement to cookie error handling.

Changing from clearing the cookie value to deleting the entire cookie when decryption fails is a more secure and logical approach. This prevents leaving corrupted or invalid cookies in the request headers.

middleware/encryptcookie/config.go (1)

77-79: Excellent addition of early key validation.

Adding validateKey(cfg.Key) during configuration setup implements fail-fast validation, catching invalid encryption keys at initialization time rather than during runtime operations. This improves error handling and developer experience.

middleware/encryptcookie/config_test.go (2)

12-22: Well-structured test for invalid base64 key validation.

The test properly validates that configDefault panics with the correct error message when given an invalid base64 key. The approach of comparing expected error strings ensures robust validation.


24-33: Comprehensive test for invalid key length validation.

The test effectively validates the key length requirement by generating a 20-byte key (invalid length) and verifying that configDefault panics with ErrInvalidKeyLength. This aligns with the retrieved learnings about key length enforcement.

middleware/encryptcookie/utils.go (4)

16-30: Excellent refactoring with the decodeKey function.

This centralized function eliminates code duplication and provides consistent base64 decoding and length validation. The error handling is comprehensive, wrapping base64 errors with descriptive messages while using the dedicated ErrInvalidKeyLength for length validation.


32-36: Clean validation interface with validateKey.

This simple wrapper function provides a clean interface for key validation that's used in the config setup. The design follows the single responsibility principle effectively.


39-43: Good refactoring in EncryptCookie function.

The replacement of inline key validation with decodeKey() call eliminates code duplication while maintaining the same error handling behavior. This improves maintainability and consistency across the codebase.


66-69: Consistent refactoring in DecryptCookie function.

Similar to EncryptCookie, the use of decodeKey() eliminates duplicate validation logic and ensures consistent error handling across both encryption and decryption operations.

✨ 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.

@codecov
Copy link

codecov bot commented May 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.89%. Comparing base (a779888) to head (ab6755e).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3491      +/-   ##
==========================================
+ Coverage   83.81%   83.89%   +0.07%     
==========================================
  Files         120      120              
  Lines       12261    12268       +7     
==========================================
+ Hits        10277    10292      +15     
+ Misses       1559     1553       -6     
+ Partials      425      423       -2     
Flag Coverage Δ
unittests 83.89% <100.00%> (+0.07%) ⬆️

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.

@gaby gaby added this to v3 May 28, 2025
@gaby gaby added this to the v3 milestone May 28, 2025
@gaby gaby changed the title Fix encryptcookie deletion behavior 🧹 chore: Validate key during configuration of EncryptCookie middleware May 28, 2025
@gaby gaby changed the title 🧹 chore: Validate key during configuration of EncryptCookie middleware 🧹 chore: Improve config validation for EncryptCookie middleware May 28, 2025
@gaby gaby changed the title 🧹 chore: Improve config validation for EncryptCookie middleware 🧹 chore: Enhance config validation in EncryptCookie middleware May 28, 2025
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: ab6755e Previous: a779888 Ratio
Benchmark_Ctx_IsProxyTrusted/NoProxyCheckParallel 1.421 ns/op 0 B/op 0 allocs/op 0.9416 ns/op 0 B/op 0 allocs/op 1.51
Benchmark_Ctx_IsProxyTrusted/NoProxyCheckParallel - ns/op 1.421 ns/op 0.9416 ns/op 1.51

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

@gaby gaby marked this pull request as ready for review May 28, 2025 12:18
@gaby gaby requested a review from a team as a code owner May 28, 2025 12:18
@gaby gaby requested review from ReneWerner87, efectn and sixcolors May 28, 2025 12:18
@gaby gaby moved this to In Progress in v3 May 28, 2025
@ReneWerner87 ReneWerner87 merged commit 09d9e16 into main May 28, 2025
13 of 14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 May 28, 2025
@gaby gaby deleted the codex/analyze-and-fix-middleware/encryptcookie branch May 28, 2025 13:29
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