Skip to content

fix: encrypt the cookie in sessions - #225

Merged
steveiliop56 merged 3 commits into
mainfrom
fix/sessions
Jul 3, 2025
Merged

steveiliop56 merged 3 commits into
mainfrom
fix/sessions

Conversation

@steveiliop56

@steveiliop56 steveiliop56 commented Jul 3, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Improved authentication security by using separate secrets for HMAC and encryption.
  • Bug Fixes
    • Enhanced session retrieval reliability by retrying after failed attempts and clearing invalid session cookies.

@coderabbitai

coderabbitai Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce a key derivation process to generate separate HMAC and encryption secrets from a main secret using HKDF. The authentication configuration and session management are updated to use these distinct keys. Error handling is improved when retrieving sessions, and a utility function for key derivation is added.

Changes

Files/Paths Change Summary
cmd/root.go Implements key derivation for HMAC and encryption secrets; updates authConfig usage accordingly.
internal/types/config.go Replaces Secret field in AuthConfig with HMACSecret and EncryptionSecret.
internal/utils/utils.go Adds DeriveKey function using HKDF (SHA-256) to derive 24-byte keys from a secret and info string.
internal/auth/auth.go Updates session store to use both HMAC and encryption secrets; enhances session retrieval error handling with retry.
internal/api/api_test.go Updates test authConfig to use separate HMACSecret and EncryptionSecret fields instead of Secret.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GinContext
    participant Auth
    participant SessionStore
    participant Utils

    User->>GinContext: Sends request
    GinContext->>Auth: GetSession()
    Auth->>SessionStore: Create store with HMACSecret, EncryptionSecret
    Auth->>SessionStore: Get session
    alt Session retrieval fails
        Auth->>GinContext: Clear session cookie
        Auth->>SessionStore: Retry Get session
        alt Retry fails
            Auth->>GinContext: Log error, return error
        end
    end
    Auth->>GinContext: Return session
Loading

Poem

In the warren where secrets are spun,
Now two keys are better than one!
With HMAC and encryption apart,
Security’s given a jumpstart.
Derive, encode, and handle with care—
A rabbit’s touch is everywhere!
🐇🔑✨

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7640e95 and ebcf6e6.

📒 Files selected for processing (4)
  • cmd/root.go (2 hunks)
  • internal/auth/auth.go (2 hunks)
  • internal/types/config.go (1 hunks)
  • internal/utils/utils.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
cmd/root.go (1)
internal/utils/utils.go (1)
  • DeriveKey (413-440)
internal/auth/auth.go (2)
internal/types/config.go (1)
  • Config (4-39)
internal/constants/constants.go (1)
  • SessionCookieName (17-17)
🔇 Additional comments (4)
internal/types/config.go (1)

88-89: LGTM! Good security practice to separate HMAC and encryption keys.

Using separate keys for HMAC and encryption follows cryptographic best practices and improves security by ensuring that each key serves a single purpose.

cmd/root.go (2)

77-84: LGTM! Proper implementation of key derivation.

The code correctly derives separate HMAC and encryption keys using distinct context strings. Error handling is appropriate and follows the established pattern in the codebase.


133-134: LGTM! Correct assignment of derived secrets.

The AuthConfig properly uses the derived HMAC and encryption secrets, completing the transition to separate cryptographic keys.

internal/auth/auth.go (1)

36-36: LGTM! Correct usage of separate HMAC and encryption keys.

The cookie store properly uses the derived HMAC and encryption secrets in the correct order for the gorilla/sessions library.

Comment thread internal/utils/utils.go
Comment thread internal/auth/auth.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 ebcf6e6 and 5409aa5.

📒 Files selected for processing (1)
  • internal/api/api_test.go (1 hunks)

Comment thread internal/api/api_test.go Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
internal/utils/utils.go (1)

413-440: Good implementation with proper fix for previous truncation issue.

The DeriveKey function correctly implements HKDF-based key derivation and addresses the previous concern about key truncation. The function now derives 24 bytes and returns the full base64 encoded string (32 characters), preserving all entropy.

A few observations:

  1. ✅ Fixed truncation issue: 24 bytes encode to exactly 32 base64 characters without truncation
  2. ✅ Proper error handling: Checks for HKDF errors and empty keys
  3. ✅ Security practices: Uses HKDF with SHA-256 and validates the derived key

The comment about not using a salt is actually acceptable in this context since you're deriving different keys using different info parameters, which provides the necessary differentiation.

Consider adding input validation for empty parameters:

func DeriveKey(secret string, info string) (string, error) {
+	// Validate inputs
+	if secret == "" {
+		return "", errors.New("secret cannot be empty")
+	}
+	if info == "" {
+		return "", errors.New("info cannot be empty")
+	}
+
	// Create hashing function
	hash := sha256.New
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5409aa5 and acc3ad9.

📒 Files selected for processing (3)
  • internal/api/api_test.go (1 hunks)
  • internal/auth/auth.go (2 hunks)
  • internal/utils/utils.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/api/api_test.go
  • internal/auth/auth.go
🔇 Additional comments (1)
internal/utils/utils.go (1)

4-5: LGTM! New imports are appropriate for HKDF implementation.

The added imports (bytes, crypto/sha256, io, golang.org/x/crypto/hkdf) are correctly used in the new DeriveKey function for cryptographic key derivation.

Also applies to: 8-8, 17-17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant