-
Notifications
You must be signed in to change notification settings - Fork 14
refactor: simplify SecureToken API by removing the *Must variants #171
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- 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
Summary of ChangesHello @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 Highlights
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this 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:
- Add an upper limit to the token length in
GenerateSecureTokento prevent potential DoS attacks from large memory allocations. - Use
fmt.Errorfinstead offmt.Sprintfwhen panicking, to panic with a structurederrorvalue instead of a raw string.
Overall, this is a good simplification of the API.
There was a problem hiding this 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
GenerateSecureTokenMustandSecureTokenMustfunctions - Changed
GenerateSecureTokenandSecureTokento returnstringand 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
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughGenerateSecureToken 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
- 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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this 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 (current32literal is also totally fine).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (3)
.github/workflows/benchmark.ymlis excluded by!**/*.yml.github/workflows/linter.ymlis excluded by!**/*.yml.github/workflows/test.ymlis 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 wrappederrorinpanic(fmt.Errorf(... %w ...))is the right shape for downstreamrecover()handling, and the newstring-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 != nilbranch 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.
Summary
Simplifies the SecureToken API by removing the
*Mustvariants and changing the base functions to panic on RNG failure instead of returning errors.Changes
GenerateSecureTokenMustandSecureTokenMustvariantsGenerateSecureTokenandSecureTokento returnstring(panic on failure)Why no
*Mustvariants?The
*Mustpattern is useful when a function can fail in ways the caller might want to handle. However, for cryptographic RNG:crypto/rand.Readpanics internally and never returns an errorThese 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
*Mustvariants is redundant.Why no upper length limit?
An earlier iteration considered capping token length at 4096 bytes. This was removed because:
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
References
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.