Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@sixcolors
Copy link
Member

@sixcolors sixcolors commented Dec 9, 2025

Summary

Simplifies the SecureToken API by removing the *Must variants and changing the base functions to panic on RNG failure instead of returning errors.

Changes

  • Remove GenerateSecureTokenMust and SecureTokenMust variants
  • Change GenerateSecureToken and SecureToken to return string (panic on failure)
  • Update tests and benchmarks accordingly

Why no *Must variants?

The *Must pattern is useful when a function can fail in ways the caller might want to handle. However, for cryptographic RNG:

  1. Go 1.24+: crypto/rand.Read panics internally and never returns an error
  2. Go 1.23 and earlier: RNG failures indicate a permanently broken system state:
    • Uninitialized entropy pool
    • Misconfigured VM without proper randomness source
    • Kernel-level issues

These aren't transient errors worth retrying—they indicate the system cannot provide cryptographic randomness at all. Panicking is the correct response, as silently continuing could produce weak/predictable tokens.

Since the base function now panics, having separate *Must variants is redundant.

Why no upper length limit?

An earlier iteration considered capping token length at 4096 bytes. This was removed because:

  1. Silent truncation is a security footgun: If a user requests 8192 bytes and silently gets 4096, that's a potential security issue
  2. Users should control their own token sizes: Different use cases have different requirements
  3. Application-level concern: If limits are needed, they should be enforced where the requirements are known

Breaking Change?

No. These functions were added in v2 which has not had a release yet, so no existing code depends on the error-returning signature.

Additional Changes

  • Go version requirement: Upgraded from Go 1.23 to Go 1.24.0
    • Required for crypto/rand panic behavior alignment
    • Required for tooling compatibility (gotestsum v1.13.0)
  • CI/CD updates:
    • Test matrix now includes Go 1.24.x and 1.25.x
    • Updated gotestsum from v1.12.0 to v1.13.0
    • Updated all workflow files to use Go 1.24+

References

Summary by CodeRabbit

  • Refactor
    • Token generation API simplified to return strings directly and now panics on generation failure, removing prior error-returning helpers (breaking change).
  • Tests
    • Unit, concurrency and benchmark tests updated to the new token behavior and to expect panics instead of error returns.
  • Chore
    • Test tooling version in build targets upgraded.

✏️ Tip: You can customize this high-level summary in your review settings.

- Remove GenerateSecureTokenMust and SecureTokenMust variants
- Change GenerateSecureToken and SecureToken to panic instead of returning errors
- Remove arbitrary length cap (let users control token sizes)

The Must variants are unnecessary because:
- On Go 1.24+, crypto/rand.Read panics internally and never returns errors
- On Go 1.23 and earlier, RNG failures indicate permanent system failures
  (uninitialized entropy, broken VM, etc.) that warrant panicking

No upper length limit because:
- Silent truncation would be a security footgun
- Users should control their own token sizes
- If a limit is needed, it should be enforced at the application level

See: https://go.dev/issue/66821
Copilot AI review requested due to automatic review settings December 9, 2025 18:27
@sixcolors sixcolors requested a review from a team as a code owner December 9, 2025 18:27
@sixcolors sixcolors requested review from ReneWerner87, efectn and gaby and removed request for a team December 9, 2025 18:27
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sixcolors, 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!

This pull request refactors the SecureToken API to streamline its usage and error handling. By changing the core functions to panic on critical RNG failures, it eliminates the need for separate *Must variants and clarifies that such failures represent a fundamentally broken system state rather than a recoverable error. This change improves API consistency and reflects modern Go practices for cryptographic randomness.

Highlights

  • API Simplification: The SecureToken API has been simplified by removing the GenerateSecureTokenMust and SecureTokenMust variants, as their functionality is now integrated into the base functions.
  • Error Handling Change: The GenerateSecureToken and SecureToken functions now panic on cryptographic random number generator (RNG) failure instead of returning an error. This aligns with Go 1.24+'s crypto/rand.Read behavior and treats RNG failures as unrecoverable system issues.
  • Test and Benchmark Updates: All associated tests and benchmarks have been updated to reflect the new API signatures and panic-on-failure behavior, ensuring correctness and performance measurement.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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
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 simplifies the SecureToken API by removing the *Must variants and making the base functions panic on cryptographic RNG failures. The reasoning for this change is sound, as such failures typically indicate a non-recoverable system state. The implementation is clean and the tests have been updated accordingly.

I have a couple of suggestions to further improve the robustness and code quality:

  1. Add an upper limit to the token length in GenerateSecureToken to prevent potential DoS attacks from large memory allocations.
  2. Use fmt.Errorf instead of fmt.Sprintf when panicking, to panic with a structured error value instead of a raw string.

Overall, this is a good simplification of the API.

