Skip to content

fix(rand): return errors for invalid random string inputs#360

Open
hazelmayank wants to merge 1 commit intomicrocks:masterfrom
hazelmayank:fix/rand-invalid-input-errors
Open

fix(rand): return errors for invalid random string inputs#360
hazelmayank wants to merge 1 commit intomicrocks:masterfrom
hazelmayank:fix/rand-invalid-input-errors

Conversation

@hazelmayank
Copy link
Copy Markdown
Contributor

@hazelmayank hazelmayank commented May 10, 2026

This PR fixes two panic cases in pkg/util/rand.

The helper functions String and StringFromCharset return (string, error), but a couple of invalid inputs were causing the process to panic instead of returning an error.

The panic cases were:

  • StringFromCharset(1, "") panicked because crypto/rand.Int was called with a max value of 0
  • String(-1) panicked because it tried to allocate a byte slice with a negative length

This PR adds input validation before allocation and random index generation, so invalid inputs now return clear errors instead of crashing.

Fixes #359

Valid behavior is preserved:

String(0) -> "", nil
String(n) -> string with length n, nil
StringFromCharset(0, "") -> "", nil
StringFromCharset(10, "abc") -> 10-character string using only a/b/c, nil

I also added unit tests for both valid and invalid inputs.



Test plan
 gofmt -l pkg/util/rand/rand.go pkg/util/rand/rand_test.go
 git diff --check -- pkg/util/rand/rand.go pkg/util/rand/rand_test.go
 go test -v ./pkg/util/rand/...
 make build-local

Note: I did not include go test -cover because my local Go toolchain reports go: no such tool "covdata". This PR is scoped only to pkg/util/rand and its tests.

Signed-off-by: hazelmayank <mayankjeefinal@gmail.com>
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.

pkg/util/rand helpers panic on invalid input instead of returning errors

1 participant