Skip to content

Fix: Prevent predictable token generation on entropy exhaustion (Issue #65)#128

Open
diksha78dev wants to merge 1 commit into
roshankumar0036singh:mainfrom
diksha78dev:fix/issue-65
Open

Fix: Prevent predictable token generation on entropy exhaustion (Issue #65)#128
diksha78dev wants to merge 1 commit into
roshankumar0036singh:mainfrom
diksha78dev:fix/issue-65

Conversation

@diksha78dev

@diksha78dev diksha78dev commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Closes #65.

Root Cause:
GenerateRandomString silently ignored the error returned by crypto/rand.Read. If the system exhausted its entropy pool, rand.Read would fail, resulting in a predictable, zero-filled byte array being base64-encoded and used as secure tokens.

Changes:

  • Updated token_helper.go to return (string, error) and explicitly fail on rand.Read errors.
  • Updated all callers in auth_service.go to handle and propagate the generation error.
  • Updated token_service_test.go to assert the new error signature.

All tests pass. No unrelated formatting changes included.

Checklist

  • I have read and signed the CLA by commenting I have read the CLA and agree to its terms. on this PR.
  • My changes follow the project's coding style.
  • I have tested my changes.

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling in authentication features (password reset, email verification, OAuth login) to properly detect and report token generation failures, enhancing system reliability and preventing silent failures.

@github-actions

github-actions Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA. ✅ Thank you!
Posted by the CLA Assistant Lite bot.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

GenerateRandomString in token_helper.go is changed to return (string, error), checking rand.Read and wrapping failures with fmt. Three call sites in auth_service.go (ForgotPassword, sendVerificationEmail, LoginWithOAuth) are updated to capture and propagate the error. The corresponding unit test is updated to assert the error is nil.

Changes

rand.Read error propagation

Layer / File(s) Summary
GenerateRandomString signature and error return
internal/service/token_helper.go, internal/service/token_service_test.go
GenerateRandomString now returns (string, error), imports fmt, checks rand.Read, and wraps failures. The unit test captures both return values and asserts the error is nil and the string is non-empty.
Caller updates in auth_service.go
internal/service/auth_service.go
ForgotPassword, sendVerificationEmail, and LoginWithOAuth each capture (randomToken/password, err) from GenerateRandomString and return early on failure instead of silently using a zero-filled token.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hop hop, the rabbit checks its tracks,
No silent zeros slipping through the cracks!
rand.Read now speaks its mind with flair,
An error returned—a token laid bare.
Three callers updated, the path is clear,
Safe random strings for every frontier! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: fixing predictable token generation on entropy exhaustion, and references the linked issue.
Description check ✅ Passed The description provides root cause analysis, specific changes made, testing confirmation, and completes the required checklist.
Linked Issues check ✅ Passed The PR fully implements both acceptance criteria from issue #65: GenerateRandomString now returns (string, error) and all callers in auth_service.go have been updated to handle and propagate the error.
Out of Scope Changes check ✅ Passed All code changes are directly related to addressing the token generation security vulnerability in issue #65; no out-of-scope changes detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud

Copy link
Copy Markdown

@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

🧹 Nitpick comments (1)
internal/service/token_service_test.go (1)

64-75: 💤 Low value

Consider adding test coverage for the error path.

The test currently verifies successful token generation but doesn't cover the case where rand.Read fails. While mocking crypto/rand in Go is non-trivial, consider adding a test case that validates the error return behavior to ensure the security fix is fully covered.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/token_service_test.go` around lines 64 - 75, Add additional
test cases to TestTokenService_GenerateRandomString to verify error handling
when rand.Read fails. Create separate test subtests or test functions that
validate the error return path of the GenerateRandomString method, ensuring it
properly handles and returns errors when random number generation fails. While
mocking the crypto/rand package is challenging in Go, implement the error test
case using available testing techniques to ensure the error handling logic in
GenerateRandomString is validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/service/auth_service.go`:
- Around line 125-128: The error returned when GenerateRandomString fails
reveals user existence to attackers, breaking email enumeration protection.
Instead of returning the error directly when GenerateRandomString fails, log the
error internally and return the same nil response that is returned when a user
doesn't exist. This ensures attackers cannot distinguish between a non-existent
user and a token generation failure by observing different response behaviors.
Modify the error handling block after the GenerateRandomString call to log the
error and return nil instead of propagating the error.

---

Nitpick comments:
In `@internal/service/token_service_test.go`:
- Around line 64-75: Add additional test cases to
TestTokenService_GenerateRandomString to verify error handling when rand.Read
fails. Create separate test subtests or test functions that validate the error
return path of the GenerateRandomString method, ensuring it properly handles and
returns errors when random number generation fails. While mocking the
crypto/rand package is challenging in Go, implement the error test case using
available testing techniques to ensure the error handling logic in
GenerateRandomString is validated.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4f9af597-4344-4546-b308-f19d27ae1322

📥 Commits

Reviewing files that changed from the base of the PR and between e511968 and 0223561.

📒 Files selected for processing (3)
  • internal/service/auth_service.go
  • internal/service/token_helper.go
  • internal/service/token_service_test.go

Comment on lines +125 to +128
randomToken, err := s.tokenService.GenerateRandomString(32)
if err != nil {
return err
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Email enumeration vulnerability: token generation error reveals user existence.

Returning the error directly when GenerateRandomString fails breaks the email enumeration protection. An attacker can distinguish between:

  • User doesn't exist → nil return (line 118)
  • User exists but token generation failed → error return (line 127)

This allows attackers to enumerate valid email addresses by observing different response behaviors.

🔒 Proposed fix to preserve email enumeration protection
 	// Create new reset token
 	randomToken, err := s.tokenService.GenerateRandomString(32)
 	if err != nil {
-		return err
+		// Return nil to prevent email enumeration (same as user not found case)
+		// Log the error internally for monitoring
+		return nil
 	}
📝 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
randomToken, err := s.tokenService.GenerateRandomString(32)
if err != nil {
return err
}
randomToken, err := s.tokenService.GenerateRandomString(32)
if err != nil {
// Return nil to prevent email enumeration (same as user not found case)
// Log the error internally for monitoring
return nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/auth_service.go` around lines 125 - 128, The error returned
when GenerateRandomString fails reveals user existence to attackers, breaking
email enumeration protection. Instead of returning the error directly when
GenerateRandomString fails, log the error internally and return the same nil
response that is returned when a user doesn't exist. This ensures attackers
cannot distinguish between a non-existent user and a token generation failure by
observing different response behaviors. Modify the error handling block after
the GenerateRandomString call to log the error and return nil instead of
propagating the error.

@diksha78dev

diksha78dev commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

I have read the CLA and agree to its terms.

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@diksha78dev handle the coderabbit suugestion

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@diksha78dev till when will it be ready

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.

token_helper.go silently ignores rand.Read errors

2 participants