Skip to content

refactor: consolidate duplicate random string generators#104

Open
ManthanSiroya wants to merge 3 commits into
roshankumar0036singh:mainfrom
ManthanSiroya:refactor-random-string-generator
Open

refactor: consolidate duplicate random string generators#104
ManthanSiroya wants to merge 3 commits into
roshankumar0036singh:mainfrom
ManthanSiroya:refactor-random-string-generator

Conversation

@ManthanSiroya

@ManthanSiroya ManthanSiroya commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR consolidates duplicate random string generation logic into a single shared utility function to reduce duplication and improve consistency.

Previously, the repository had two separate implementations:

  • TokenService.GenerateRandomString() in token_helper.go (ignored errors)
  • generateRandomString() in oauth_provider_service.go (returned errors)

This caused inconsistent behavior and increased maintenance overhead.

Changes Made

Added shared utility

  • Added a shared GenerateRandomString() function in the utils package for centralized random string generation.

Removed duplicate implementations

  • Removed duplicate random string generation logic from:

    • token_helper.go
    • oauth_provider_service.go

Updated callers

  • Updated all callers to use the shared utility function.
  • Added proper error handling where random string generation is used.

Test updates

  • Updated affected tests to align with the new shared implementation behavior.

Benefits

  • Removes duplicated logic
  • Ensures consistent random string generation behavior
  • Properly handles random generation errors
  • Improves maintainability and future extensibility

Fixes #66

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

Release Notes

  • Improvements
    • Enhanced error handling in authentication flows (password reset, email verification, OAuth registration) to ensure failures are properly reported to users.
    • Consolidated token generation logic across services for improved consistency and reliability.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@ManthanSiroya, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 55 minutes and 39 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e0a41c4d-f9d9-4e44-9056-f17d657dceaf

📥 Commits

Reviewing files that changed from the base of the PR and between f96d7c7 and 9880e8d.

📒 Files selected for processing (3)
  • internal/service/auth_service.go
  • internal/service/token_service_test.go
  • internal/utils/random.go
📝 Walkthrough

Walkthrough

A new internal/utils/random.go introduces a single exported GenerateRandomString(length int) (string, error) backed by crypto/rand. TokenService.GenerateRandomString is updated to delegate to it with error propagation. The duplicate local helper in oauth_provider_service.go is deleted and its call sites migrate to utils.GenerateRandomString. Three call sites in auth_service.go add error handling for the now-error-returning signature.

Changes

Random String Consolidation

Layer / File(s) Summary
New shared utility
internal/utils/random.go
Adds exported GenerateRandomString(length int) (string, error) using crypto/rand, base64 URL-encoding, and truncation to the requested length.
TokenService wrapper and test
internal/service/token_helper.go, internal/service/token_service_test.go
GenerateRandomString signature changes from string to (string, error), delegates to utils.GenerateRandomString; test updated to capture error and assert exact string length.
OAuth provider service migration
internal/service/oauth_provider_service.go
Removes crypto/rand/encoding/base64 imports and the local generateRandomString helper; CreateClient, GenerateAuthorizationCode, and ExchangeCodeForToken now call utils.GenerateRandomString.
Auth service error handling
internal/service/auth_service.go
ForgotPassword, sendVerificationEmail, and LoginWithOAuth now capture the error from GenerateRandomString(32) and return early on failure.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hop hop, no more clones in sight,
One random helper, done just right.
crypto/rand fills each byte with care,
Errors caught now, none left bare.
A single source of truth—how neat!
✨ This bunny's code review is complete.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 accurately summarizes the main change: consolidating duplicate random string generators into a shared utility.
Linked Issues check ✅ Passed All coding requirements from issue #66 are met: consolidated random string function in utils package and all callers updated to use the shared implementation.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the objective of consolidating duplicate random string generators; no out-of-scope modifications detected.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering all required checklist items and providing clear context about the changes.

✏️ 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.

@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

🤖 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 121-124: The error returned from GenerateRandomString calls at
lines 121-124, 420-423, and 553-556 are being returned directly to handlers,
which exposes raw RNG/OS failures to clients through ErrorResponse. Instead of
returning the error directly from GenerateRandomString, wrap it with a custom
service-level error (such as ErrTokenGenerationFailed) at all three locations.
This ensures handlers receive stable, sanitized error messages that do not
expose internal implementation details to clients.

In `@internal/utils/random.go`:
- Around line 9-16: The GenerateRandomString function does not validate the
length parameter before passing it to make(), which will panic if a negative
value is provided instead of returning an error as expected from an exported
function. Add input validation at the start of GenerateRandomString to check
that length is a valid positive integer, and return an appropriate error if the
validation fails before attempting to allocate the byte slice.
🪄 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: e36fb0f4-20a9-4a19-80d1-5c0aa6a2d92e

📥 Commits

Reviewing files that changed from the base of the PR and between b73c079 and f96d7c7.

📒 Files selected for processing (5)
  • internal/service/auth_service.go
  • internal/service/oauth_provider_service.go
  • internal/service/token_helper.go
  • internal/service/token_service_test.go
  • internal/utils/random.go

Comment thread internal/service/auth_service.go
Comment thread internal/utils/random.go Outdated
@roshankumar0036singh

roshankumar0036singh commented Jun 15, 2026

Copy link
Copy Markdown
Owner

@ManthanSiroya
Token length changed from 44 → 32 chars for some tokens, and it's silent.

Password reset tokens, email verification tokens, and the temp OAuth password used to be 44 characters (base64 of 32 random bytes, untruncated). Now they're 32 chars because the new shared utils.GenerateRandomString truncates the base64 output to length. If there's a VARCHAR(44) column or anything else downstream that assumes the old length, this could cause issues. Can you double check the DB schema ?

The truncation itself reduces entropy a bit more than intended.

In utils.GenerateRandomString, we generate length random bytes, base64-encode them (~4/3 * length chars), then cut it down to length chars. So a "32-character" token actually only has the randomness of ~24 bytes (192 bits), not 32 bytes (256 bits). since this function is now used everywhere (passwords, OAuth secrets, auth codes), might be worth generating enough bytes upfront so the final string actually has length chars worth of full entropy.

@sonarqubecloud

Copy link
Copy Markdown

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

You're right. The shared utility unintentionally changed token behavior by truncating the base64 output, which silently reduced token length and entropy.

I'll update the implementation to preserve the original behavior (44-char output for 32 random bytes) so downstream assumptions and randomness characteristics remain unchanged.

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@ManthanSiroya Centralizing our random string generation and adding defensive error handling to our cryptographic operations is a great step forward for cleaning up technical debt!

However, we have a blocker regarding how entropy and string limits are handled. The new utility mixes up byte length with character length. This causes our core authentication tokens (resets, registration verifications) to silently shrink from 44 down to 32 characters, which will conflict with database requirements and validation layers. Furthermore, truncating strings down this way strips out real cryptographic entropy.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh, Good catch — you were right about the byte-length vs character-length issue.

I’ve already updated the shared utility to preserve the original behavior (no truncation), so token length/entropy remain unchanged and existing downstream expectations (44-char tokens for 32 random bytes) are preserved.

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@ManthanSiroya did you commit the push ?

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh ,I Addressed the random string generation concern and pushed the fix.

Updated the shared GenerateRandomString utility to preserve the previous token behavior (length/entropy expectations) while keeping generation centralized. Also verified tests pass after the change.

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@ManthanSiroya i cant see your updated commit ?

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@ManthanSiroya Thanks for the update, but changing the test to expect 44 characters instead of 32 just hides the symptom. The length parameter must dictate the final character length of the string returned, not the input bytes before Base64 expansion. If returned strings are longer than our database column sizes, production writes will crash. Please add encoded[:length] slicing to utils.GenerateRandomString to guarantee strict character counts, and update the test to assert for exactly 32

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh ,I will do this and the another PR issue by tommorrow as I have to go now.
Thank You.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh,

I wanted to share an update regarding this PR. I’ve spent 5–6+ hours working through the refactor, review feedback, testing, and follow-up fixes around the shared random string utility and related behavior changes.

At this point, I’m unable to continue working on the remaining review items for this PR. I’ve already addressed the earlier requested fixes and pushed my latest changes.

If the completed work is acceptable, I’d appreciate consideration for merge and recognition of the effort already contributed. For the remaining requested improvements/comments, I kindly request creating separate follow-up issues so they can be handled independently later.

Thanks for the detailed reviews and guidance throughout the process.

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.

Duplicate generateRandomString functions in different files

2 participants