Copy link

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 simplifies the SecureToken API by removing the *Must function variants and changing the base functions to panic on RNG failure instead of returning errors. This aligns with Go 1.24+ behavior where crypto/rand.Read panics internally, and addresses the fact that RNG failures indicate permanent system issues rather than transient errors.

  • Removed GenerateSecureTokenMust and SecureTokenMust functions
  • Changed GenerateSecureToken and SecureToken to return string and panic on failure
  • Updated all tests and benchmarks to use the simplified API

Reviewed changes

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

File Description
common.go Removed *Must variants, changed function signatures to return string instead of (string, error), and updated implementation to panic on RNG failure with detailed comments explaining the rationale
common_test.go Updated all test cases to use the new API signature without error handling, modified error simulation test to verify panic behavior, and updated benchmarks to use the simplified function names

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

- Upgrade minimum Go version from 1.23.0 to 1.24.0
- Update golang.org/x/tools to v0.40.0 to fix compilation errors
- This fixes the 'make test' error with tokeninternal.go
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 9, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

GenerateSecureToken and SecureToken were simplified to return plain strings and now panic on RNG failures; Must wrappers were removed. Tests were updated to new signatures and panic-based expectations. Makefile bumped gotestsum from v1.12.0 to v1.13.0.

Changes

Cohort / File(s) Summary
Token generation API refactor
common.go
GenerateSecureToken(length int) and SecureToken() signatures changed from (string, error) to string; error paths now panic (wrapped error); GenerateSecureTokenMust / SecureTokenMust removed.
Tests updated
common_test.go
Tests updated to call new string-returning APIs (removed error handling), removed Must usage, and assert panics for RNG-failure scenarios; benchmarks/concurrency tests switched accordingly.
Tooling version bump
Makefile
Updated gotest.tools/gotestsum from v1.12.0 to v1.13.0 in test/coverage targets.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay special attention to:
    • Repository-wide callers of GenerateSecureToken / SecureToken that expected (string, error).
    • Code that previously handled token-generation errors (now panics) and whether that behavior is acceptable.
    • Test changes that convert error checks to panic assertions, and concurrency/benchmark correctness.
    • Any API consumers outside the repo (if public) that rely on the removed Must wrappers.

Possibly related PRs

Suggested reviewers

  • gaby
  • efectn

Poem

🐇 I nibbled through the code tonight,

Tokens trimmed to strings so bright,
The Must hopped off, the errors leap,
Panic wakes where secrets sleep,
I twitch my nose — concise and light.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main change: removing the *Must variants from the SecureToken API to simplify it, which aligns with the primary modifications across all files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/simplify-secure-token-api

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.

- Upgrade gotestsum from v1.12.0 to v1.13.0
- This fixes compatibility with Go 1.24.0 and golang.org/x/tools v0.40.0
- Resolves the tokeninternal.go compilation error in 'make test'
This follows Go best practices for error handling - using fmt.Errorf with %w
allows recovery mechanisms to inspect error types and provides better error
chaining if panics are recovered and inspected.
@codecov
Copy link

codecov bot commented Dec 9, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.08%. Comparing base (e0d3c4a) to head (941a1d3).
⚠️ Report is 12 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #171      +/-   ##
==========================================
+ Coverage   84.98%   85.08%   +0.09%     
==========================================
  Files          12       12              
  Lines         966      959       -7     
==========================================
- Hits          821      816       -5     
+ Misses        125      123       -2     
  Partials       20       20              
Flag Coverage Δ
unittests 85.08% <100.00%> (+0.09%) ⬆️

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.

@sixcolors sixcolors changed the title refactor: simplify SecureToken API to panic on failure refactor: simplify SecureToken API by removing the *Must variants Dec 9, 2025
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: 0

🧹 Nitpick comments (1)
common.go (1)

120-124: SecureToken() delegation is clean; optional: reuse defaulting behavior.
If you want a single source of truth for the default length, return GenerateSecureToken(0) would leverage the existing “<= 0 defaults to 32” rule (current 32 literal is also totally fine).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4836c20 and 941a1d3.

⛔ Files ignored due to path filters (3)
  • .github/workflows/benchmark.yml is excluded by !**/*.yml
  • .github/workflows/linter.yml is excluded by !**/*.yml
  • .github/workflows/test.yml is excluded by !**/*.yml
📒 Files selected for processing (1)
  • common.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Compare
🔇 Additional comments (1)
common.go (1)

99-118: Panic payload and simplified API are correct; Go 1.24+/1.25 behavior verified.
The wrapped error in panic(fmt.Errorf(... %w ...)) is the right shape for downstream recover() handling, and the new string-only API is consistent.

Verification confirms: Go 1.24+ and Go 1.25 crypto/rand.Read indeed panic (via fatal + panic) before returning an error — never returns a non-nil error. The if _, err := randRead(bytes); err != nil branch is unreachable on Go 1.24+ but correctly preserved for Go 1.23 and earlier compatibility. The in-function comment accurately describes this dual-version behavior, so no clarification is needed.

@ReneWerner87 ReneWerner87 merged commit 577cbd4 into master Dec 12, 2025
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants