gofr-dev/gofr · error
failed to read random bytes: %w
Error message
failed to read random bytes: %w
What it means
generateRandomString (mock_oauth_server.go:164) reads random bytes via crypto/rand.Read to build random client credentials/tokens, and wraps any failure as "failed to read random bytes: %w". crypto/rand only fails when the OS entropy source is unavailable, which is effectively fatal for the process.
Source
Thrown at pkg/gofr/service/mock_oauth_server.go:164
for key, value := range r.Form {
if key == "client_id" || key == "client_secret" || key == "grant_type" {
continue
}
claims[key] = value
}
return claims
}
// Helper function to generate a random string.
func generateRandomString(length int) (token string, err error) {
// Generate random bytes
b := make([]byte, length)
_, err = rand.Read(b) // Use crypto/rand.Read
if err != nil {
return "", fmt.Errorf("failed to read random bytes: %w", err)
}
// Encode to base64 to make it URL-safe and human-readable (for tokens)
return base64.URLEncoding.EncodeToString(b), nil
}
View on GitHub (pinned to 187eb24962)
Solutions
- Fix the environment so crypto/rand works: ensure /dev/urandom exists or the getrandom syscall is permitted by the container/seccomp profile.
- Read the wrapped %w cause to distinguish ENOENT on /dev/urandom from fd exhaustion (raise ulimit -n).
- Run tests on a host/container with a working entropy source instead of a hardened sandbox.
- If reproducible only in CI, compare the CI image with the working local image.
Example fix
// before (docker run) FROM scratch // no /dev, rand.Read fails // after FROM golang:1.22 // standard /dev/urandom present
Defensive patterns
Strategy: try-catch
Validate before calling
if _, err := rand.Read(make([]byte, 1)); err != nil {
return fmt.Errorf("crypto/rand unavailable in this environment: %w", err)
} Try / catch
token, err := generateRandomString(32)
if err != nil {
var pe *os.PathError
if errors.As(err, &pe) { /* entropy source missing — fix container image */ }
return fmt.Errorf("cannot create mock credentials: %w", err)
} Prevention
- Use standard base images that ship /dev/urandom.
- Do not apply seccomp/AppArmor profiles that block getrandom(2) in test containers.
- Raise open-file limits if tests run with high parallelism.
- Fail fast in TestMain with a clear message when rand.Read fails.
When it happens
Trigger: Calling generateRandomString (via oAuthConfigForTests during mock server setup) when rand.Read fails — e.g. /dev/urandom unavailable in a stripped-down container or sandbox, or fd exhaustion preventing opening the entropy source.
Common situations: Running tests in minimal Docker images/chroots without /dev/urandom; seccomp policies blocking getrandom(2); resource-limit exhaustion under heavy parallel test runs.
Related errors
AI-assisted analysis of gofr-dev/gofr@187eb24962 (2026-09-01).
Data as JSON: /api/errors/3c1bc47818c6b806.
Report an issue: GitHub.